package index; use lib '.'; #use me; use loyalty; use Barcode::Code128; use PDF::Reuse; use Time::HiRes qw(gettimeofday tv_interval); use YAML::XS qw/LoadFile Load/; use CGI::Carp qw(fatalsToBrowser); #use File::Copy::Recursive qw(dircopy); use File::Find; use File::Path qw(mkpath); use File::Copy; use LWP::Simple; use Data::Dumper; use Net::SMTP; use Calendar::Simple; our $folder = '/wwwroot/extranet/'; my $font_dir = "/wwwroot/extranet/pdflabels/ttf/"; our $sessiondir = '/wwwsessions'; our $smtpserver = slurpfile("smtp.conf"); our $dbuser = 'root'; our $dbpassword = 'fbg4ips'; our $dbhost = '127.0.0.1'; our $tdir = $folder; #use Apache2; use MD5T; # blamamura_mode = 1 looks for html files, 2 looks in Blamamura.pm our $blamamura_mode = 2; #use blamamura = 2 use Blamamura; use Fcntl; use strict; use lflag; use Time::localtime qw(localtime); use Time::Local; use CGI qw/:standart/; use CGI::Session; use CGI::Session::Driver::mysql; #use CGI::Session::Serialize::default; use Template; use Template::Plugin::CGI; use Apache::DBI; use URI::Escape; #~ use anatoli; #~ use ck; #use settings; #No need.... use SDBM_File; use calendarz; #/to fly away use turnoversm; #use printsetup; use Printit; use JSON; #Import a new global variable to replace old settings our %sys_settings; our $socketflag; our $qnafile = 'data/qna.txt'; our %issuetypes = (1=>"Opening Stock",2=>"Closing Stock"); #~ our $socketflag = "1"; #~ $socketflag = "0" if ($ck::CC_status > 0); # expires our $edit_stock_items = $lflag::edit_stock_items; our $copycstock = $lflag::copycstock; #OLD settings need to take care our $show_noqty_stock = $sys_settings{'show_noqty_stock'};#$settings::show_noqty_stock; our $currency; #if ($settings::currency ne "") {$currency=$settings::currency} else {$currency = "$currency"}; if ($sys_settings{'currency'} ne "") {$currency=$sys_settings{'currency'}} else {$currency = "$currency"}; our $previewpurchases = 1; #/in stock control our $pme=&fpme('"\DPROTECT_PERL_FOLDER_FILTER_KEY%@$%%$REKEY::12FFDD21111122333DFFDDFFDDF333111111DDDDDCABAB211321:::REGISTERED:::ANATOLIRADULOV:::radulov.com+till.opentill.com"'); our $q; our $tmprn; our %tmprns; #/ a copy for each printer / header, footer may differ for each printer device our %psubst;# = %printsetup::psubst; our %prntype;# = %printsetup::prntype; #&logit("PSUBST:".Dumper(\%psubst)); #&logit("PSUBST:".Dumper(\%prntype)); #/extranet is not supposed to open drawers #our $thisshop;# = $settings::shop_id; #/superuser = 0 #our $abrevi;# = $settings::abrev; #/shop abreviature #/my $database = "server"; #our $database;# = "$abrevi"."_$thisshop"; #our $menu_db;# = $database; #our ($results, $subresults, $subresults1, $ref,$ref1,$ref2,$subref,$subref1); #/ database our %account_types = ( 1=> "COST OF SALES", 2=> "CONSUMABLE ASSETS (EXPENCES)", 3=> "FIXED ASSETS REGISTER (MOVABLES)" ); our %cacheflag; our %stocktypes_account_type; our %stocktypes; our %stocktypes_breakdown; our %menutypes; our %bins; our %tax; our %btax; our %departments; our %stockcats; our %wstatus = (1=>"active", 2=>"non-active"); our %months = (1 => "January", 2 => "February", 3 => "March", 4 => "April", 5 => "May",6 => "June", 7 => "July", 8 => "August", 9 => "September", 10 => "October", 11 => "November", 12 => "December"); our %weekdays = (0=>"Sunday",1=>"Monday",2=>"Tuesday",3=>"Wednesday",4=>"Thursday",5=>"Friday",6=>"Saturday"); our @wdays = ( "Mn","Tu","We","Th","Fr","Sa","Su"); our %alarm_repeats = (1 => 'ONCE OFF',2 => 'EVERY DAY',3 => 'EVERY WEEK',4 => 'EVERY MONTH',5 => 'EVERY YEAR'); our %alarm_repeats_when = (1 => 'Never',2 => 'Tomorrow',3 => 'Next Week',4 => 'Next Month',5 => 'Next Year'); our %priority = (4 => 'HIGH',3 => 'MEDIUM',2 => 'NORMAL',1 => 'ON STAND BY'); our %notecases = (); our %yes_no = ( 1 => "yes", 2 => "no" ); our %units = (1=>"kg", 2=>"litre", 3=>"each", 4=>"meter(s)", 5=>"sq.meter(s)", 6=>"hour(s)"); our %unitalias = (1=> ["g", "0.001", 1], 2=> ["ml", "0.001", 2], 3=> ["each", "1", 3], 4=> ["piece(s)", "1", 3], 5=> ["portion(s)", "1", 3], 6=> ["can(s)", "1", 3], 7=> ["kg", "1", 1], 8=> ["l", "1", 2], 9=> ["loaf(s)", "1", 3], 10=> ["slice(s)", "1", 3], 11=> ["cube(s)", "1", 3], 12=> ["spoon(s)", "1", 3], 13=> ["cup(s)", "1", 3], 14=> ["pinch(es)", "1", 3], 15=> ["box(es)", "1", 3], 16=> ["packet(s)", "1", 3], 17=> ["box(es)", "1", 3], 18=> ["unit(s)", "1", 3], 19=> ["percent(s)", "0.01", 3], 20=> ["ton(s)", "1000", 1], 21=> ["m", "1", 4], 22=> ["cm", "0.01", 4], 23=> ["mm", "1", 4], 24=> ["kilometer(s)", "1000", 4], 25=> ["sq.m", "1", 5], 26=> ["sq.cm", "0.0001", 5], 27=> ["are(s)", "100", 5], 28=> ["hectare(s)", "10000", 5], 29=> ["sq.kilometer(s)","1000000",5], 30=> ["hour(s)", "1", 6], 31=> ["minute(s)", 1/60, 6], 32=> ["second(s)", (1/60)/60, 6] ); #NUMBER SYSTEM ID CODES my $dprefixx = $sys_settings{'dprefix'}; my %documents = ( 1 => ["Tax Invoice", $dprefixx."INV"], 2 => ["Proforma Invoice", $dprefixx."PRO"], 3 => ["Credit Note", $dprefixx."CRN"], 4 => ["Purchase Order", $dprefixx."POR"], 5 => ["Supplier Invoice", ""], 6 => ["Supplier Credit Note", $dprefixx."SCRN"], 7 => ["Inter Branch Transfer(OUT)",$dprefixx."IBT-OUT"], 8 => ["Goods Received Voucher", $dprefixx."GRV"], 9 => ["Inter Branch Transfer (IN)", $dprefixx."IBT-IN"], 10 => ["PDF Labels Document", $dprefixx."PDFL"], 11 => ["Loyalty Cards Document", $dprefixx."LCL"], 12 => ["User Cards Document", $dprefixx."UBC"], 13 => ["Power User Cards Document", $dprefixx."UBC"], ); my %sbt_documents = ( 1 => "Storage Bin Transfer", 2 => "Goods Received Voucher", 3 => "Supplier Credit Note", 4 => "Inter Branch Transfer(OUT)", 5 => "Used in Production", #debit stock for producing 6 => "Produced Items", #credit stock with produced 7 => "From Disassembled", #credit stock from disasembled 8 => "Disassembled" #debit stock with disasembled ); my %sbt_transaction_types = ( 0 => "Move Stock", 1 => "Produce Stock", 2 => "Disassemble Stock" ); our %clienttypes = ( 1 => 'debtor', 3 => 'takeaway', 4 => 'loyalty' ); our $tillmode=1; our $tillprinter = $sys_settings{'intranet_printer'}||"T1"; #/func in supervisor mode #print "
$tillprinter
"; #my ($results, $subresults, $subresults1, $ref,$ref1,$ref2,$subref,$subref1); #/ database our %zebra = (-1 => "#FFFFFF", 1=>"#D2D2D2"); our $zindex =1; our ($linecolor,$cellcolor); our $count; our $onload; our $onsubmit; our $selectioncolor = "#BBCFE8"; our $errorcolor = "#FFC4C4"; our $calccolor = "#FFFAD5"; our $headcolor = "#B89147"; our $weekcolor = "#CCF8FF"; #/########################################## our %ps; $ps{red} = chr(27).chr(114).chr(1); $ps{black} = chr(27).chr(114).chr(0); #/double width $ps{dw} = chr(27)."!".chr(32); #/double height $ps{dh} = chr(27)."!".chr(16); #/boldish $ps{b} = chr(27)."!".chr(8); #/normal $ps{n} = chr(27)."!".chr(0); #/condensed $ps{c} = chr(27)."!".chr(1); #/underline $ps{u} = chr(27).chr(45).chr(49); #/open cash drawer $ps{od} = chr(27).chr(112).chr(48).chr(40).chr(40); #/cut paper #/ not working $ps{cp} = chr(27).chr(112); $ps{cp} = chr(29)."VB"; #/minuses $ps{minuses} = "-"x33; #/feed $ps{feed} = "\n\n\n\n\n\n"; our $pmax = 33; #/########################################### our %icons; $icons{det} = "";#/\"Detach $icons{cal} = "\"Calendar"; $icons{d} = "\"Delete"; $icons{m} = "\"Modify"; $icons{i} = "\"\""; $icons{corn} = ""; $icons{thick} = ""; $icons{w} = ""; $icons{lock} = "\"Lock\""; $icons{unlock} = "\"Unlock\""; $icons{subrecipe} = "\"subrecipe\""; $icons{mainrecipe} = "\"subrecipe\""; our %table; #/define table styles $table{start} = qq ~ "; $temphtml .= ""; $temphtml .= ""; $results = $dbh->prepare("SELECT * FROM tax ORDER BY id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= "
Jump to PLU Items
"; $temphtml .= ""; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "Closing Stock Undo") { my $temphtml; $template =~ s/\@title\@/UNDO STOCK TAKE/sgi; $temphtml .= "
"; $onload="document.form1.name.focus();"; if ($R::command eq "Proceed") { if (! $R::name or ! $R::reason or ! $R::take) { $mess .= "$error PLEASE PROVIDE NAME, REASON AND SELECT STOCK TAKE DATE!"; $formvars{name}=$R::name; $formvars{reason}=$R::reason; $temphtml .= getform("unlock", \%formvars); $temphtml =~ s/\@formtitle\@/UNDOING CLOSING STOCK/gsi; $temphtml =~ s/\@action\@/$R::action/gsi; $temphtml =~ s/\@subaction\@/$R::subaction/gsi; $temphtml .= ""; } else { my ($type,$stamp) = split /\|/, $R::take; my $results = $dbh->prepare(" select * from cstock where date='$stamp' and stocktype = $type; ") or die $results->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $tempdb{"cs$type"."_$ref->{stockitems_id}"}=$ref->{qty}; } $results = $dbh->prepare("INSERT INTO unlocked (shop_id,date,datestamp,name,reason,section) values ('$shop{id}','$stamp',CURRENT_DATE,'$R::name',?,2);") or die $results->errstr(); $results->execute("STOCK: $stocktypes{$database}{$type} STAMP: $stamp \n REASON: \n".$R::reason) or die $results->errstr(); $results = $dbh->prepare(" UPDATE cstock SET f_status=101 where shop_id = $shop{id} and stocktype=$type and date = '$stamp';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $R::reason =~ s/\n/
/sgi; $temphtml .= "STOCK: $stocktypes{$database}{$type}
STAMP: $stamp
UNDONE BY: $R::name
REASON: $R::reason

NOTE THAT THE DELETED STOCK ON HAND IS STORED AS NOT FINALIZED ON YOUR CLOSING STOCK EDITING SCREEN.
Please use the main menu to continue. "; } } else { $temphtml .= "Please select the stock take which you would like to undo:


"; $temphtml .= getform("unlock", undef); $temphtml =~ s/\@formtitle\@/UNDOING CLOSING STOCK/gsi; $temphtml =~ s/\@action\@/$R::action/gsi; $temphtml =~ s/\@subaction\@/$R::subaction/gsi; $temphtml .= ""; } $temphtml .= "
"; $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "accounts") { my $file = "$tdir/account.html"; my $output; my $ttemplate = Template->new(ABSOLUTE => 1,COMPILE_EXT => '.ttc'); my $vars = { message => "", sessionusername => $username }; my $temphtml = $ttemplate->process($file, $vars, \$output) || die "Template process failed: ", $ttemplate->error(), "\n"; $template =~ s/\@content\@//gsi; $template =~ s/\@title\@/Welcome/gsi; $template = ""; print $output; } elsif ($socketflag == 1 and $R::action eq "Daily Cash-up") { my $temphtml; my %calc; $template =~ s/\@title\@/Daily Cash-up/sgi; $temphtml = "
"; if ($R::subaction eq "Create New Cash-up") { my %sqldate = dateforsql($R::date); $onload="document.form1.name.focus();"; if ($R::command eq "Create") { #/ query for cashup existance $results = $dbh->prepare("SELECT id,name FROM dcash WHERE f_status<100 and shop_id = $shop{id} and DAYOFMONTH(date)='$sqldate{day}' and MONTH(date)='$sqldate{month}' and YEAR(date)='$sqldate{year}';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $results->finish(); if ($sqldate{day} eq "" or $sqldate{month} eq "" or $sqldate{year} eq "") { $mess = qq|$error Date incorrect!!!|; $formvars{date} = $R::date || $date; $formvars{name} = $R::name; $formhtml = getform("dcash", \%formvars); $temphtml .= $formhtml; } elsif (! $R::name) { $mess = qq|$error Cash-up by field is missing!!!|; $formvars{date} = $R::date || $date; $formhtml = getform("dcash", \%formvars); $temphtml .= $formhtml; } elsif ($ref->{id}) { $mess = qq|$error Cash-up for $R::date exists it was created by $ref->{name}!!!|; $formvars{date} = $R::date || $date; $formvars{name} = $R::name; $formhtml = getform("dcash", \%formvars); $temphtml .= $formhtml; } else { #/check whether all the waitrons has been cached up #/ foreach waiter select the last till id and then check whether there is trade for the waiter after this ID my %activity; my %opentables; my %waitronname; my %tabledetails; $results = $dbh->prepare("select id,number from tilltables where shop_id='$shop{id}' and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while($ref = $results->fetchrow_hashref()) { $tabledetails{number}{$ref->{id}} = $ref->{number}; } $results = $dbh->prepare("select id,name from waitron where f_status<101;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while($ref = $results->fetchrow_hashref()) { $waitronname{$ref->{id}} = $ref->{name}; #/ all names #/ retreive last cashup mark $subresults = $dbh->prepare("select max(last_tillid) last_tillid from dcashitems where waitron_id = '$ref->{id}' and f_status<101 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $lasttillid = $subref->{last_tillid}; #/retreive sales activity $subresults = $dbh->prepare("select count(ttod.id) activity from tillordersdetails ttod, tillorders tto, tillinvoices inv where ttod.shop_id=$shop{id} and tto.shop_id=$shop{id} and inv.shop_id=$shop{id} and tto.f_status < 101 and ttod.f_status < 101 and ttod.id > '$lasttillid' and ttod.waitron_id = '$ref->{id}' and ttod.orders_id = tto.id and ttod.stamp > DATE_SUB(CURRENT_DATE, INTERVAL 10 day) and tto.confirm_status = 3 and inv.id = ttod.invoice and (inv.voided is NULL or inv.voided = 0 or inv.voided = 2) ;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); if ($subref->{activity}) {$activity{$ref->{id}} = 1} #/retreive open tables #/TODO - only active from tilltables my @alltables; $subresults = $dbh->prepare("select distinct table_id from tilltableops where shop_id=$shop{id} and tilltableops.stamp > DATE_SUB(CURRENT_DATE, INTERVAL 10 day) and waitron_id='$ref->{id}' and f_status<101;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { push @alltables, $subref->{table_id}; } foreach my $tbl (@alltables) { $subresults = $dbh->prepare(" select action from tilltableops where shop_id=$shop{id} and f_status < 101 and waitron_id = '$ref->{id}' and table_id='$tbl' order by id desc limit 1;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); if ($subref->{action} != 2 and $subresults->rows > 0) { push @{ $opentables{$ref->{id}} } , $tabledetails{number}{$tbl}; } } } if ((! scalar keys %activity) and (! scalar keys %opentables)) { $subresults = $dbh->prepare("select max(id) last_tillid from tillordersdetails where f_status<101;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $lasttillid_all = $subref->{last_tillid}; #/create virtual cashup $mess = "New Cash-up created for the following date: ".$R::date." by ".$R::name; $results = $dbh->prepare("delete from tillonholds;;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #/insert the new cash-up here: $R::name=~ tr/a-z/A-Z/; $results = $dbh->prepare("INSERT INTO dcash (name,date,time,shop_id,last_tillid) values ('$R::name','$sqldate{year}-$sqldate{month}-$sqldate{day}',CURRENT_TIME,'$shop{id}', '$lasttillid_all');") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } else { $mess = "PROBLEM CREATING CASHUP"; if (scalar keys %activity) { $temphtml .= qq|ERROR - USERS NOT CASH-UP FROM PREVIOUS CASH-UP
|; $temphtml .= "
  • $waitronname{$_}" foreach (keys %activity); $temphtml .= "
    "; } if (scalar keys %opentables) { $temphtml .= qq|ERROR - TABLES STILL OPEN FOR USERS
    |; foreach my $waitron (keys %opentables) { $temphtml .= "
  • $waitronname{$waitron} Table(s): " ; foreach my $tblnum (@{$opentables{$waitron}}) { $temphtml .= " $tblnum"; } } $temphtml .= "
    "; } } } #/last else of creation checkup #/ command Create } else { #/ print the form for this subaction - Create New Cash-up $mess = "Please provide the information required:"; $formvars{date} = $R::date || $date; $formhtml = getform("dcash", \%formvars); $temphtml .= $formhtml; } $temphtml .= "
    "; } #/ end subaction Create New Cash-up if ($R::subaction eq "editcash") { $temphtml .= qq~ ~; #/ prepare waitrons my (%waitrons, %allwaitrons, %demowaitrons); #/ note: sorting of the waitrons must be done using array not hash! my $results = $dbh->prepare("SELECT id, name,active FROM waitron WHERE f_status<100 AND shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $allwaitrons{$ref->{id}} = $ref->{name}; $waitrons{$ref->{id}} = $ref->{name} if ($ref->{active} == 1); $demowaitrons{$ref->{id}} = 1 if ($ref->{name} =~ /!DEMO!/sgi) } $onload=""; %calc=(); #/RESET my $lockflag; my $pettycash; my $pdate; my $thisdate_lasttillid; $results = $dbh->prepare("SELECT id,pettycash,name, DAYOFMONTH(date) day, MONTH(date) month, YEAR(date) year, last_tillid, date,f_lock FROM dcash WHERE f_status<100 and shop_id = $shop{id} and id=$R::id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $cashupdate; $cashupdate->{day} = $ref->{day}; $cashupdate->{month} = $ref->{month}; $cashupdate->{year} = $ref->{year}; $lockflag = $ref->{f_lock}; $thisdate_lasttillid = $ref->{last_tillid}*1; $pdate = $ref->{date}; $pettycash = $ref->{pettycash}; $temphtml .="
    "; $temphtml .= "You are editing Cash-up for $ref->{day} $months{$ref->{month}} $ref->{year} created by $ref->{name}

    "; #next tillid $results = $dbh->prepare("select last_tillid from dcash where last_tillid > '$thisdate_lasttillid' and f_status<100 and shop_id = $shop{id} limit 1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $nextdate_lasttillid = $ref->{last_tillid}*1; $temphtml .= qq~ ~ if ($lockflag == 1); #/ Javascript for IE #/document.all.td_avrnet.innerHTML=pr(avrnet); #/document.all.td_grossto.innerHTML=pr(grossto); #/document.all.td_nettoexc.innerHTML=pr(nettoexc); #/document.all.td_vat.innerHTML=pr(vat); #/document.all.td_cash.innerHTML=pr(cash); #/document.all.td_grosscash.innerHTML=pr(grosscash); #/## COMMANDS CASHUP #/AUTO COMMANDS if (($R::command eq "Cash Up User" and $R::autocash > 0) and $demowaitrons{$R::autocash} != 1) { my $lastcashuptillid; $subresults = $dbh->prepare("select last_tillid from dcashitems where waitron_id=$R::autocash and f_status<101 order by id desc limit 1; ") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $lastcashuptillid = $subref->{last_tillid} / 1; #verify for open table first. $results = $dbh->prepare("SELECT waitron.name, t1.table_id, tilltables.type, tilltables.number, t1.action, t1.id, t1.waitron_id FROM tilltableops AS t1, (SELECT MAX(id) AS maxid FROM tilltableops WHERE f_status< 100 GROUP BY table_id) AS t2, tilltables, waitron WHERE waitron_id = ? AND t1.f_status< 100 AND t1.id = t2.maxid AND tilltables.id = t1.table_id AND t1.waitron_id = waitron.id AND t1.action = 1 GROUP BY t1.table_id; ;") or die $dbh->errstr(); $results->execute($R::autocash) or die $results->errstr(); ######## Cashup possible if (! $results->rows) { my @my_invoices; my @my_finaldata; $results = $dbh->prepare(" SELECT MAX(tillinvoices_id) lastinvoice FROM dcashinvoices WHERE dcashitems_id = (SELECT MAX(id) FROM dcashitems WHERE waitron_id=? AND f_status < 101); ;") or die $dbh->errstr(); $results->execute($R::autocash) or die $results->errstr(); my $lastinvoice = $ref->{lastinvoice}; $results = $dbh->prepare(" SELECT DISTINCT todds.invoice FROM tillordersdetails todds left join tillinvoices inv on inv.id = todds.invoice WHERE todds.id > ? AND todds.invoice > 0 and todds.waitron_id = ? and (inv.voided is NULL or inv.voided = 2 or inv.voided = 0) and inv.f_status < 101 ORDER BY todds.invoice; ;") or die $dbh->errstr(); $results->execute($lastcashuptillid, $R::autocash) or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { push @my_invoices, $ref->{invoice}; } #~ open(DDD , ">/dddd.txt"); foreach my $winv (@my_invoices) { $results = $dbh->prepare(" select inv.client_id, inv.account, inv.discount, inv.cash, inv.ccard, inv.ccardtype, inv.cheque, inv.id inv, inv.void_reason, inv.supervised_by, inv.voided, time(inv.stamp) invtime, date(inv.stamp) invdate from tillinvoices inv where id = ? and f_status < 101 ;") or die $dbh->errstr(); $results->execute($winv) or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $ldata; $ldata->{client_id} = $ref->{client_id}; $ldata->{account} = $ref->{account}; $ldata->{discount} = $ref->{discount}; $ldata->{cash} = $ref->{cash}; $ldata->{ccard} = $ref->{ccard}; $ldata->{ccardtype} = $ref->{ccardtype}; $ldata->{cheque} = $ref->{cheque}; $ldata->{inv} = $ref->{inv}; $ldata->{void_reason} = $ref->{void_reason}; $ldata->{supervised_by} = $ref->{supervised_by}; $ldata->{voided} = $ref->{voided}; $ldata->{invtime} = $ref->{invtime}; $ldata->{invdate} = $ref->{invdate}; my @refs; $results = $dbh->prepare(" select (ttod.price*ttod.qty) price, (ttod.discount*ttod.qty) plu_discount, ttod.price uprice, ttod.qty qty, ttod.yield yield, ttod.name name, ttod.orders_id, ttod.plu from tillordersdetails ttod where invoice = ? and f_status < 101 and plu > 0 ;") or die $dbh->errstr(); $results->execute($winv) or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { push @refs, { 'price' => $ref->{price}, 'plu_discount' => $ref->{plu_discount}, 'uprice' => $ref->{uprice}, 'qty' => $ref->{qty}, 'yield' => $ref->{yield}, 'name' => $ref->{name}, 'orders_id' => $ref->{orders_id}, 'plu' => $ref->{plu} }; } foreach my $todds (@refs) { $ldata->{price} = $todds->{price}; $ldata->{plu_discount} = $todds->{plu_discount}; $ldata->{uprice} = $todds->{uprice}; $ldata->{qty} = $todds->{qty}; $ldata->{yield} = $todds->{yield}; $ldata->{name} = $todds->{name}; $ldata->{orderid} = $todds->{orders_id}; $ldata->{plu} = $todds->{plu}; $results = $dbh->prepare(" select type, id menuid from menu where id = ? ;") or die $dbh->errstr(); $results->execute($todds->{plu}) or die $results->errstr(); $ref = $results->fetchrow_hashref(); $ldata->{type} = $ref->{type}; $ldata->{menuid} = $ref->{menuid}; $results = $dbh->prepare(" select confirm_status, tableops_id from tillorders where f_status < 101 and id = ? ;") or die $dbh->errstr(); $results->execute($todds->{orders_id}) or die $results->errstr(); $ref = $results->fetchrow_hashref(); my ($confirm_status, $tableops_id) = ($ref->{confirm_status}, $ref->{tableops_id}); if ($confirm_status == 3) { $results = $dbh->prepare(" select tabops.visitors covers, tabops.id tabopsid, tabops.table_id from tilltableops tabops where f_status < 101 and id = ? ;") or die $dbh->errstr(); $results->execute($tableops_id) or die $results->errstr(); my $ref = $results->fetchrow_hashref(); $ldata->{covers} = $ref->{covers}; $ldata->{tabopsid} = $ref->{tabopsid}; my $table_id = $ref->{table_id}; $results = $dbh->prepare(" select tilltables.type ttype, tilltables.id tilltables_id from tilltables where f_status < 101 and id = ? ;") or die $dbh->errstr(); $results->execute($table_id) or die $results->errstr(); $ref = $results->fetchrow_hashref(); $ldata->{ttype} = $ref->{ttype}; $ldata->{tilltables_id} = $ref->{tilltables_id}; push @my_finaldata, { %{$ldata} }; # use anonymous hash ref to create a copy of the hash #~ foreach my $kk ( keys %{$ldata} ) { #~ print DDD "$kk\t$ldata->{$kk}\t"; #~ } #~ print DDD "\n"; } #confirm_status = 3 } # items } #invoices #~ close (DDD); #~ open (DDD, ">/dddd.dump"); #~ print DDD Dumper(\@my_finaldata); #~ close DDD; #old cashup---------- #~ $results = $dbh->prepare(" #~ select #~ inv.client_id client_id, #~ inv.account account, #~ inv.discount discount, #~ inv.cash cash, #~ inv.ccard ccard, #~ inv.ccardtype ccardtype, #~ inv.cheque cheque, #~ (ttod.price*ttod.qty) price, #~ ttod.price uprice, #~ (ttod.discount*ttod.qty) plu_discount, #~ ttod.qty qty, #~ ttod.yield yield, #~ inv.id inv, #~ inv.void_reason void_reason, #~ inv.supervised_by supervised_by, #~ menu.type type, #~ menu.id menuid, #~ inv.voided voided, #~ tto.id orderid, #~ tabops.visitors covers, #~ tilltables.type ttype, #~ tilltables.id tilltables_id, #~ ttod.name name, #~ tabops.id tabopsid, #~ IF (menu.novat, 0,ttod.price/(100 + $cvat)*$cvat*qty) vat, #~ time(inv.stamp) invtime, #~ date(inv.stamp) invdate #~ from #~ tillordersdetails ttod, #~ tillorders tto, #~ menu, #~ tillinvoices inv, #~ tilltableops tabops, #~ tilltables #~ where #~ ttod.f_status < 101 #~ and tto.f_status <101 #~ and ttod.waitron_id = $R::autocash #~ and ttod.id > '$lastcashuptillid' #~ and tabops.id = tto.tableops_id #~ and tilltables.id = tabops.table_id #~ and ttod.orders_id = tto.id #~ and tto.confirm_status=3 #~ and ttod.plutype = 1 #~ and ttod.menusource = 1 #~ and menu.id = ttod.plu #~ and inv.id = ttod.invoice #~ and (inv.voided is NULL or inv.voided = 2 or inv.voided = 0) #~ ;") or die $dbh->errstr(); #~ $results->execute() or die $results->errstr(); my $dci_turnover_total; my %dcinv_total_turnover; my %cash_control=(); my %costcenter_turnovers; my %bills; my %client_id; my %returnsfromwaitrons; my %returnsauthor; my %void_reasons; my %invoicestamp; #determine itemcount my %itemCnts; my %discounts; foreach my $ref (@my_finaldata){ $discounts{$ref->{inv}} = $ref->{discount}; if(!($ref->{plu_discount} > 0)){ $itemCnts{$ref->{inv}} += $ref->{qty}; } } my $itemDiscount=0; my %tax_cache; foreach my $ref (@my_finaldata) { #old #~ while ($ref = $results->fetchrow_hashref()) { #retreive tax for the PLU if (! exists $tax_cache{$ref->{menuid}}) { $subresults = $dbh->prepare(" select * from menu_tax where menu_id='$ref->{menuid}';") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $tax_cache{$ref->{menuid}} += $tax{$database}{$subref->{tax_id}}{tax}; } } if($ref->{ttype} == 4){ $ref->{vat} = 0; }else{ #FORMULA dcashvat: # (price - discount)/(100 + vat))*vat # (((ttod.price - ((ttod.discount/itemCnt)*ttod.qty))/(100 + vat)*vat if($ref->{plu_discount} > 0){ $ref->{vat} = (($ref->{price} - $ref->{plu_discount})/(100 + $tax_cache{$ref->{menuid}}))*$tax_cache{$ref->{menuid}} if ($tax_cache{$ref->{menuid}} > 0); }else{ #$itemDiscount = $discounts{$ref->{inv}}/$itemCnts{$ref->{inv}}; #BY STEVEN 2019 $itemDiscount = $discounts{$ref->{inv}}/$itemCnts{$ref->{inv}} if $itemCnts{$ref->{inv}} >0; $ref->{vat} = (($ref->{price} - ($itemDiscount * $ref->{qty}))/(100 + $tax_cache{$ref->{menuid}}))*$tax_cache{$ref->{menuid}} if ($tax_cache{$ref->{menuid}} > 0); } } $client_id{$ref->{inv}} = $ref->{client_id}; #total turnovers #DCASHITEMS TURNOVER TOTAL $dci_turnover_total += $ref->{price}; #DCASHINVOICES TURNOVER TOTAL $dcinv_total_turnover{$ref->{inv}} += $ref->{price}; $cash_control{discounts}{$ref->{inv}} = 0; #CONTROLS if($ref->{voided} == 2) { $cash_control{returns}{$ref->{inv}} += $ref->{price}; $void_reasons{$ref->{inv}} = $ref->{void_reason}; } else { if ($ref->{ttype} == 4) { #4$cash_control{staffpromos}{$ref->{inv}} += $ref->{price}; #/ 4 = staff $cash_control{staffpromos}{$ref->{inv}} += $ref->{price} unless $ref->{voided} ==1; #/ 4 = staff } else { $cash_control{accounts}{$ref->{inv}} = $ref->{account} if ($ref->{account}!=0 ); $cash_control{discounts}{$ref->{inv}} = $ref->{discount} if ($ref->{discount}!=0); $cash_control{plu_discount}{$ref->{inv}} += $ref->{plu_discount}; #if ($ref->{ccardtype} eq "eft" and $ref->{ccard}!=0) { #CHANGE STEVEN 2019-06-03 if (($ref->{ccardtype} eq "eft" || $ref->{ccardtype} eq "zapper" || $ref->{ccardtype} eq "snapscan") and $ref->{ccard}!=0) { $cash_control{eft}{$ref->{inv}} = $ref->{ccard}; } elsif ($ref->{ccard}!=0) { $cash_control{creditcards}{$ref->{inv}} = $ref->{ccard}; } $cash_control{cheques}{$ref->{inv}} = $ref->{cheque} if ($ref->{cheque}!=0); } } # print "$ref->{vat} DEBUG"; $cash_control{vat}{$ref->{inv}} += $ref->{vat} if ($ref->{vat}); $cash_control{date}{$ref->{inv}} = $ref->{invdate}; $cash_control{time}{$ref->{inv}} = $ref->{invtime}; $cash_control{tilltables_id}{$ref->{inv}} = $ref->{tilltables_id}; $bills{$ref->{inv}}{covers}{$ref->{covers}} = 1 if ($ref->{ttype} != 4 and ! $ref->{voided}); $cash_control{supervised_by}{$ref->{inv}} = $ref->{supervised_by} if ($ref->{supervised_by}>0); #DCASHTURNOVERS TURNOVER TOTAL $costcenter_turnovers{$ref->{inv}}{$ref->{type}}{total_turnover} += ($ref->{price}-$ref->{vat}); $costcenter_turnovers{$ref->{inv}}{$ref->{type}}{total_staffpromo} += ($ref->{price} - $ref->{vat}) if ($ref->{ttype} == 4); $costcenter_turnovers{$ref->{inv}}{$ref->{type}}{total_returns} += ( $ref->{price} - $ref->{vat}) if ($ref->{voided} == 2); if ($ref->{plu_discount} != 0 and $ref->{price} != 0) { $costcenter_turnovers{$ref->{inv}}{$ref->{type}}{plu_discounts} += ( $ref->{plu_discount} - $ref->{vat}*($ref->{plu_discount}/$ref->{price}) ); } $costcenter_turnovers{$ref->{inv}}{$ref->{type}}{vat} += $ref->{vat}; } #distribute discount not from PLUS by Stock Types and calculate total discount per cost center foreach my $invoice (keys %{$cash_control{discounts}}) { my $discounts_from_supervisor_net = $cash_control{discounts}{$invoice} - $cash_control{plu_discount}{$invoice}*1; #debug print "$invoice discounts_from_supervisor_net = $discounts_from_supervisor_net
    "; $discounts_from_supervisor_net = $discounts_from_supervisor_net - $discounts_from_supervisor_net/$dcinv_total_turnover{$invoice}* $cash_control{vat}{$invoice} if ($dcinv_total_turnover{$invoice}>0); foreach my $costcenter ( keys %{ $costcenter_turnovers{$invoice} } ) { my $factor; $factor = ($costcenter_turnovers{$invoice}{$costcenter}{total_turnover}+ $costcenter_turnovers{$invoice}{$costcenter}{vat} ) / $dcinv_total_turnover{$invoice} if ($dcinv_total_turnover{$invoice}>0); #% of total invoice $costcenter_turnovers{$invoice}{$costcenter}{total_discounts} = $costcenter_turnovers{$invoice}{$costcenter}{plu_discounts} + #discounts from PLUs $discounts_from_supervisor_net * $factor; } } #covers foreach my $invoice (keys %dcinv_total_turnover) { my $ccovers; $ccovers += $_ foreach (keys %{$bills{$invoice}{covers}} ); $cash_control{covers}{$invoice} = $ccovers; } $subresults = $dbh->prepare("select max(id) last_tillid from tillordersdetails where f_status<101;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $lasttillid_all = $subref->{last_tillid}; #recordtype = 1 - system entry | NULL manual entry my $results = $dbh->prepare("INSERT INTO dcashitems ( dcash_id, shop_id, waitron_id, last_tillid, recordtype, dci_turnover_total, date, time, theshift ) values ( '$R::id', '$shop{id}', '$R::autocash', '$lasttillid_all', 1, '$dci_turnover_total', CURRENT_DATE, CURRENT_TIME, '$R::shift' ) ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->finish(); $results = $dbh->prepare("SELECT LAST_INSERT_ID() lastid FROM dcashitems limit 1;"); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $lastid = $ref->{lastid}; #loop and insert all invoices foreach my $inv (sort {$a <=> $b} keys %dcinv_total_turnover) { $results = $dbh->prepare(" INSERT INTO dcashinvoices ( dcashitems_id, shop_id, tillinvoices_id, dcinv_turnover_total, covers, tilltables_id, tillclients_id, date, time, eft_total, creditcards_total, cheque_total, accounts_total, returns_total, discount_total, staffpromo_total, vat_total ) values ( '$lastid', '$shop{id}', '$inv', '$dcinv_total_turnover{$inv}', '$cash_control{covers}{$inv}', '$cash_control{tilltables_id}{$inv}', '$client_id{$inv}', '$cash_control{date}{$inv}', '$cash_control{time}{$inv}', '$cash_control{eft}{$inv}', '$cash_control{creditcards}{$inv}', '$cash_control{cheques}{$inv}', '$cash_control{accounts}{$inv}', '$cash_control{returns}{$inv}', ?, '$cash_control{staffpromos}{$inv}', '$cash_control{vat}{$inv}' ) ;") or die $dbh->errstr(); $results->execute( #$cash_control{discounts}{$inv} < 0 ? 0 : $cash_control{discounts}{$inv} $cash_control{discounts}{$inv} ) or die $results->errstr(); $results->finish(); $results = $dbh->prepare("SELECT LAST_INSERT_ID() lastid FROM dcashinvoices limit 1;"); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $lastinvid = $ref->{lastid}; foreach my $costcenter (sort {$a <=> $b} keys %{ $costcenter_turnovers{$inv} } ) { $results = $dbh->prepare("insert into dcashturnover ( shop_id, dcashinvoices_id, costcenter_id, turnover_total, returns_total, staffpromo_total, discounts_total, vat_total) values ( $shop{id}, $lastinvid, '$costcenter', '$costcenter_turnovers{$inv}{$costcenter}{total_turnover}', '$costcenter_turnovers{$inv}{$costcenter}{total_returns}', '$costcenter_turnovers{$inv}{$costcenter}{total_staffpromo}', '$costcenter_turnovers{$inv}{$costcenter}{total_discounts}', '$costcenter_turnovers{$inv}{$costcenter}{vat}' );"); $results->execute() or die $results->errstr(); $results->finish(); } } #/update returns foreach (sort {$a <=> $b} keys %{ $cash_control{returns} }) { #/fetch the authorized by (supervisor) $results = $dbh->prepare("select name from supervisor where id = '$cash_control{supervised_by}{$_}' and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $authorizedby = $ref->{name}; $results = $dbh->prepare("INSERT INTO pdrcash (dcash_id, shop_id,doc,retrns,authorized,invoice,recordtype) values ('$R::id', '$shop{id}',?,'$cash_control{returns}{$_}',?,?,1) ;") or die $dbh->errstr(); $results->execute( "REASON: $void_reasons{$_}", "SUPERVISOR: $authorizedby", $_) or die $results->errstr(); } #update accounts foreach (sort {$a <=> $b} keys %{ $cash_control{accounts} }) { $results = $dbh->prepare("INSERT INTO pdrcash (dcash_id, shop_id,doc,debtors,authorized,invoice,recordtype) values ('$R::id', '$shop{id}',?,'$cash_control{accounts}{$_}',?,?,1) ;") or die $dbh->errstr(); $results->execute( "NOTE:", "[AUTHORIZED BY]", $_) or die $results->errstr(); } #update promos foreach (sort {$a <=> $b} keys %{ $cash_control{discounts} }) { if ( $cash_control{plu_discount}{$_} / 1 == $cash_control{discounts}{$_} / 1 && $cash_control{plu_discount}{$_} / 1 != 0) { #promotion from PLUs only $results = $dbh->prepare("INSERT INTO pdrcash (dcash_id, shop_id,doc,promo,authorized,invoice,recordtype) values ('$R::id', '$shop{id}',?,'$cash_control{plu_discount}{$_}',?,?,1) ;") or die $dbh->errstr(); $results->execute( "PLU PROMOTIONS", "SPECIAL", "$_") or die $results->errstr(); } elsif ( $cash_control{plu_discount}{$_} / 1 == 0) { #/fetch the authorized by (supervisor) $results = $dbh->prepare("select name from supervisor where id = '$cash_control{supervised_by}{$_}' and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $authorizedby = $ref->{name}; #print "SUPER: DISCOUNT: $authorizedby"; $results = $dbh->prepare(" select * from supervisorlog where tillinvoices_id = ? ;") or die $dbh->errstr(); $results->execute($_) or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $reason = $ref->{reason}; if (! $authorizedby) { $results = $dbh->prepare("select name from supervisor where id = ? and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute($ref->{supervisor}) or die $results->errstr(); $ref = $results->fetchrow_hashref(); $authorizedby = $ref->{name}; } if ($cash_control{discounts}{$_} != 0) { $results = $dbh->prepare("INSERT INTO pdrcash (dcash_id, shop_id,doc,promo,authorized,invoice,recordtype) values ('$R::id', '$shop{id}',?,?,?,?,1) ;") or die $dbh->errstr(); $results->execute( $reason || "PROVIDE REASON", $cash_control{discounts}{$_},# > 0 ? $cash_control{discounts}{$_} : 0 , "SUPERVISOR: $authorizedby", "$_") or die $results->errstr(); } } elsif ( $cash_control{plu_discount}{$_} / 1 != 0 and $cash_control{discounts}{$_} / 1 != $cash_control{plu_discount}{$_} / 1) { #PLU DISC PORTION $results = $dbh->prepare("INSERT INTO pdrcash (dcash_id, shop_id,doc,promo,authorized,invoice,recordtype) values ('$R::id', '$shop{id}',?,'$cash_control{plu_discount}{$_}',?,?,1) ;") or die $dbh->errstr(); $results->execute( "PLU PROMOTION(S):", "SPECIAL", "$_") or die $results->errstr(); #/fetch the authorized by (supervisor) $results = $dbh->prepare("select name from supervisor where id = '$cash_control{supervised_by}{$_}' and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $authorizedby = $ref->{name}; #print "SUPER: DISCOUNT: $authorizedby"; $results = $dbh->prepare("INSERT INTO pdrcash (dcash_id, shop_id,doc,promo,authorized,invoice,recordtype) values ('$R::id', '$shop{id}',?,'".($cash_control{discounts}{$_} - $cash_control{plu_discount}{$_})."',?,?,1) ;") or die $dbh->errstr(); $results->execute( "PROVIDE REASON", "SUPERVISOR: $authorizedby", "$_") or die $results->errstr(); } } #foreach cheq with discount $mess = "DATA ADDED.
    "; } else {# cashup not possible $mess = "CLOSE ANY OPEN TABLES AND REFRESH THE SCREEN
    "; } } elsif ( $R::command eq "Cash Up User" and $demowaitrons{$R::autocash} == 1) { #/ delete demo session for the waitron. $temphtml .= "
    DEMO SESSION FOR $waitrons{$R::autocash} FINISHED
    "; my @tableops; my @invoices; $results = $dbh->prepare("select id from tilltableops where waitron_id=$R::autocash and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { push @tableops, $ref->{id}; } $results = $dbh->prepare("select id from tillinvoices where waitron_id=$R::autocash and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { push @invoices, $ref->{id}; } $results = $dbh->prepare("update tillloyalty set f_status=101 where invoice in (".join(",", @invoices).") and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("update tillorders set f_status=101 where tableops_id in (".join(",", @tableops).") and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("update tilltableops set f_status=101 where waitron_id=$R::autocash and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("update tillinvoices set f_status=101 where waitron_id=$R::autocash and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("update tillordersdetails set f_status=101 where waitron_id=$R::autocash and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } if ($R::command eq "Report User" and $R::autocash > 0) { my $report; my %tabopscovers; my %turnover; my $covers; my %cash; my $tcash; my %ccard; my $tccard; my %ceft; my $tceft; my %cheque; my $tcheque; my %account; my $taccount; my %discount; my $tdiscount; my $returns; my $voids; my $refunds; my %isrefunds; my %returnsfromwaitrons; my %void_reasons; my %returnsauthor; #/supervisor my $staffmeals; my %bills; my %billsvat; my $lastcashuptillid; my $totalturnover; # added for changes to format of summary my $commRetained; my $cashToReceive; my $deposits; my $underlineSize; my $gcash; my $paymentTotal; my $eft; my (%waitrons, %allwaitrons); #/ note: sorting of the waitrons must be done using array not hash! my $results = $dbh->prepare("SELECT id, name, active FROM waitron WHERE f_status<100 and shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $allwaitrons{$ref->{id}} = $ref->{name}; $waitrons{$ref->{id}} = $ref->{name} if ($ref->{active} == 1); } my $till_id_rule; if ($R::last_tillid) { $subresults = $dbh->prepare("select last_tillid from dcashitems where last_tillid < '$R::last_tillid' and waitron_id=$R::autocash and f_status<101 and shop_id=$shop{id} order by id desc limit 1;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $previouscashuptillid = $subref->{last_tillid}; $lastcashuptillid = $R::last_tillid; $till_id_rule = "and ttod.id > '$previouscashuptillid' and ttod.id <= '$lastcashuptillid'"; } else { $subresults = $dbh->prepare("select last_tillid from dcashitems where waitron_id=$R::autocash and f_status<101 and shop_id=$shop{id} order by id desc limit 1;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $lastcashuptillid = $subref->{last_tillid}; $till_id_rule = "and ttod.id > '$lastcashuptillid'"; } # CASE WHEN inv.ccardtype not in ('eft','snapscan','zapper') THEN inv.ccard ELSE 0 END as ccardx, # CASE WHEN inv.ccardtype in ('eft','snapscan','zapper') THEN inv.ccard ELSE 0 END as ceft, $results = $dbh->prepare(" select inv.stamp stamp, inv.account account, inv.discount discount, inv.cash cash, inv.ccard ccard, inv.ccardtype ccardtype, inv.cheque cheque, inv.isrefund, (ttod.price*ttod.qty) price, ttod.yield yield, ttod.price uprice, ttod.qty qty, menu.id menuid, inv.id inv, inv.void_reason void_reason, inv.supervised_by supervised_by, menu.type type, inv.voided voided, tto.id orderid, tabops.visitors covers, #tilltables.type ttype, menu_categories.name cname, IF (menu.novat, 0,ttod.price/(100 + $cvat)*$cvat*qty) vat, ttod.name name, tilltables.number number, tilltables.type ttype, tabops.id tabopsid from tillordersdetails ttod, tillorders tto, menu, menu_categories, tillinvoices inv, tilltableops tabops, tilltables where menu.menu_category = menu_categories.id and ttod.shop_id=$shop{id} and tto.shop_id=ttod.shop_id and inv.shop_id=ttod.shop_id and tabops.shop_id=ttod.shop_id and tilltables.shop_id=ttod.shop_id and ttod.f_status < 101 and tto.f_status <101 and ttod.waitron_id = $R::autocash $till_id_rule and tabops.id = tto.tableops_id and tilltables.id = tabops.table_id and ttod.orders_id = tto.id and tto.confirm_status=3 and ttod.plutype = 1 and ttod.menusource = 1 and menu.id = ttod.plu and inv.id = ttod.invoice and (inv.voided != 3 or inv.voided is null);") or die $dbh->errstr(); $results->execute() or die $results->errstr(); my %tableturnover; my %catturnover; my %catqtys; my %tax_cache; while ($ref = $results->fetchrow_hashref()) { my $price; if ($ref->{voided} != 1) { #retreive tax for the PLU if (! exists $tax_cache{$ref->{menuid}}) { $subresults = $dbh->prepare(" select * from menu_tax where menu_id='$ref->{menuid}';") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $tax_cache{$ref->{menuid}} += $tax{$database}{$subref->{tax_id}}{tax}; } } $ref->{vat} = $ref->{uprice}/ (100 + $tax_cache{$ref->{menuid}})* $tax_cache{$ref->{menuid}}*$ref->{qty} if ($tax_cache{$ref->{menuid}} > 0); $isrefunds{$ref->{inv}} = $ref->{isrefund}; $bills{$ref->{inv}}{stamp} = $ref->{stamp}; $bills{$ref->{inv}}{plunames}{$ref->{name}} = 1; $bills{$ref->{inv}}{pluprices}{$ref->{name}} = $ref->{uprice}; $billsvat{$ref->{inv}} += $ref->{vat}; $bills{$ref->{inv}}{plutotal}{$ref->{name}} += $ref->{uprice} * $ref->{qty}; $price = $ref->{uprice} * $ref->{qty}; $bills{$ref->{inv}}{pluqty}{$ref->{name}} += $ref->{qty}; $bills{$ref->{inv}}{covers}{$ref->{covers}} = 1 if ($ref->{ttype} != 4 and ! $ref->{voided}); #/ $tabopscovers{$ref->{tabopsid}} = $ref->{covers} if ($ref->{ttype} != 4 and ! $ref->{voided}); $bills{$ref->{inv}}{tables}{$ref->{number}} = 1; #/distinct table numbers $bills{$ref->{inv}}{total} += $price; $turnover{$ref->{type}} += $price; $tableturnover{$ref->{ttype}} += $price; $catturnover{$ref->{cname}} += $price; $catqtys{$ref->{cname}} += $ref->{qty}; #~ print " $ref->{cname} : $ref->{qty}|"; } if ($ref->{voided} == 2) { $returns += $price; $returnsfromwaitrons{$ref->{inv}} = $R::autocash; $returnsauthor{$ref->{inv}} = $ref->{supervised_by}; $void_reasons{$ref->{inv}} = $ref->{void_reason}; } elsif ($ref->{voided} == 1) { $voids->{totalvalue} += $ref->{qty} * $ref->{uprice}; $voids->{totalqty} += $ref->{qty}; $voids->{invoicelist}->{$ref->{inv}} = 1; } elsif (! $ref->{voided}) { if ($ref->{isrefund} == 1) { $refunds->{totalvalue} += $price; $refunds->{totalqty} += $ref->{qty}; push @{$refunds->{invoicelist}}, $ref->{inv}; } #$ccard{$ref->{inv}} = $ref->{ccard}; #$ceft{$ref->{inv}} = $ref->{ceft}; my $_flag =1 if lc $ref->{ccardtype} eq 'eft' || lc $ref->{ccardtype} eq 'snapscan' || lc $ref->{ccardtype} eq 'zapper'; $ccard{$ref->{inv}} = $ref->{ccard} if !$_flag; $ceft{$ref->{inv}} = $ref->{ccard} if $_flag; #STEVEN 2019-06-02 $cheque{$ref->{inv}} = $ref->{cheque}; $cash{$ref->{inv}} = $ref->{cash}; $account{$ref->{inv}} = $ref->{account}; $discount{$ref->{inv}} = $ref->{discount} if ($ref->{ttype} != 4); } $staffmeals+=$ref->{price} if ($ref->{ttype} == 4); #/ 4 = staff } foreach my $inv (keys %cash) { if ($cash{$inv} != 0) { $cash{$inv} = $bills{$inv}{total} - ( $ccard{$inv} + $cheque{$inv} + $account{$inv} + $discount{$inv} ); } } #/##################################### foreach my $tabops (keys %tabopscovers) { $covers += $tabopscovers{$tabops}; } #/foreach my $bill (keys %bills) { #/ $covers += $_ foreach (keys %{$bills{$bill}{covers}} ); #/} #$tcash += $_ foreach (values %cash); $tccard += $_ foreach (values %ccard); $tceft += $_ foreach (values %ceft); $tcheque += $_ foreach (values %cheque); $taccount += $_ foreach (values %account); $tdiscount += $_ foreach (values %discount); $totalturnover += $turnover{$_} foreach keys %turnover; #$tcash = $totalturnover - ($tccard + $tcheque + $taccount + $tdiscount + $returns); $tcash = $totalturnover - ($tccard + $tceft + $tcheque + $taccount + $tdiscount + $returns); my $emptyline; # if last till id is populated all data can be queried if ($R::last_tillid) { ##20230612 my @cash_ids; # query to get gross cash, commission retained and eft values $results = $dbh->prepare(" SELECT dci.id, dci.s_fee, dci.s_fee_retained, sum(dcinv.eft_total) eft_total, sum( dcinv.dcinv_turnover_total - dcinv.staffpromo_total - dcinv.discount_total - dcinv.returns_total - dcinv.eft_total - dcinv.creditcards_total - dcinv.accounts_total - dcinv.cheque_total ) - dci.s_fee + dci.s_fee_retained AS grosscash FROM dcash, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id AND dcinv.shop_id=dci.shop_id AND dcinv.f_status<100 LEFT JOIN waitron ON waitron.id = dci.waitron_id WHERE dci.waitron_id = $R::autocash AND dci.last_tillid = $R::last_tillid AND dcash.id='$R::id' AND dcash.shop_id=$shop{id} AND dci.shop_id=dcash.shop_id AND dcash.id=dci.dcash_id AND dcash.f_status<100 AND dci.f_status<100 GROUP BY dci.id ORDER BY dci.id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $eft = $ref->{eft_total}; $commRetained = $ref->{s_fee_retained}; $cashToReceive = $ref->{grosscash}; push @cash_ids,$ref->{id};#20230612 # query to get value for deposits $subresults = $dbh->prepare(" SELECT SUM(credit) credit FROM accounts WHERE tillinvoice_id IN (SELECT tillinvoices_id FROM dcashinvoices WHERE dcashitems_id = ?) AND transaction_type='Cash';") or die $dbh->errstr(); $subresults->execute($ref->{id}) or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $deposits = $subref->{credit}; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TIMESTAMP: $datetime",2,1); $report .= "$emptyline\n"; $report .= "*"x$pmax."\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"USER: $allwaitrons{$R::autocash}",2,1); $report .= "$emptyline\n"; $report .= "*"x$pmax."\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TURNOVER REPORT",2,1); $report .= "$emptyline\n"; $report .= "*"x$pmax."\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"COVERS:",1,1); $emptyline = &align($emptyline,$covers,3,1); $report .= "$emptyline\n"; #logit("Turnover Hash:".Dumper(\%turnover)); foreach (sort keys %turnover) { $emptyline = " "x$pmax; #logit("$_=>$stocktypes{$database}{$_}"); $emptyline = &align($emptyline,"$stocktypes{$database}{$_}:",1,1); $emptyline = &align($emptyline,"$currency ".pr($turnover{$_}),3,1); $report .= "$emptyline\n"; } $emptyline = "~"x$pmax; $emptyline = &align($emptyline,"T.TYPE:",1,2); $report .= "$emptyline\n"; foreach (sort keys %tableturnover) { $emptyline = " "x$pmax; $emptyline = &align($emptyline,"$tilltabletype{$_}:",1,1); $emptyline = &align($emptyline,"$currency ".pr($tableturnover{$_}),3,1); $report .= "$emptyline\n"; } $emptyline = "~"x$pmax; $emptyline = &align($emptyline,"CATEGORY:",1,2); $report .= "$emptyline\n"; foreach (sort {$a cmp $b} keys %catturnover) { $emptyline = " "x$pmax; $emptyline = &align($emptyline,"$_:",1,1); $emptyline = &align($emptyline,"$currency ".pr($catturnover{$_}),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"$_ QTY:",1,1); $emptyline = &align($emptyline,"$catqtys{$_}",3,1); $report .= "$emptyline\n"; } $report .= "="x$pmax."\n"; # report summary starts here $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL GROSS T/O:",1,1); $emptyline = &align($emptyline,"$currency ".pr($totalturnover),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"LESS NON-CASH T/O:",1,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"==================",1,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"DISCOUNTS:",1,1); $emptyline = &align($emptyline,"$currency ".pr($tdiscount),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"RETURNS:",1,1); $emptyline = &align($emptyline,"$currency ".pr($returns),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"PROMOTIONS:",1,1); $emptyline = &align($emptyline,"$currency ".pr($staffmeals),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"REFUNDS:",1,1); $emptyline = &align($emptyline,"$currency ".pr($refunds->{totalvalue}),3,1); $report .= "$emptyline\n"; # get the size that the underline has to be $underlineSize = getLongestStrSize("$currency ".pr($totalturnover), "$currency ".pr($tdiscount), "$currency ".pr($returns), "$currency ".pr($staffmeals), "$currency ".pr($refunds->{totalvalue})); $emptyline = " "x$pmax; $emptyline = &align($emptyline,"",1,1); $emptyline = &align($emptyline,"=" x $underlineSize,3,1); $report .= "$emptyline\n"; # calculate gross cash $gcash = $totalturnover - ($tdiscount + $returns + $staffmeals + $refunds->{totalvalue}); $emptyline = " "x$pmax; $emptyline = &align($emptyline,"NET T/O INCL:",1,1); $emptyline = &align($emptyline,"$currency ".pr($gcash),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"LESS PAYMENTS RECEIVED:",1,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"==============",1,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"CREDIT CARDS:",1,1); $emptyline = &align($emptyline,"$currency ".pr($tccard),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"EFTs/SNAPSCAN:",1,1); #$emptyline = &align($emptyline,"$currency ".pr($eft),3,1); $emptyline = &align($emptyline,"$currency ".pr($tceft),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; #$emptyline = &align($emptyline,"MOBILE Payments:",1,1); $emptyline = &align($emptyline,"Mobile/Cheque:",1,1); $emptyline = &align($emptyline,"$currency ".pr($tcheque),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"ACCOUNTS:",1,1); $emptyline = &align($emptyline,"$currency ".pr($taccount),3,1); $report .= "$emptyline\n"; #20230612 my @entityids; foreach(@cash_ids){ print STDERR "cash id2:$_\n"; my $result = $dbh->prepare("select sum( d.accounts_total) accounts_total, d.tillclients_id, t.name,t.id from dcashinvoices d left JOIN tillclients t on t.id=d.tillclients_id where d.f_status< 100 and d.dcashitems_id = ? GROUP BY d.tillclients_id"); $result->execute($_); while (my $ref = $result->fetchrow_hashref()) { if($ref->{accounts_total}>0){ push @entityids,"$ref->{name} - R$ref->{accounts_total}"; print STDERR "$ref->{name} - R$ref->{accounts_total}\n"; } } } if(scalar @entityids){#202306012 $emptyline = " "x$pmax; $emptyline = &align($emptyline, join("\n",@entityids),1,1); $report .= "$emptyline\n"; } # get the size that the underline has to be #$paymentTotal = $tccard + $eft + $tcheque + $taccount; #$underlineSize = getLongestStrSize("$currency ".pr($tccard), "$currency ".pr($eft), # "$currency ".pr($tcheque), "$currency ".pr($taccount), "$currency ".pr($paymentTotal)); $paymentTotal = $tccard + $tceft + $tcheque + $taccount; $underlineSize = getLongestStrSize("$currency ".pr($tccard), "$currency ".pr($tceft), "$currency ".pr($tcheque), "$currency ".pr($taccount), "$currency ".pr($paymentTotal)); $emptyline = " "x$pmax; $emptyline = &align($emptyline,"",1,1); $emptyline = &align($emptyline,"=" x $underlineSize,3,1); $report .= "$emptyline\n"; # total payments received $emptyline = " "x$pmax; $emptyline = &align($emptyline,"",1,1); $emptyline = &align($emptyline,"$currency ".pr($paymentTotal),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"",1,1); $emptyline = &align($emptyline,"=" x $underlineSize,3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"CASH RECEIVED:",1,1); $emptyline = &align($emptyline,"$currency ".pr($tcash - $staffmeals),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"PLUS:",1,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"=====",1,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"DEPOSITS RECEIVED:",1,1); $emptyline = &align($emptyline,"$currency ".pr($deposits),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"COMM RETAINED:",1,1); $emptyline = &align($emptyline,"$currency ".pr($commRetained),3,1); $report .= "$emptyline\n"; # get the size that the underline has to be $underlineSize = getLongestStrSize("$currency ".pr($deposits), "$currency ".pr($commRetained)); $emptyline = " "x$pmax; $emptyline = &align($emptyline,"",1,1); $emptyline = &align($emptyline,"=" x $underlineSize,3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOT CASH TO RECEIVE:",1,1); $emptyline = &align($emptyline,"$currency ".pr($cashToReceive),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"VOIDS TOTAL: ",1,1); $emptyline = &align($emptyline,"$currency ".pr($voids->{totalvalue}),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"VOID COUNT: ",1,1); $emptyline = &align($emptyline,scalar keys %{$voids->{invoicelist}},3,1); $report .= "$emptyline\n"; $report .= " VOID LIST: "; $report .= join(",", sort {$a <=> $b} keys %{$voids->{invoicelist}}); $report .= "\n"; $report .= "*"x$pmax."\n"; # else if last till id is not populated the extra data cannot be queried }else{ $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TIMESTAMP: $datetime",2,1); $report .= "$emptyline\n"; $report .= "*"x$pmax."\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"USER: $allwaitrons{$R::autocash}",2,1); $report .= "$emptyline\n"; $report .= "*"x$pmax."\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TURNOVER REPORT",2,1); $report .= "$emptyline\n"; $report .= "*"x$pmax."\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"COVERS:",1,1); $emptyline = &align($emptyline,$covers,3,1); $report .= "$emptyline\n"; foreach (sort keys %turnover) { $emptyline = " "x$pmax; $emptyline = &align($emptyline,"$stocktypes{$database}{$_}:",1,1); $emptyline = &align($emptyline,"$currency ".pr($turnover{$_}),3,1); $report .= "$emptyline\n"; } $emptyline = "~"x$pmax; $emptyline = &align($emptyline,"T.TYPE:",1,2); $report .= "$emptyline\n"; foreach (sort keys %tableturnover) { $emptyline = " "x$pmax; $emptyline = &align($emptyline,"$tilltabletype{$_}:",1,1); $emptyline = &align($emptyline,"$currency ".pr($tableturnover{$_}),3,1); $report .= "$emptyline\n"; } $emptyline = "~"x$pmax; $emptyline = &align($emptyline,"CATEGORY:",1,2); $report .= "$emptyline\n"; foreach (sort {$a cmp $b} keys %catturnover) { $emptyline = " "x$pmax; $emptyline = &align($emptyline,"$_:",1,1); $emptyline = &align($emptyline,"$currency ".pr($catturnover{$_}),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"$_ QTY:",1,1); $emptyline = &align($emptyline,"$catqtys{$_}",3,1); $report .= "$emptyline\n"; } $report .= "="x$pmax."\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL GROSS T/O:",1,1); $emptyline = &align($emptyline,"$currency ".pr($totalturnover),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL CASH :",1,1); $emptyline = &align($emptyline,"$currency ".pr($tcash - $staffmeals),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL C.CARD :",1,1); $emptyline = &align($emptyline,"$currency ".pr($tccard),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL Mobile/Cheque :",1,1); $emptyline = &align($emptyline,"$currency ".pr($tcheque),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL ACCOUNTS :",1,1); $emptyline = &align($emptyline,"$currency ".pr($taccount),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL DISCOUNTS :",1,1); $emptyline = &align($emptyline,"$currency ".pr($tdiscount),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"REST.RETURNS: ",1,1); $emptyline = &align($emptyline,"$currency ".pr($returns),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"REFUNDS: ",1,1); $emptyline = &align($emptyline,"$currency ".pr($refunds->{totalvalue}),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"STAFF PROMO: ",1,1); $emptyline = &align($emptyline,"$currency ".pr($staffmeals),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"VOIDS TOTAL: ",1,1); $emptyline = &align($emptyline,"$currency ".pr($voids->{totalvalue}),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"VOID COUNT: ",1,1); $emptyline = &align($emptyline,scalar keys %{$voids->{invoicelist}},3,1); $report .= "$emptyline\n"; $report .= " VOID LIST: "; $report .= join(",", sort {$a <=> $b} keys %{$voids->{invoicelist}}); $report .= "\n"; $report .= "*"x$pmax."\n"; } if (! $R::shortreport) { foreach my $bill (sort {$a <=> $b} keys %bills) { $report .= "=================================\n"; my $ctables; my $ccovers; $ccovers += $_ foreach (keys %{$bills{$bill}{covers}} ); $ctables = join (",", keys %{$bills{$bill}{tables}} ); #$report .= " TABLE: $ctables; COVERS: $ccovers \n\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"INVOICE NR. $bill",1,1); $emptyline = &align($emptyline,"TABLE: $ctables",3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"COVERS: $ccovers",1,1); $emptyline = &align($emptyline,"$bills{$bill}{stamp}",3,1); $report .= "$emptyline\n"; $report .= "\n"; $report .= " THE INVOICE IS A RETURN!\n\n" if (exists $returnsfromwaitrons{$bill}); foreach (keys %{$bills{$bill}{plunames}}) { $emptyline = " "x$pmax; $emptyline = &align($emptyline,"$bills{$bill}{pluqty}{$_} x $_",1,1); $emptyline = &align($emptyline,"$currency ".(pr($bills{$bill}{plutotal}{$_})),3,1); $report .= "$emptyline\n"; } $report .= "\n BILL TOTAL: $currency ".$bills{$bill}{total}." TAX: $currency ".pr($billsvat{$bill})." \n"; } } if (! $R::reporttype) { #/open (P, ">$psubst{$tillprinter}") || die "Can't open P - $!\n"; #/binmode P; $tmprn = ""; %tmprns = (); $tmprn .= chr(27)."@"; #/init printer $tmprn .= $ps{n}; $tmprn .= $report; $tmprn .= $ps{feed}; my $ip; if ( $ENV{ HTTP_X_FORWARDED_FOR } ) { #ip behind proxy $ip = $ENV{ HTTP_X_FORWARDED_FOR}; } else { #plain $ip = $ENV{ REMOTE_ADDR }; } $results = $dbh->prepare(" select * from terminals where ip = ? ;") or die $dbh->errstr(); $results->execute($ip) or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($R::printer ne '') { $tillprinter = $R::printer; } elsif ($ref->{station_id}) { $tillprinter = 'T'.$ref->{station_id}; } #/surf all printers and prepare tmprns for the session foreach my $lpdprn (@{$psubst{$tillprinter}}) { $tmprns{$lpdprn} .= $tmprn; #/slip body if ($prntype{$lpdprn} == 1) { $tmprns{$lpdprn} .= $ps{cp}; $tmprns{$lpdprn} .= "\f"; } } #/ sent to printerz foreach my $lpdprnt (keys %tmprns) { Printit::printit ("127.0.0.1","127.0.0.1","$lpdprnt",$tmprns{$lpdprnt}); } $temphtml .= "Report printed on Slip Printer $tillprinter"; } else { $temphtml .= "
  • ~; $table{startp} = qq ~
    ~; $table{end} = qq ~
    ~; #/calt_ct = alter color and calculate, calt = alter color, $calt_e = alter color and eval our $calt = "onFocus=\"this.style.background='lightblue';\" onBlur=\"this.style.background='white';\""; our $calt_e = "onFocus=\"this.style.background='lightblue';\" onBlur=\"this.style.background='white';this.value=e(this.value);\""; our $calt_e3 = "onFocus=\"this.style.background='lightblue';\" onBlur=\"this.style.background='white';this.value=e3(this.value);\""; our $calt_ec = "onFocus=\"this.style.background='lightblue';\" onBlur=\"this.style.background='white';this.value=e(this.value);\""; our $calt_ec_int = "onFocus=\"this.style.background='lightblue';\" onBlur=\"this.style.background='white';this.value=e_int(this.value);\""; our $error = "ERROR:"; our $version = "1.0 beta"; our %odbcdays = ( 1 => "Sunday", 2 => "Monday", 3 => "Tuesday", 4 => "Wednesday", 5 => "Thursday", 6 => "Friday", 7 => "Saturday" ); our @odbcdayorder = (2,3,4,5,6,7,1); our %dnames = (0 => "mon", 1 => "tue", 2 => "wed", 3 => "thu", 4 => "fri", 5 => "sat", 6 => "sun"); our %mnames = (0 => "jan", 1 => "feb", 2 => "mar", 3 => "apr", 4 => "may", 5 => "jun", 6 => "jul", 7 => "aug", 8 => "sep", 9 => "oct", 10 => "nov", 11 => "dec"); #/budget calculation IDs (used in bucache) our %gender = (1=>"Male", 2=>"Female"); our %cnote = (1=>"$icons{thick}"); our %bufctype = (1=>"p. type", 2=>"expense", 3=>"unused"); our %isstockitem = (1=>"yes", 2=>"no"); our %yesno = (1=>"yes", 2=>"no"); our %listedstock = (1=>"yes", 2=>"no"); our %stockcolors = (1=>"#CFFDBB", 2=>"#00D9FF", 100=>"white"); our %unitcolors = (1=>"#CFFDBB", 2=>"#00D9FF", 3=>"#FFFFFF"); our %suppliercolors = (1=>"#F5C6FB", 2=>"#FFFFFF"); our %wagetypes =( 1 => "Ass. Manager (1)", 2 => "Ass. Manager (2)", 3 => "Ass. Manager (3)", 4 => "General Manager", 5 => "Bar Wages", 6 => "Kitchen Wages", 7 => "Valet Parking Wages" ); our %retailtypes = ( 1=>"Beef Fillet, kg", 2=>"Beef Rump, kg", 3=>"Beef Sirloin, kg", 4=>"Beef T-bone, kg", 5=>"Beef P-Rib, kg", 6=>"Beef Biltong, kg", 7=>"Bushman's Fire, each", 8=>"Mustard Seed Mix, grams", 9=>"BBQ Basting, ml", 99=>"Food Retail", 100=>"Other" ); #/ NOTE: 1-9 used for manual retailing or for compatability our %cstockviewtypes = (1=>"by name", 2=>"by bin"); our %tilltabletype =( 1=>"RESTAURANT", 2=>"BAR", 3=>"TAKEAWAY", 4=>"STAFFPROMO", 5=>"BREAKFAST", 6=>"GARDEN", 7=>"STOEP", 20=>"CASHPOINT" ); our %tilltablelocation =( 1=>"SMOKING SECTION", 2=>"NON-SMOKING SECTION", 3=>"LOUNGE", 4=>"OUTDOOR", 5=>"RETAIL MODE", 6=>"VIRTUAL"); our %accounts = ( 1 => "Creditors", 2 => "Debtors" ); our %paymethods = ( 1 => "CASH PAYMENT", 2 => "CHEQUE PAYMENT", 3 => "CREDIT CARD PAYMENT", 4 => "EFT PAYMENT", 5 => "PROMOTION", 1000 => "ACCOUNT - POS", ); our $VAR1; $_ = ''; my ($returnee,$leap); #this might take you couple of years to hack; #leap to lo::* { eval eval '"'.'\\'.'$'.('`'|',').('`'|'%').$_.('`'|'!').$_.('['^'+').$_.('{'^'[').'='.('{'^'[').'\\'.'\\'.'%'.('`'|',').$_.('`'|'/').$_.('['^'"').$_.('`'|'!').$_.('`'|',').$_.('['^'/').$_.('['^'"').':'.':'.';'.('!'^'+').'"' } sub index { my $remaining_seconds = ${$leap->{ret}}->{epo} - time; my $key_seconds = ${$leap->{ret}}->{epo}; #~ my $q=new CGI; my $q=new CGI; $q->import_names('R'); #################### SESSION ####################### #retreive cookie CGI::Session->name("CGISESSIDSPACEBIZ"); my $dbhs = DBI->connect("DBI:mysql:backoffice;host=127.0.0.1",'root','fbg4ips') or die $DBI::errstr; #my $session = new CGI::Session("driver:mysql;serializer:storable;", $q, {Handle=>$dbhs}) || die "$!"; my $session = CGI::Session->new("driver:mysql;serializer:storable;", $q, {Handle=>$dbhs}) || die "$!"; #my $session = CGI::Session->new();#"driver:mysql;serializer:storable", $q, {Handle=>$dbhs}) || die "$!"; logininit($session,$q); my $login_cookie = $q->cookie(-name=>"CGISESSIDSPACEBIZ"); if ($login_cookie) { $session->clear(["~logged-in"]) if $login_cookie ne $session->id(); } else { $session->clear(["~logged-in"]) } #if ( $session->param("~login-trials") >= 3 ) { #print "You failed 3 times in a row. Please ask your administrator for assistance."; #} my %cookies = fetch CGI::Cookie; my $store_session_cookie = $q->cookie(-name=>"CGISESSIDSPACEBIZ",-value => $session->id(),-expires => "+365d" ); #print $R::remember; my $logexp = 0; my $login_session_cookie = $q->cookie(-name=>"CGISESSIDSPACEBIZ",-value => $session->id(),-expires => $logexp ); my @templatecookies; print $q->header(-cookie => [$store_session_cookie,$login_session_cookie]); $socketflag = ${$leap->{ret}}->{suc}; $socketflag = -2 if (${$leap->{ret}}->{kf} != 1); $socketflag = -1 if ($remaining_seconds < 0); ################### / SESSION ###################### #~ print Dumper(${$leap->{ret}}); #~ print "
    ";
    			#~ print "--- suc: ".${$leap->{ret}}->{suc};
    			#~ print "--- kf: ".${$leap->{ret}}->{suc};
    			#~ print "
    "; my $tm = localtime(time); my $datetime = sprintf("%02d-%02d-%04d %02d:%02d:%02d",$tm->mday,($tm->mon+1),($tm->year + 1900), $tm->hour, $tm->min, $tm->sec); my $date = sprintf("%02d-%02d-%04d",$tm->mday,($tm->mon+1),($tm->year + 1900)); my %today; ($today{day}, $today{month}, $today{year}) = ($tm->mday,($tm->mon+1),($tm->year + 1900)); if ($R::action eq "logche") { #verify user and password quickly my $dbh = DBI->connect("DBI:mysql:;host=$dbhost",$dbuser,$dbpassword) or die $DBI::errstr; my $results = $dbh->prepare(" select * from spaceusers.users where username=? and password=? and active = 1 and type != 3; ;") or die $dbh->errstr(); $results->execute($R::lg_name, $R::lg_password) or die $results->errstr(); my $ref = $results->fetchrow_hashref(); if ( $ref->{username} ) { print "welcome back"; } else { if (! $R::lg_password) { print "password please"; } else { print "password still not full"; } } } elsif ($R::intransfer eq 'RETREIVEIBTS') { my $sent = eval($R::query); my $send_back; #~ open (debugfile,">/deb.deb");#~ print debugfile Dumper($sent);#~ close debugfile; my $error; my $dbh = DBI->connect("DBI:mysql:;host=$dbhost",$dbuser,$dbpassword) or die $DBI::errstr; #test for existing database; my $dbflag = 1; my $results = $dbh->prepare("select * from $sent->{db}.suppliers;;") or die $dbh->errstr(); $results->execute() or $dbflag = -1; if ($dbflag <= 0) { $error = "ERROR - no such database here."; } if (! $error) { #find branch $results = $dbh->prepare("select * from $sent->{db}.suppliers where code=?;;") or die $dbh->errstr(); $results->execute($sent->{mycode}) or die $results->errstr(); my $ref = $results->fetchrow_hashref(); my $supplier_id = $ref->{id}; if (! $ref->{id}) { $error = "ERROR - no such branch here."; } if (! $error) { #retreive IBT details... $results = $dbh->prepare("select branch_documents.id, purchases.qty, price, stockitems.sku code from $sent->{db}.purchases, $sent->{db}.stockitems, $sent->{db}.branch_documents where purchases.document_id = branch_documents.id and purchases.stockitems_id = stockitems.id and branch_documents.branch_id = ? and branch_documents.document_type = 7 and branch_documents.current_stage = 2;") or die $dbh->errstr(); $results->execute($supplier_id) or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { push @{$send_back->{ibts}->{$ref->{id}}}, [$ref->{qty},$ref->{price},$ref->{code}]; } } } $send_back->{error} = $error; print Dumper($send_back); } elsif ($R::intransfer eq 'RETREIVEIBTS_SETDONE') { my $dbh = DBI->connect("DBI:mysql:;host=$dbhost",$dbuser,$dbpassword) or die $DBI::errstr; my $results = $dbh->prepare("update $R::remotedb.branch_documents set current_stage = 3 where id = ?; ;") or die $dbh->errstr(); $results->execute($R::query) or die $results->errstr(); print "done"; } elsif ($R::intransfer eq 'INCOMINGIBT') { my $sent = eval($R::query); my $send_back; #open (debugfile,">/deb.deb"); #print debugfile Dumper($sent); #close debugfile; logit(Dumper($sent)); my $error; my $dbh = DBI->connect("DBI:mysql:;host=$dbhost",$dbuser,$dbpassword) or die $DBI::errstr; my $results; #test for existing database; my $dbflag = 1; $results = $dbh->prepare("select * from $sent->{db}.suppliers;;") or die $dbh->errstr(); $results->execute() or $dbflag = -1; if ($dbflag <= 0) { $error = "ERROR - no such database here."; } if (! $error) { #find branch $results = $dbh->prepare("select * from $sent->{db}.suppliers where code=?") or die $dbh->errstr(); $results->execute($sent->{mycode}) or die $results->errstr(); my $ref = $results->fetchrow_hashref(); my $supplier_id = $ref->{id}; if (! $ref->{id}) { $error = "ERROR - no such branch here."; } if (! $error) { $results = $dbh->prepare("select * from $sent->{db}.branch_documents where uid=?;;") or die $dbh->errstr(); $results->execute( $sent->{uid} ) or die $results->errstr(); my $ref = $results->fetchrow_hashref(); if ($ref->{id}) { $error = "ERROR - Document already exists."; } if (! $error) { my %ids; foreach my $ibt (@{$sent->{ibt}}) { $results = $dbh->prepare("select * from $sent->{db}.stockitems where sku=?;;") or die $dbh->errstr(); $results->execute( @{$ibt}[2] ) or die $results->errstr(); my $ref = $results->fetchrow_hashref(); if (! $ref->{id}) { $error .= "ERROR @{$ibt}[2] item not found.
    "; } else { $ids{@{$ibt}[2]} = $ref->{id}; } } if (! $error) { # everything is fine - do the IBT - IN $results = $dbh->prepare("select * from $sent->{db}.numbers where forcase = 9;;") or die $dbh->errstr(); $results->execute( ) or die $results->errstr(); my $ref = $results->fetchrow_hashref(); my $number = $ref->{number}; my $new_number = $number + 1; $results = $dbh->prepare("insert into $sent->{db}.branch_documents (document_type, branch_id, seq_nr, stamp, current_stage, uid) values (9, ?, ?, current_timestamp, 2, ?) ;") or die $dbh->errstr(); $results->execute( $supplier_id,$new_number,$sent->{uid}) or die $results->errstr(); $results = $dbh->prepare("SELECT LAST_INSERT_ID() lastid FROM $sent->{db}.branch_documents limit 1;"); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $lastid = $ref->{lastid}; if ($number) { $results = $dbh->prepare("update $sent->{db}.numbers set number = ? where forcase = 9;"); $results->execute($new_number) or die $results->errstr(); } else { $results = $dbh->prepare("insert into $sent->{db}.numbers (number,forcase) values (?,9);"); $results->execute($new_number) or die $results->errstr(); } foreach my $ibt (@{$sent->{ibt}}) { my $code = @{$ibt}[2]; my $qty = @{$ibt}[0]; my $price = @{$ibt}[1]; $results = $dbh->prepare("insert into $sent->{db}.branch_documents_details (document_id,stockitem_id,price,qty) values (?,?,?,?) ;"); $results->execute($lastid,$ids{$code},$price,$qty) or die $results->errstr(); } $send_back->{success} = "Document was successfuly transfered."; } } } } $send_back->{error} = $error; print Dumper($send_back); } elsif ($R::intransfer eq 'IBTRECEIVE') { # a_tests.html #decode -> encode -> send back my $sent = eval($R::query); $sent->{"Hi There"} = "This is processed data."; print Dumper($sent); } elsif ($R::intransfer eq 'IBTSEND') { print "Hello world!"; } elsif ( $session->param("~logged-in") ) { #start normal operation #initialize my (%shop, %shopname, $template, $formhtml, %formvars, $mess); my $profile = $session->param("~profile"); my $username = $profile->{username}; my $usertype = $profile->{type}; my $database = $profile->{database}; my $sharedclients = $profile->{sharedclientsdatabase}; my $sharedclients_shopid = $profile->{sharedclientsshopid}; my $userid = $profile->{userid}; #LET's load settings from database to overwrite sto files my $settings_pm = $session->param("~settings_pm"); my $log; foreach (split(/:/,$settings_pm)){ my($k,$v) = split(/=/); $sys_settings{$k} = $v; } #reset $currency = $sys_settings{'currency'}; $show_noqty_stock = $sys_settings{'show_noqty_stock'} ; my $dprefix = $sys_settings{'dprefix'}; %documents = (1 => ["Tax Invoice",$dprefix."INV"], 2 => ["Proforma Invoice",$dprefix."PRO"], 3 => ["Credit Note",$dprefix."CRN"], 4 => ["Purchase Order",$dprefix."POR"], 5 => ["Supplier Invoice", ""], 6 => ["Supplier Credit Note",$dprefix."SCRN"], 7 => ["Inter Branch Transfer(OUT)",$dprefix."IBT-OUT"], 8 => ["Goods Received Voucher", $dprefix."GRV"], 9 => ["Inter Branch Transfer (IN)", $dprefix."IBT-IN"], 10 => ["PDF Labels Document", $dprefix."PDFL"], 11 => ["Loyalty Cards Document", $dprefix."LCL"], 12 => ["User Cards Document", $dprefix."UBC"], 13 => ["Power User Cards Document",$dprefix."UBC"], ); $tillprinter= $sys_settings{'intranet_printer'}; my %tempdb; tietempdb($database."_".$username, \%tempdb); my $bstartmonth = $sys_settings{'bstartmonth'}; my $budgetyear = $today{year}; $budgetyear-- if ($today{month}<$bstartmonth); $shop{id} = $profile->{shop_id}; $shop{name} = $profile->{profilename}; my $thisshop = $shop{id};# = $settings::shop_id; #/superuser = 0 my $abrevi = "";# = $settings::abrev; #/shop abreviature my $menu_db = $database; my $dbh = DBI->connect("DBI:mysql:$database;host=127.0.0.1",'root','fbg4ips') or die $DBI::errstr; my ($results, $subresults, $subresults1, $ref,$ref1,$ref2,$subref,$subref1); #/ database if (! exists $cacheflag{$database} ) { retreive_stocktypes($database, $profile->{shop_id}); retreive_bins($database, $profile->{shop_id}); #retreive_tax($database, $profile->{shop_id}); retreive_stockcats($database, $profile->{shop_id}); } retreive_tax($database, $profile->{shop_id}); retreive_printers();#2022-09-05 ,get rid of Storable module my $cvat = $btax{$database}{cvat}; my $nvat = $btax{$database}{nvat}; #/ calendar state from cookies if (! $R::year) { $R::year = $tempdb{current_dcyear}; $R::month = $tempdb{current_dcmonth}; } else { $tempdb{current_dcyear} = $R::year; $tempdb{current_dcmonth} = $R::month; } #~ #/---------------------------------------------------------------- #~ open DATA, "$folder/data/shopid.txt"; #~ while () {my ($shopid, $shoptitle) = split (/\:/,$_); $shopname{$shopid}=$shoptitle} #~ close DATA; #~ #/---------------------------------------------------------------- #/rollup is givving shop id if ($R::shopid) {$tempdb{current_shop_id} = $R::shopid} if ($tempdb{current_shop_id} eq "") {$tempdb{current_shop_id} = 1} { #/shop $shop{id}=$thisshop; $shop{name}=$shop{name}; #$shopname{$thisshop}; } # SERVE AJAX LOOKUPS - AJAX CODE (C) ANATOLI RADULOV # %%% %%%% %%% %% %% # %%%% %% %%%% %% %% # %% %% %% %% %% %%%% # %%%%%% % %% %%%%%% %% %% # %% %% %%% %% %% %% %% if ($R::action eq "ajax") { my $temphtml; #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ if ($R::subaction eq "retreive_recipe_units") { #retreive recipe ingredients $results = $dbh->prepare("SELECT yield_unit FROM recipe_yields WHERE recipe_id='$R::recipe_id';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $temphtml .= ""; } elsif ($R::subaction eq "retreive_stockdates") { $temphtml .= ""; } elsif ($R::subaction eq "retreive_stockitems") { $results = $dbh->prepare(" SELECT si.id id,concat(sc.name,' - ',si.name) name, bin, units FROM stockitems si, stockcats sc WHERE sc.id = si.stockcats_id and si.f_status<100 and si.shop_id=$shop{id} and sc.f_status<100 and sc.shop_id=$shop{id} and si.type=$R::stocktype and sc.name like ? and si.name like ? order by name ;") or die $dbh->errstr(); $results->execute("%"."$R::catsfilter"."%","%"."$R::namefilter"."%") or die $results->errstr(); $temphtml .= ""; } #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ print $temphtml; } #/ end ACTION == AJAX #--------------------------------------------------------------------------------- #--------------------------------------------------------------------------------- # END OF AJAX FUNCTIONS # %%% %%%% %%% %% %% # %%%% %% %%%% %% %% # %% %% %% %% %% %%%% # %%%%%% % %% %%%%%% %% %% # %% %% %%% %% %% %% %% #$shopname{$tempdb{current_shop_id}} if ($socketflag == 1 and $R::action eq "popup") {$template = slurpfile("emptypop.htm");} elsif ($R::action ne "ajax") {$template = slurpfile("empty.htm");} $shop{name} =~ s/\n//gsi; $shop{name} =~ s/\r//gsi; $date =~ s/\n//gsi; $date =~ s/\r//gsi; $shop{name} = $database unless $shop{name}; $template =~ s/\@shopname\@/$shop{name}/sgi; $template =~ s/\@date\@/$date/sgi; $template =~ s/\@version\@/$version/sgi; $template =~ s/\@user\@/$sessioner::thisrealname/sgi; #/***************************************************************** #/***************************************************************** #/***************************************************************** #/## START SURFING AND PROGRAMMING ALL ACTIONS!!!!!!!!!!! if ($socketflag == 1 and $R::action eq "tax") { my $temphtml; $onload="document.form1.name.focus();"; $template =~ s/\@title\@/Edit Tax Settings/sgi; $temphtml = "
    "; #/## SUPPLIER EDIT COMMANDS if (($R::command eq "Add Data" and $R::name)) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("INSERT INTO tax (name,percent,date,std) values (?,?,CURRENT_DATE,?);") or die $dbh->errstr(); $results->execute($R::name,$R::percent,$R::std ? 1 : 2) or die $results->errstr(); $mess = "DATA ADDED."; retreive_tax($database, $shop{id}); #&extraplus::menueditor::retreive_tax; } elsif ($R::command eq "delete") { my $results = $dbh->prepare("delete from tax WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "ITEM DELETED."; retreive_tax($database, $shop{id}); } elsif ($R::command eq "Modify Data" and $R::name) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("UPDATE tax SET name=?, percent=?, std=? WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::name,$R::percent,$R::std ? 1 : 2) or die $results->errstr(); $mess = "DATA MODIFIED."; retreive_tax($database, $shop{id}); #&extraplus::menueditor::retreive_tax; } #/## /COMMANDS #/ DRAW TABLE $temphtml .= $table{start}; $temphtml .= "
    NamePercentDateDefault:COMMANDS:
    $ref->{name}$ref->{percent}$ref->{date}$yesno{$ref->{std}}"; $temphtml .= ""; #/check for usage of the supplier $subresults = $dbh->prepare("SELECT count(id) activity FROM menu_tax WHERE tax_id = $ref->{id};") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $subresults->finish(); if ($ref1->{activity}==0) { $temphtml .= "{id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\" onclick=\"return confirm('DELETE ITEM: $ref->{name} ?');\">$icons{d} "; } $temphtml .= " {id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\">$icons{m}"; $temphtml .= "
    {name}\" $calt> {percent}\" $calt> $ref->{date} {std} == 1 ? "checked" : "").">
    ";
    					$temphtml .= $report;
    					$temphtml .= "
    "; } } #/report waitron if ($R::command eq "Turnover Report") { my %sqldate = dateforsql($R::date); my $report; my %tabopscovers; my %turnover; my $covers; my %cash; my $tcash; my %ccard; my $tccard; my %ceft;#STEVEN 2019-06-04 my $teft; my %cheque; my $tcheque; my %account; my $taccount; my %discount; my $tdiscount; my $returns; my %returnsfromwaitrons; my %void_reasons; my %returnsauthor; #/supervisor my $staffmeals; my %bills; my $lastcashuptillid; my $totalturnover; my (%waitrons, %allwaitrons); #/ note: sorting of the waitrons must be done using array not hash! my $results = $dbh->prepare("SELECT id, name,active FROM waitron WHERE f_status<100 and shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $allwaitrons{$ref->{id}} = $ref->{name}; $waitrons{$ref->{id}} = $ref->{name} if ($ref->{active} == 1); } my $between; if ($thisdate_lasttillid >= 0 and $nextdate_lasttillid > 0) { #normal between $between = "and ttod.id between $thisdate_lasttillid and $nextdate_lasttillid"; } elsif ($thisdate_lasttillid > 0 and $nextdate_lasttillid == 0) { # no new cashup $between = "and ttod.id > $thisdate_lasttillid"; } elsif ($thisdate_lasttillid == 0 and $nextdate_lasttillid == 0) { # first cashup $between = ""; } $results = $dbh->prepare(" select inv.stamp stamp, inv.account account, inv.discount discount, inv.cash cash, inv.ccard ccard, inv.ccardtype ccardtype, inv.cheque cheque, (ttod.price*ttod.qty) price, ttod.yield yield, ttod.price uprice, ttod.qty qty, inv.id inv, inv.void_reason void_reason, inv.supervised_by supervised_by, menu.type type, inv.voided voided, tto.id orderid, tabops.visitors covers, tilltables.type ttype, menu_categories.name cname, ttod.name name, tilltables.number number, tabops.id tabopsid from tillordersdetails ttod, tillorders tto, menu, menu_categories, tillinvoices inv, tilltableops tabops, tilltables where menu.menu_category = menu_categories.id and ttod.shop_id=$shop{id} and tto.shop_id=ttod.shop_id and inv.shop_id=ttod.shop_id and tabops.shop_id=ttod.shop_id and tilltables.shop_id=ttod.shop_id and ttod.f_status < 101 and tto.f_status <101 #and ttod.stamp >= '$pdate 04:00:00' #and ttod.stamp <= DATE_ADD('$pdate 04:00:00',INTERVAL 1 DAY) and ttod.id > ( select last_tillid from dcash order by date desc limit 1 ) and tabops.id = tto.tableops_id and tilltables.id = tabops.table_id and ttod.orders_id = tto.id and tto.confirm_status=3 and ttod.plutype = 1 and ttod.menusource = 1 and menu.id = ttod.plu and inv.id = ttod.invoice and (inv.voided is NULL or inv.voided = 2 or inv.voided = 0);") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #print "DEBUG: and ttod.stamp <= DATE_ADD('$pdate 04:00:00',INTERVAL 1 DAY)"; my %tableturnover; my %catturnover; while ($ref = $results->fetchrow_hashref()) { if($ref->{ccardtype} eq 'eft' || $ref->{ccardtype} eq 'snapscan' ||$ref->{ccardtype} eq 'zapper' ){ $ceft{$ref->{inv}} = $ref->{ccard}; }else{ $ccard{$ref->{inv}} = $ref->{ccard}; } $cheque{$ref->{inv}} = $ref->{cheque}; $cash{$ref->{inv}} = $ref->{cash}; $account{$ref->{inv}} = $ref->{account}; $discount{$ref->{inv}} = $ref->{discount}; $bills{$ref->{inv}}{stamp} = $ref->{stamp}; $bills{$ref->{inv}}{plunames}{$ref->{name}} = 1; $bills{$ref->{inv}}{pluprices}{$ref->{name}} = $ref->{uprice}; my $price; $bills{$ref->{inv}}{plutotal}{$ref->{name}} += $ref->{price} ; $price = $ref->{price}; $bills{$ref->{inv}}{pluqty}{$ref->{name}} += $ref->{qty}; $bills{$ref->{inv}}{covers}{$ref->{covers}} = 1; #/ $tabopscovers{$ref->{tabopsid}} = $ref->{covers}; $bills{$ref->{inv}}{tables}{$ref->{number}} = 1; #/distinct table numbers $bills{$ref->{inv}}{total} += $price; $turnover{$ref->{type}} += $price; $tableturnover{$ref->{ttype}} += $price; $catturnover{$ref->{cname}} += $price; if ($ref->{voided} == 2) { $returns += $price; $returnsfromwaitrons{$ref->{inv}} = $R::autocash; $returnsauthor{$ref->{inv}} = $ref->{supervised_by}; $void_reasons{$ref->{inv}} = $ref->{void_reason}; } $staffmeals+=$ref->{price} if ($ref->{ttype} == 4); #/ 4 = staff } #OPEN TABLES $results = $dbh->prepare(" select (ttod.price*ttod.qty) price, ttod.yield yield, ttod.price uprice, ttod.qty qty, menu.type type, tto.id orderid, tto.current_covers covers, tilltables.type ttype, menu_categories.name cname, ttod.name name, tilltables.number number, tabops.id tabopsid from tillordersdetails ttod, tillorders tto, menu, menu_categories, tilltableops tabops, tilltables where menu.menu_category = menu_categories.id and ttod.shop_id=$shop{id} and tto.shop_id=ttod.shop_id and tabops.shop_id=ttod.shop_id and tilltables.shop_id=ttod.shop_id and ttod.f_status < 101 and tto.f_status <101 $between and tabops.id = tto.tableops_id and tilltables.id = tabops.table_id and ttod.orders_id = tto.id and tto.confirm_status=3 and ttod.plutype = 1 and ttod.menusource = 1 and menu.id = ttod.plu and (ttod.invoice is null or ttod.invoice < 0);") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #print "DEBUG: and ttod.stamp <= DATE_ADD('$pdate 04:00:00',INTERVAL 1 DAY)"; %tableturnover = (); %catturnover = (); while ($ref = $results->fetchrow_hashref()) { $ccard{$ref->{inv}} = $ref->{ccard}; $cheque{$ref->{inv}} = $ref->{cheque}; $cash{$ref->{inv}} = $ref->{cash}; $account{$ref->{inv}} = $ref->{account}; $discount{$ref->{inv}} = $ref->{discount}; $bills{$ref->{inv}}{stamp} = $ref->{stamp}; $bills{$ref->{inv}}{plunames}{$ref->{name}} = 1; $bills{$ref->{inv}}{pluprices}{$ref->{name}} = $ref->{uprice}; my $price; $bills{$ref->{inv}}{plutotal}{$ref->{name}} += $ref->{price}; $price = $ref->{price}; $bills{$ref->{inv}}{pluqty}{$ref->{name}} += $ref->{qty}; $bills{$ref->{inv}}{covers}{$ref->{covers}} = 1; #/ $tabopscovers{$ref->{tabopsid}} = $ref->{covers}; $bills{$ref->{inv}}{tables}{$ref->{number}} = 1; #/distinct table numbers $bills{$ref->{inv}}{total} += $price; $turnover{$ref->{type}} += $price; $tableturnover{$ref->{ttype}} += $price; $catturnover{$ref->{cname}} += $price; if ($ref->{voided} == 2) { $returns += $price; $returnsfromwaitrons{$ref->{inv}} = $R::autocash; $returnsauthor{$ref->{inv}} = $ref->{supervised_by}; $void_reasons{$ref->{inv}} = $ref->{void_reason}; } $staffmeals+=$ref->{price} if ($ref->{ttype} == 4); #/ 4 = staff } #/open tables #/##################################### foreach my $tabops (keys %tabopscovers) { $covers += $tabopscovers{$tabops}; } foreach my $inv (keys %cash) { if ($cash{$inv} != 0) { $cash{$inv} = $bills{$inv}{total} - ( $ccard{$inv} + $cheque{$inv} + $account{$inv} + $discount{$inv} ); } } #/foreach my $bill (keys %bills) { #/ $covers += $_ foreach (keys %{$bills{$bill}{covers}} ); #/} $tcash += $_ foreach (values %cash); $tccard += $_ foreach (values %ccard); $teft += $_ foreach (values %ceft);#STEVEN2019-06-04 $tcheque += $_ foreach (values %cheque); $taccount += $_ foreach (values %account); $tdiscount += $_ foreach (values %discount); $totalturnover += $turnover{$_} foreach keys %turnover; my $emptyline; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TIMESTAMP: $datetime",2,1); $report .= "$emptyline\n"; $report .= "*"x$pmax."\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TURNOVER REPORT",2,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"$pdate",2,1); $report .= "$emptyline\n"; $report .= "*"x$pmax."\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"COVERS:",1,1); $emptyline = &align($emptyline,$covers,3,1); $report .= "$emptyline\n"; foreach (sort keys %turnover) { $emptyline = " "x$pmax; $emptyline = &align($emptyline,"$stocktypes{$database}{$_}:",1,1); $emptyline = &align($emptyline,"$currency ".pr($turnover{$_}),3,1); $report .= "$emptyline\n"; } $emptyline = "~"x$pmax; $emptyline = &align($emptyline,"T.TYPE:",1,2); $report .= "$emptyline\n"; foreach (sort keys %tableturnover) { $emptyline = " "x$pmax; $emptyline = &align($emptyline,"$tilltabletype{$_}:",1,1); $emptyline = &align($emptyline,"$currency ".pr($tableturnover{$_}),3,1); $report .= "$emptyline\n"; } $emptyline = "~"x$pmax; $emptyline = &align($emptyline,"CATEGORY:",1,2); $report .= "$emptyline\n"; foreach (sort {$a cmp $b} keys %catturnover) { $emptyline = " "x$pmax; $emptyline = &align($emptyline,"$_:",1,1); $emptyline = &align($emptyline,"$currency ".pr($catturnover{$_}),3,1); $report .= "$emptyline\n"; } $report .= "="x$pmax."\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL GROSS T/O:",1,1); $emptyline = &align($emptyline,"$currency ".pr($totalturnover),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL CASH :",1,1); $emptyline = &align($emptyline,"$currency ".pr($tcash - $staffmeals),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL C.CARD :",1,1); $emptyline = &align($emptyline,"$currency ".pr($tccard),3,1); $report .= "$emptyline\n"; ##STEVEN 2019-06-04 $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL EFT :",1,1); $emptyline = &align($emptyline,"$currency ".pr($teft),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL MOBILE/CHEQUE :",1,1); $emptyline = &align($emptyline,"$currency ".pr($tcheque),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL ACCOUNTS :",1,1); $emptyline = &align($emptyline,"$currency ".pr($taccount),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"TOTAL DISCOUNTS :",1,1); $emptyline = &align($emptyline,"$currency ".pr($tdiscount),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"RETURNS: ",1,1); $emptyline = &align($emptyline,"$currency ".pr($returns),3,1); $report .= "$emptyline\n"; $emptyline = " "x$pmax; $emptyline = &align($emptyline,"STAFF PROMO: ",1,1); $emptyline = &align($emptyline,"$currency ".pr($staffmeals),3,1); $report .= "$emptyline\n"; $report .= "*"x$pmax."\n"; $temphtml .= "
    ";
    					$temphtml .= $report;
    					$temphtml .= "
    "; } #/## MANUAL COMMANDS if ($R::command eq "Add Data" and $demowaitrons{$R::waitron_id} != 1) { $subresults = $dbh->prepare("select max(id) last_tillid from tillordersdetails where f_status<101;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $lasttillid_all = $subref->{last_tillid}; my $results = $dbh->prepare("INSERT INTO dcashitems (dcash_id, shop_id, waitron_id, last_tillid, date, time) values ('$R::id', '$shop{id}', '$R::waitron_id', '$lasttillid_all',current_date,current_time) ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "DATA ADDED."; %calc=(); } elsif ($R::command eq "delete") { $results = $dbh->prepare("UPDATE dcashitems SET f_status=101 WHERE dcash_id=$R::id and id=$R::itemid and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("UPDATE dcashinvoices SET f_status=101 WHERE dcashitems_id=$R::itemid and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("UPDATE dcashturnover SET f_status=101 WHERE dcashinvoices_id in (select id from dcashinvoices where dcashitems_id=$R::itemid and shop_id=$shop{id}) and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("UPDATE pdrcash SET f_status=101 WHERE invoice in (select tillinvoices_id from dcashinvoices where dcashitems_id = $R::itemid and shop_id=$shop{id}) and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "LINE DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { #Update DCASHITEMS $results = $dbh->prepare("UPDATE dcashitems SET waitron_id='$R::waitron_id', s_fee_retained='$R::s_fee_retained', s_fee='$R::s_fee', theshift='$R::shift', f_status=1 WHERE dcash_id=$R::id and id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #update dcashinvoices my %invoice_update; my @pars = $q->param; #/save if unsaved foreach (@pars) { if ($_ =~ /^(covers_)(\d+)/) { $invoice_update{$2}{covers} = $q->param("covers_$2"); } elsif ($_ =~ /^(accounts_)(\d+)/) { $invoice_update{$2}{accounts} = $q->param("accounts_$2"); } elsif ($_ =~ /^(eft_)(\d+)/) { $invoice_update{$2}{eft} = $q->param("eft_$2"); } elsif ($_ =~ /^(creditcards_)(\d+)/) { $invoice_update{$2}{creditcards} = $q->param("creditcards_$2"); } elsif ($_ =~ /^(cheques_)(\d+)/) { $invoice_update{$2}{cheques} = $q->param("cheques_$2"); } } #update the invoices foreach my $invoice (keys %invoice_update) { $results = $dbh->prepare(" update dcashinvoices set f_status=1, covers='$invoice_update{$invoice}{covers}', accounts_total='$invoice_update{$invoice}{accounts}', eft_total='$invoice_update{$invoice}{eft}', creditcards_total='$invoice_update{$invoice}{creditcards}', cheque_total='$invoice_update{$invoice}{cheques}' where tillinvoices_id = '$invoice' and shop_id=$shop{id} and dcashitems_id=$R::itemid ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare(" update tillinvoices set account=?, eft=?, ccard=?, cheque=? where id = ? ;") or die $dbh->errstr(); $results->execute( $invoice_update{$invoice}{accounts} || 0, $invoice_update{$invoice}{eft} || 0, $invoice_update{$invoice}{creditcards} || 0, $invoice_update{$invoice}{cheques} || 0, $invoice ) or die $results->errstr(); } $mess = "DATA MODIFIED."; } elsif ($R::command eq "Update") { #petty cash update my $results = $dbh->prepare("UPDATE dcash SET f_status=1, pettycash='$R::pettycash' WHERE id=$R::id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "PETTYCASH UPDATED."; $pettycash=$R::pettycash; } #/## /COMMANDS #/### DRAW THE TABLE CASHUP --wow. my friend, your head is HUGE than a PC :( $temphtml .= qq~~; $temphtml .= $table{start}; $temphtml .= qq ~ # User Shift Clients Avg. Net GROSS T/O Commission retained Commission NET T/O Excl TAX Staff Promotions Discounts Returns Accounts Eft Credit Cards Mobile/Cheque Cash Deposits Gross Cash~; $temphtml.= " :COMMANDS: " if $lockflag == 1; $temphtml.= ""; #lets collect TIPS 2020-02-21 my $grpTips; my $tips_result = $dbh->prepare("select *, ( dcinv_turnover_total - staffpromo_total - discount_total - returns_total - vat_total ) nettoexc, ( (dcinv_turnover_total - vat_total) - (staffpromo_total*1 - staffpromo_total/dcinv_turnover_total*vat_total) - (discount_total*1 - discount_total/dcinv_turnover_total*vat_total) - (returns_total*1 - returns_total/dcinv_turnover_total*vat_total) ) / covers ahsnet, ( dcinv_turnover_total - staffpromo_total - discount_total - returns_total - eft_total - creditcards_total - accounts_total - cheque_total ) cash FROM dcashinvoices WHERE dcashitems_id in(select id from dcashitems where dcash_id =$R::id )") or die $dbh->errstr(); $tips_result->execute() or die $tips_result->errstr(); #creditcards_total,eft_total,cheque_total,accounts_total,staffpromo_total while (my $ref = $tips_result->fetchrow_hashref()) { #if($ref->{accounts_total} > 0 && $ref->{cash} < 0){ # $grpTips->{$ref->{dcashitems_id}}->{accounts_total_tips} += abs($ref->{cash}); #} # if (dcinv.accounts_total > round(dcinv.dcinv_turnover_total,2) # and dcinv.dcinv_turnover_total > 0, # dcinv.accounts_total - dcinv.dcinv_turnover_total, 0) if($ref->{dcinv_turnover_total}>0 && $ref->{accounts_total} > $ref->{dcinv_turnover_total} ){ $grpTips->{$ref->{dcashitems_id}}->{accounts_total_tips} += $ref->{accounts_total} - $ref->{dcinv_turnover_total}; }else{ $grpTips->{$ref->{dcashitems_id}}->{accounts_total_tips} += 0; } if($ref->{eft_total} > 0 && $ref->{cash} < 0){ $grpTips->{$ref->{dcashitems_id}}->{eft_total_tips} += abs($ref->{cash}); } if($ref->{creditcards_total} > 0 && $ref->{cash} < 0){ $grpTips->{$ref->{dcashitems_id}}->{creditcards_total_tips} += abs($ref->{cash}); } if($ref->{cheque_total} > 0 && $ref->{cash} < 0){ $grpTips->{$ref->{dcashitems_id}}->{cheque_total_tips} += abs($ref->{cash}); } } #end of 2020-02-21 my $turnOver_SQL=qq|select dci.*, dcinv.tillclients_id tillclients_id, waitron.commission, sum(dcinv.covers) covers_total, sum(dcinv.staffpromo_total) staff_promo, sum(dcinv.returns_total) returns_total, sum(dcinv.discount_total) promo_total, sum(dcinv.eft_total) eft_total, sum(dcinv.creditcards_total) creditcard_total, sum(dcinv.accounts_total) accounts_total, sum(dcinv.cheque_total) cheque_total, sum(dcinv.vat_total) vat_total, sum( if(dcinv.creditcards_total > round(dcinv.dcinv_turnover_total,2) and dcinv.dcinv_turnover_total > 0, dcinv.creditcards_total - dcinv.dcinv_turnover_total, 0 ) ) cc_totaltip, sum( if(dcinv.accounts_total > round(dcinv.dcinv_turnover_total,2) and dcinv.dcinv_turnover_total > 0, dcinv.accounts_total - dcinv.dcinv_turnover_total, 0 ) ) acc_totaltip, sum( (dcinv.dcinv_turnover_total - dcinv.staffpromo_total - dcinv.discount_total - dcinv.returns_total- dcinv.vat_total) ) - dci.s_fee AS nettoexc, sum( ( (dcinv.dcinv_turnover_total - dcinv.vat_total) - (dcinv.staffpromo_total - dcinv.staffpromo_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.discount_total - dcinv.discount_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.returns_total - dcinv.returns_total/dcinv.dcinv_turnover_total*dcinv.vat_total) ) / dcinv.covers ) AS avgnet, sum( dcinv.dcinv_turnover_total - dcinv.staffpromo_total - dcinv.discount_total - dcinv.returns_total - dcinv.eft_total - dcinv.creditcards_total - dcinv.accounts_total - dcinv.cheque_total ) - dci.s_fee AS cash, sum( dcinv.dcinv_turnover_total - dcinv.staffpromo_total - dcinv.discount_total - dcinv.returns_total - dcinv.eft_total - dcinv.creditcards_total - dcinv.accounts_total - dcinv.cheque_total ) - dci.s_fee + dci.s_fee_retained AS grosscash, dcash.date date FROM dcash,dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 LEFT JOIN waitron on waitron.id = dci.waitron_id WHERE dcash.id='$R::id' and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 group by dci.id order by dci.id|; #open FILE,">C:/wwwroot/extranet/logfile.txt"; #print FILE $turnOver_SQL; #close FILE; #the cashup ... below $results = $dbh->prepare(" select dci.*, dcinv.tillclients_id tillclients_id, waitron.commission, sum(dcinv.covers) covers_total, sum(dcinv.staffpromo_total) staff_promo, sum(dcinv.returns_total) returns_total, sum(dcinv.discount_total) promo_total, sum(dcinv.eft_total) eft_total, sum(dcinv.creditcards_total) creditcard_total, sum(dcinv.accounts_total) accounts_total, sum(dcinv.cheque_total) cheque_total, sum(dcinv.vat_total) vat_total, sum( if(dcinv.creditcards_total > round(dcinv.dcinv_turnover_total,2) and dcinv.dcinv_turnover_total > 0, dcinv.creditcards_total - dcinv.dcinv_turnover_total, 0 ) ) cc_totaltip, sum( if(dcinv.accounts_total > round(dcinv.dcinv_turnover_total,2) and dcinv.dcinv_turnover_total > 0, dcinv.accounts_total - dcinv.dcinv_turnover_total, 0 ) ) acc_totaltip, sum( (dcinv.dcinv_turnover_total - dcinv.staffpromo_total - dcinv.discount_total - dcinv.returns_total- dcinv.vat_total) ) - dci.s_fee AS nettoexc, sum( ( (dcinv.dcinv_turnover_total - dcinv.vat_total) - (dcinv.staffpromo_total - dcinv.staffpromo_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.discount_total - dcinv.discount_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.returns_total - dcinv.returns_total/dcinv.dcinv_turnover_total*dcinv.vat_total) ) / dcinv.covers ) AS avgnet, sum( dcinv.dcinv_turnover_total - dcinv.staffpromo_total - dcinv.discount_total - dcinv.returns_total - dcinv.eft_total - dcinv.creditcards_total - dcinv.accounts_total - dcinv.cheque_total ) - dci.s_fee AS cash, sum( dcinv.dcinv_turnover_total - dcinv.staffpromo_total - dcinv.discount_total - dcinv.returns_total - dcinv.eft_total - dcinv.creditcards_total - dcinv.accounts_total - dcinv.cheque_total ) - dci.s_fee + dci.s_fee_retained AS grosscash, dcash.date date FROM dcash,dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 LEFT JOIN waitron on waitron.id = dci.waitron_id WHERE dcash.id='$R::id' and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 group by dci.id order by dci.id") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $count = 0; while ($ref = $results->fetchrow_hashref()) { $count++; #/init #$calc{grossto}=$ref->{dci_turnover_total}; #$calc{vat}=$ref->{vat_total}; #$calc{cash}=($calc{grossto} - $ref->{s_fee}) - ($ref->{staff_promo} + $ref->{promo_total} + $ref->{returns_total} + $ref->{accounts_total} + $ref->{creditcard_total} + $ref->{cheque_total}); #$calc{grosscash}=$ref->{s_fee_retained} + $calc{cash}; #$calc{nettoexc} = $calc{grossto} - $ref->{s_fee} - $calc{vat} - $ref->{staff_promo} - $ref->{promo_total} - $ref->{returns_total}; #$calc{nettoexc} = $calc{grossto} - $ref->{s_fee} - $ref->{staff_promo} - $ref->{promo_total} - $ref->{returns_total}; $subresults = $dbh->prepare("select sum(debit) debit, sum(credit) credit from accounts where transaction_type='Cash' AND credit > 0 AND banked =0 AND tillinvoice_id in (select tillinvoices_id from dcashinvoices where dcashitems_id = ?) ") or die $dbh->errstr(); $subresults->execute($ref->{id}) or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $calc{total_debit} += $subref->{debit} ;# if $subref->{account} ==1; $calc{total_credit} += $subref->{credit} ;#if $subref->{account} ==2; $calc{this_debit} = $subref->{debit} ;#if $subref->{account} ==1;; $calc{this_credit} = $subref->{credit} ;#if $subref->{account} ==2; $ref->{grosscash} = $ref->{grosscash} + $subref->{credit}; $ref->{grosscash} = $ref->{grosscash} - $subref->{debit}; if($ref->{avgnet}>0) {$calc{totwaiters}++;} $calc{total_grossto} += $ref->{dci_turnover_total}; $calc{total_cash} += $ref->{cash}; $calc{total_grosscash} += $ref->{grosscash}; $calc{total_nettoexc} += $ref->{nettoexc}; #/$calc{total_avrnet}+=$calc{avrnet}; $calc{total_cvr} += $ref->{covers_total}; $calc{total_s_fee_retained} += $ref->{s_fee_retained}; $calc{total_s_fee} += $ref->{s_fee}; $calc{total_staff_meals} += $ref->{staff_promo}; $calc{total_pro} += $ref->{promo_total}; $calc{total_retrns} += $ref->{returns_total}; $calc{total_accounts} += $ref->{accounts_total}; $calc{total_eft} += $ref->{eft_total}; $calc{total_cred_c} += $ref->{creditcard_total}; $calc{total_cheq} += $ref->{cheque_total}; # query vat for the date that is being cashed up my $taxRes = $dbh->prepare("SELECT percent FROM tax WHERE '$ref->{date}' >= tax.date AND (tax.std = 1 OR tax.std = 9) ORDER BY tax.date DESC LIMIT 1;") or die $dbh->errstr(); $taxRes->execute(); my $taxRef = $taxRes->fetchrow_hashref(); #my $vatval; #$vatval = ($ref->{dci_turnover_total} - $ref->{staff_promo} - $ref->{promo_total} - $ref->{returns_total}) * ($taxRef->{percent}/(100+$taxRef->{percent})); #$calc{total_vat}+=$vatval; $calc{total_vat} += $ref->{vat_total}; if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= " $count ".( $lockflag == 1 ? "{id}\"> $allwaitrons{$ref->{waitron_id}} " : "$allwaitrons{$ref->{waitron_id}}" ).""; $temphtml .= "*" if (! exists $waitrons{$ref->{waitron_id}}); $ref->{avgnet} = 0; $ref->{avgnet} = $ref->{nettoexc} / $ref->{covers_total} if ($ref->{covers_total} != 0); $temphtml .= " $ref->{theshift} ".($ref->{covers_total}*1)." ".pr($ref->{avgnet})." ".pr($ref->{dci_turnover_total})." ".pr($ref->{s_fee_retained})." ".pr($ref->{s_fee}).(($ref->{nettoexc}+$ref->{s_fee}) > 0 ? " (".pr( $ref->{s_fee} / ($ref->{nettoexc}+$ref->{s_fee}) * 100)." %)" : "")." ".pr($ref->{nettoexc})." ".pr($ref->{vat_total})." ".pr($ref->{staff_promo})." ".pr($ref->{promo_total})." ".pr($ref->{returns_total}).""; #$temphtml .=" ".pr($ref->{accounts_total}).( sprintf("%.2f",$ref->{acc_totaltip}) > 0 ? " (tip: $ref->{acc_totaltip}) " : '' )." # ".pr($ref->{eft_total})." # ".pr($ref->{creditcard_total}).( sprintf("%.2f",$ref->{cc_totaltip}) > 0 ? " (tip: $ref->{cc_totaltip}) " : '' )." # ".pr($ref->{cheque_total}).""; $temphtml .=" ".pr($ref->{accounts_total}) .( $grpTips->{$ref->{id}}->{accounts_total_tips} > 0 ? " (tip: " . sprintf("%.2f",$grpTips->{$ref->{id}}->{accounts_total_tips}) .")" : '' )." " .pr($ref->{eft_total}) .( $grpTips->{$ref->{id}}->{eft_total_tips} > 0 ? " (tip: " . sprintf("%.2f",$grpTips->{$ref->{id}}->{eft_total_tips}) .")" : '' )." " .pr($ref->{creditcard_total}).( $grpTips->{$ref->{id}}->{creditcards_total_tips}> 0 ? " (tip: " . sprintf("%.2f",$grpTips->{$ref->{id}}->{creditcards_total_tips}) .")" : '' )." " .pr($ref->{cheque_total}) .( $grpTips->{$ref->{id}}->{cheque_total_tips} > 0 ? " (tip: " . sprintf("%.2f",$grpTips->{$ref->{id}}->{cheque_total_tips}) .")" : '' )." "; $temphtml .=" ".pr($ref->{cash})." ".pr($calc{this_credit})." ".pr($ref->{grosscash}).""; #old vat ".pr($vatval)." $temphtml.="{id}\" onclick=\"return confirm('DELETE LINE # $count ?');\">$icons{d} " if ($lockflag == 1 and $ref->{recordtype} != 1); $temphtml.="{id}\">$icons{m}" if ($lockflag == 1); $temphtml .= " ( {waitron_id}&last_tillid=$ref->{last_tillid}\" title=\"X-report to screen\">ss| {waitron_id}&last_tillid=$ref->{last_tillid}\" title=\"X-report to printer\">sp| {waitron_id}&last_tillid=$ref->{last_tillid}\" title=\"X-report to screen\">fs| {waitron_id}&last_tillid=$ref->{last_tillid}\" title=\"X-report to printer\">fp )"; $temphtml.= " {waitron_id}&last_tillid=$ref->{last_tillid}','','status=yes,scrollbars=yes,width=800,height=550');\">Q&A"; } elsif ($lockflag == 1) { #modify dcashitems #$onload="calc()"; $temphtml .= qq ~
    ~; #$temphtml .= qq~$icons{det} ~ if ($ref->{recordtype} != 1); $temphtml .="$count"; $temphtml .= ""; my %wsel; $wsel{$ref->{waitron_id}}="selected"; if ($ref->{recordtype} != 1) { $temphtml .= ""; } else { $temphtml .= "$waitrons{$ref->{waitron_id}}"; $temphtml .= "{waitron_id}>"; } $temphtml .= " {theshift}\" class=ra $calt_e> $ref->{covers_total} ".pr($ref->{avgnet})." ".pr($ref->{dci_turnover_total})." {s_fee_retained}\" class=ra $calt_e> {s_fee}\" class=ra $calt_e>"; if ($ref->{s_fee} == 0 and $ref->{commission} > 0) { $temphtml .= "
    {nettoexc}*($ref->{commission}/100)')\">Calculate $ref->{commission} %"; } $temphtml .= "".pr($ref->{nettoexc})." ".pr($ref->{vat_total})." ".pr($ref->{staff_promo})." ".pr($ref->{promo_total})." ".pr($ref->{returns_total}).""; #OLD #$temphtml .=" # ".pr($ref->{accounts_total}).( sprintf("%.2f",$ref->{acc_totaltip}) > 0 ? " (tip: $ref->{acc_totaltip}) " : '' )." # ".pr($ref->{eft_total})." # ".pr($ref->{creditcard_total}).( sprintf("%.2f",$ref->{cc_totaltip}) > 0 ? " (tip: $ref->{cc_totaltip}) " : '' )." # ".pr($ref->{cheque_total}).""; $temphtml .=" ".pr($ref->{accounts_total}) .( $grpTips->{$ref->{id}}->{accounts_total_tips} > 0 ? " (tip: " . sprintf("%.2f",$grpTips->{$ref->{id}}->{accounts_total_tips}) .")" : '' )." " .pr($ref->{eft_total}) .( $grpTips->{$ref->{id}}->{eft_total_tips} > 0 ? " (tip: " . sprintf("%.2f",$grpTips->{$ref->{id}}->{eft_total_tips}) .")" : '' )." " .pr($ref->{creditcard_total}).( $grpTips->{$ref->{id}}->{creditcards_total_tips}> 0 ? " (tip: " . sprintf("%.2f",$grpTips->{$ref->{id}}->{creditcards_total_tips}) .")" : '' )." " .pr($ref->{cheque_total}) .( $grpTips->{$ref->{id}}->{cheque_total_tips} > 0 ? " (tip: " . sprintf("%.2f",$grpTips->{$ref->{id}}->{cheque_total_tips}) .")" : '' )." "; $temphtml .=" ".pr($ref->{cash})." ".pr($calc{this_credit})." ".pr($ref->{grosscash})." "; $subresults = $dbh->prepare("select count(id) isnotlast from dcashitems where waitron_id=$ref->{waitron_id} and id > $ref->{id} and f_status < 100 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $isnotlast = $subref->{isnotlast}; $subresults = $dbh->prepare("select count(id) notlastdcash from dcash where id > $R::id and f_status < 100 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $notlastdcash = $subref->{notlastdcash}; $temphtml.="{id}\" onclick=\"return confirm('DELETE LINE # $count ?');\">$icons{d}" if ($lockflag == 1 and ! $isnotlast and ! $notlastdcash); $temphtml .= " "; #Level two - retreive invoices for waitrons $subresults = $dbh->prepare("select *, ( dcinv_turnover_total - staffpromo_total - discount_total - returns_total - vat_total ) nettoexc, ( (dcinv_turnover_total - vat_total) - (staffpromo_total*1 - staffpromo_total/dcinv_turnover_total*vat_total) - (discount_total*1 - discount_total/dcinv_turnover_total*vat_total) - (returns_total*1 - returns_total/dcinv_turnover_total*vat_total) ) / covers ahsnet, ( dcinv_turnover_total - staffpromo_total - discount_total - returns_total - eft_total - creditcards_total - accounts_total - cheque_total ) cash from dcashinvoices where dcashitems_id = $ref->{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $subresults1 = $dbh->prepare("SELECT tilltab.number FROM tillinvoices tillinv, tilltableops tabops, tilltables tilltab WHERE tillinv.id = ? AND tillinv.tableops_id = tabops.id AND tilltab.id = tabops.table_id; ") or die $dbh->errstr(); $subresults1->execute($subref->{tillinvoices_id}) or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); my $tabnumber = $subref1->{number}; $temphtml .= " TABLE: $tabnumber INVOICE {tillinvoices_id}','','status=yes,scrollbars=yes,width=700,height=400');\">$subref->{tillinvoices_id}"; $temphtml .= ""; if ($subref->{staffpromo_total}>0 or $subref->{returns_total}>0) { $temphtml .= "".($subref->{covers}*1).""; } else { #~ $temphtml .= #~ "{tillinvoices_id} class=ra $calt_ec type=text style=\"width: 100%\" value=\"".($subref->{covers}*1)."\"> #~ "; $temphtml .= "{tillinvoices_id}>".($subref->{covers}*1)." "; } $temphtml .= " ".pr($subref->{ahsnet})." $subref->{dcinv_turnover_total} $subref->{date} $subref->{time} ".pr($subref->{nettoexc})." ".pr($subref->{vat_total})." ".pr($subref->{staffpromo_total})." ".pr($subref->{discount_total})." ".pr($subref->{returns_total})." "; if ($subref->{staffpromo_total}>0 or $subref->{returns_total}>0 ) { $temphtml .= " ".pr($subref->{accounts_total})." ".pr($subref->{eft_total})." ".pr($subref->{creditcards_total})." ".pr($subref->{cheque_total})." "; $temphtml .=" ".pr($subref->{cash})."   "; } else { #~ $temphtml .= #~ " {tillinvoices_id} class=ra $calt_ec type=text style=\"width: 100%\" value=\"".($subref->{accounts_total})."\"> ".($subref->{accounts_total} > $subref->{dcinv_turnover_total} ? "
    ($currency".($subref->{accounts_total} - $subref->{dcinv_turnover_total})." tip)" : "")." #~ {tillinvoices_id} class=ra $calt_ec type=text style=\"width: 100%\" value=\"".($subref->{creditcards_total})."\"> ".($subref->{creditcards_total} > $subref->{dcinv_turnover_total} ? "
    ($currency".($subref->{creditcards_total} - $subref->{dcinv_turnover_total})." tip)" : "")." #~ {tillinvoices_id} class=ra $calt_ec type=text style=\"width: 100%\" value=\"".($subref->{cheque_total})."\"> ".($subref->{cheque_total} > $subref->{dcinv_turnover_total} ? "
    ($currency".($subref->{cheque_total} - $subref->{dcinv_turnover_total})." tip)" : "")." #~ "; #$temphtml .= # "{tillinvoices_id}> " .($subref->{accounts_total}) ."" .($subref->{accounts_total} > sprintf("%.2f",$subref->{dcinv_turnover_total}) && $subref->{dcinv_turnover_total} > 0 ? "
    ($currency".($subref->{accounts_total} - $subref->{dcinv_turnover_total})." tip)" : "")." # {tillinvoices_id}> " .($subref->{eft_total}) ."" .($subref->{eft_total} > sprintf("%.2f",$subref->{dcinv_turnover_total}) && $subref->{dcinv_turnover_total} > 0 ? "
    ($currency".($subref->{eft_total} - $subref->{dcinv_turnover_total})." over)" : "")." # {tillinvoices_id}> " .($subref->{creditcards_total}) ."" .($subref->{creditcards_total} > sprintf("%.2f",$subref->{dcinv_turnover_total}) && $subref->{dcinv_turnover_total} > 0 ? "
    ($currency".($subref->{creditcards_total} - $subref->{dcinv_turnover_total})." tip)" : "")." # {tillinvoices_id}> " .($subref->{cheque_total}) ."" .($subref->{cheque_total} > sprintf("%.2f",$subref->{dcinv_turnover_total}) && $subref->{dcinv_turnover_total} > 0 ? "
    ($currency".($subref->{cheque_total} - $subref->{dcinv_turnover_total})." tip)" : "")." # "; $temphtml .= "{tillinvoices_id}> " .($subref->{accounts_total}) ."" .($subref->{accounts_total} && $subref->{cash} < 0 ? "
    ($currency".abs($subref->{cash})." tip)" : "")." {tillinvoices_id}> " .($subref->{eft_total}) ."" .($subref->{eft_total} && $subref->{cash} < 0 ? "
    ($currency".abs($subref->{cash})." tip)" : "")." {tillinvoices_id}> " .($subref->{creditcards_total}) ."" .($subref->{creditcards_total} && $subref->{cash} < 0 ? "
    ($currency".abs($subref->{cash})." tip)" : "")." {tillinvoices_id}> " .($subref->{cheque_total}) ."" .($subref->{cheque_total} && $subref->{cash} < 0 ? "
    ($currency".abs($subref->{cash})." tip)" : "")." "; $temphtml .=" ".pr($subref->{cash})." {tillinvoices_id}> "; $temphtml .= "{tillinvoices_id})\">Edit "; } } $temphtml .= "
    "; }# modify dcashitems } #/ TOTALS CASHUP: my ($prefix, $sufix); $calc{total_avrnet} = ($calc{total_nettoexc} + $calc{total_s_fee}) / $calc{total_cvr} if ($calc{total_cvr});#/ / $calc{totwaiters} if ($calc{totwaiters}); $temphtml .= "   Totals $calc{total_cvr} ".pr($calc{total_avrnet})." "; $temphtml .= " ".pr($calc{total_grossto})." ".pr($calc{total_s_fee_retained})." ".pr($calc{total_s_fee})." ".pr($calc{total_nettoexc})." ".pr($calc{total_vat})." ".pr($calc{total_staff_meals})." "; #/check difference - pdrcash my $subresults = $dbh->prepare("SELECT round(SUM(promo),2) promo, SUM(debtors) debtors, SUM(retrns) retrns FROM pdrcash WHERE f_status<100 and dcash_id=$R::id and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $prefix= ""; $sufix=""; #~ print "DEBUG: |$ref1->{promo}| --- |$calc{total_pro}|"; $calc{total_pro} = sprintf("%.2f", $calc{total_pro}); if ($ref1->{promo} != $calc{total_pro} ) { $cellcolor="style=\"background-color: $errorcolor\""; } else { $cellcolor=""; } $temphtml .= " $prefix".pr($calc{total_pro})."$sufix "; if ($ref1->{retrns}-$calc{total_retrns} !=0) { $cellcolor="style=\"background-color: $errorcolor\""; } else { $cellcolor=""; } $temphtml .= " $prefix".pr($calc{total_retrns})."$sufix "; if ($ref1->{debtors}-$calc{total_accounts} !=0) { $cellcolor="style=\"background-color: $errorcolor\""; } else { $cellcolor=""; } $temphtml .= " $prefix".pr($calc{total_accounts})."$sufix "; #$subresults = $dbh->prepare("select sum(credit) credit from accounts # where account=1 # and transaction_type='Card' # and date = ?;") or die $dbh->errstr(); ## using stamp but not date --reference : a_report_debtors.html ## $subresults = $dbh->prepare("select sum(credit) credit from accounts where account=1 and transaction_type='Card' and date(stamp) = ?;") or die $dbh->errstr(); $subresults->execute($pdate) or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $calc{depcard} = $ref1->{credit}; ################### minus debit ## reference a_report_debtors.html , credit, no need minus debit. #$subresults = $dbh->prepare("select sum(debit) debit from accounts # where account=1 # and transaction_type is null # and date = ?;") or die $dbh->errstr(); #$subresults->execute($pdate) or die $subresults->errstr(); #$ref1 = $subresults->fetchrow_hashref(); #$calc{depcard} = $calc{depcard} - $ref1->{debit}; ###################14000-30427 ##we need to get deposit EFT ,Cheque, Bank Deposit 2020-09-29 ##============================================================ #A and entityid=? $subresults = $dbh->prepare("select sum(credit) credit from accounts where account=1 and date = ? and (transaction_type='EFT' OR transaction_type='Bank Deposit') ;") or die $dbh->errstr(); $subresults->execute($pdate) or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $calc{total_eft} += $subref->{credit}; #B and entityid=? $subresults = $dbh->prepare("select sum(credit) credit from accounts where account=1 and date = ? and transaction_type='Cheque' ;") or die $dbh->errstr(); $subresults->execute($pdate) or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $calc{total_cheq} += $subref->{credit}; #CASH 2022-11-13 $subresults = $dbh->prepare("select sum(credit) credit from accounts where account=1 and date = ? AND tillinvoice_id > 0 and transaction_type='Cash' AND banked=1;") or die $dbh->errstr(); $subresults->execute($pdate) or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $calc{total_dep_cash} += $subref->{credit}; #============================================================ $temphtml .= " ".pr($calc{total_eft})." ".pr($calc{total_cred_c}); if ($calc{depcard} > 0) {#202305 STEVEN $temphtml .= "
    Deposits: $currency ".pr($calc{depcard}) .""; $temphtml .= "
    Total: $currency ".pr($calc{depcard} + $calc{total_cred_c}); } #comments : STEVEN #$calc{total_cheq} = mobile payment #$calc{total_eft} = eft #$calc{total_cred_c}= credit card $temphtml .= " ".pr($calc{total_cheq})." ".pr($calc{total_cash})." ".pr($calc{total_credit})." ".pr($calc{total_grosscash})." "; $temphtml.="   " if ($lockflag == 1); $temphtml.=""; $calc{total_cashdedpetty} = $calc{total_cash} - $pettycash; $calc{cc1}=$calc{total_grossto} - $calc{total_s_fee} - ($calc{total_staff_meals}+$calc{total_pro}+$calc{total_retrns}+$calc{total_accounts}+$calc{total_cred_c}+$calc{total_cheq})-$calc{total_cash}; $calc{cc2}=$calc{total_grossto} - ($calc{total_staff_meals}+$calc{total_pro}+$calc{total_retrns}+$calc{total_accounts}+$calc{total_cred_c}+$calc{total_cheq}+$calc{total_cash}); $calc{tb1}=$calc{total_cashdedpetty} + $calc{total_cheq}; $calc{tb2}=($calc{total_grosscash} + $calc{total_cheq}) - $pettycash; ########## #AND tillinvoice_id > 0 $subresults = $dbh->prepare("select sum(credit) credit from accounts where account=1 and transaction_type='Cash' AND tillinvoice_id = 0 and date = ? and credit > 0") or die $dbh->errstr(); $subresults->execute($pdate) or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $calc{dep} = $ref1->{credit}; #and document_id > 0 $subresults = $dbh->prepare("select sum(credit) credit from accounts where account=2 and document_id = 0 and transaction_type='Cash' and date = ? and credit > 0") or die $dbh->errstr(); $subresults->execute($pdate) or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $calc{dep} += $ref1->{credit}; ########## $subresults = $dbh->prepare("select sum(debit) debit from accounts where account=1 and transaction_type='Cash' and date = ?;") or die $dbh->errstr(); $subresults->execute($pdate) or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $calc{withdraws} = $ref1->{debit}; $subresults = $dbh->prepare("select sum(debit) debit from accounts where account=2 and transaction_type='Cash' and date = ?;") or die $dbh->errstr(); $subresults->execute($pdate) or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $calc{withdraws} += $ref1->{debit}; $calc{withdraws} *= -1; $temphtml .= "CASH ON HAND: ".pr($calc{tb2}).""; $temphtml .= " CASH DEPOSITS: "; $temphtml .= pr($calc{dep} + $calc{total_dep_cash}) ."";#.pr($calc{total_credit}) Nile request 2022 $temphtml .= " CASH WITHDRAWS / PAYMENTS: "; $temphtml .= pr($calc{withdraws}).""; #$calc{ban} = $calc{tb2} + $calc{dep} ; $calc{ban} = $calc{tb2} + $calc{dep} + $calc{total_dep_cash}; #2022-11-14 $calc{ban} = $calc{ban} + $calc{withdraws}; $temphtml .= "TOTAL BANKED: ".pr($calc{ban}).""; $calc{totaldeposits} = $calc{dep} + $calc{depcard}; if ($R::command ne "modify" and $lockflag == 1) { #~ $temphtml .= qq ~ #~ #~   #~ Create manual cashup entry for #~ #~ #~ #~ ~; }; $temphtml .= qq ~ ~ if ($lockflag == 1); $temphtml .= $table{end}; $temphtml .= "
    Total deposits from Credit Cards and Cash = $currency ".pr($calc{totaldeposits})."
    "; #/check difference - pettycash $subresults = $dbh->prepare("SELECT sum(org_price) total_pettycash FROM purchases WHERE f_status<100 and date='$pdate' and type=3 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $calc{pettycash} = $ref1->{total_pettycash}; $results = $dbh->prepare("SELECT SUM(amount) FROM loans WHERE f_status<100 and date='$pdate' and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{pettycash} += $ref; $results = $dbh->prepare("SELECT SUM(amount) FROM creditors WHERE f_status<100 and date='$pdate' and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{pettycash} += $ref; if (sprintf("%.2f",$calc{pettycash}-$pettycash) !=0) { $cellcolor="style=\"background-color: $errorcolor\""; } else { $cellcolor=""; } if ($lockflag == 1) { $temphtml .= "
    PETTY CASH (Don't use together with Creditors - CASH tr.type)

    "; } else { $temphtml .= "
    PETTY CASH
    PETTY CASH FOR THE DAY: $currency $pettycash

    "; } #$temphtml .= "0 vouchers sold today. "; $subresults = $dbh->prepare("select count(id) cnt from dcash where date > '$pdate' and shop_id = $shop{id} and f_status < 100;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); if (! $subref->{cnt}) { #/till cashup $temphtml .= "
    POINT OF SALE
    "; $temphtml .= "USERS WITH TRADE FOR TODAY:"; #/trading start - id $subresults = $dbh->prepare("select last_tillid from dcash where id=$R::id;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $tradestartid = $subref->{last_tillid}; my %cashablewaiters; my %tradewaiters; $subresults = $dbh->prepare(" select distinct ttod.waitron_id waitron_id, waitron.name name from tillorders tto, tillordersdetails ttod, waitron, tillinvoices inv where ttod.f_status < 101 and tto.f_status<101 and ttod.id > '$tradestartid' and tto.confirm_status = 3 and tto.id = ttod.orders_id and waitron.id = ttod.waitron_id and inv.id = ttod.invoice and (inv.voided is NULL or inv.voided = 0 or inv.voided = 2) ;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $cashablewaiters{$subref->{waitron_id}} = $subref->{name}; $tradewaiters{$subref->{waitron_id}} = $subref->{name}; } foreach my $curwaiter (keys %tradewaiters) { #/retreive open tables #/TODO - only active from tilltables my %alltables; $subresults = $dbh->prepare("select distinct table_id from tilltableops where waitron_id='$curwaiter' AND stamp > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 7 DAY) and f_status<101;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $alltables{$subref->{table_id}}=1; } foreach my $curtable (keys %alltables) { $subresults = $dbh->prepare("select action from tilltableops where f_status < 101 and waitron_id = '$curwaiter' and table_id='$curtable' AND stamp > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 7 DAY) order by id desc limit 1;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); if ($subref->{action} != 2 and $subresults->rows) {delete $cashablewaiters{$curwaiter}; #/print "Waitron $waitrons{$curwaiter} Open table id: $curtable |"; } } } delete $tradewaiters{$_} foreach (keys %cashablewaiters); $temphtml .= " "; $temphtml .= qq~
    Report to screen Report Summary Only
    Select Printer for Report:

    Shift: ~; $temphtml .= "

    USERS WITH TRADE & OPEN TABLES:"; foreach (keys %tradewaiters) { $temphtml .= "
  • $tradewaiters{$_}"; } $temphtml .= "
    "; #/calendar JS $temphtml .= qq~ ~; $temphtml .= qq~ ~; $temphtml .= "
    "; $temphtml .= "
  • "; } $temphtml .= "
    POS Users | "; $temphtml .= "Jump to Petty Cash | "; $temphtml .= "Jump to Promo, Debtors & Returns | "; $temphtml .= "{day}/$cashupdate->{month}/$cashupdate->{year}&edate=$cashupdate->{day}/$cashupdate->{month}/$cashupdate->{year}&command=Submit&dcashid=$R::id\">Client Transactions
    "; $temphtml .= "
    Cash Drops
    "; $temphtml .= "
    "; $temphtml .= ""; $temphtml .= ""; } #202305 subactions :detail_deposits elsif($R::subaction eq 'detail_deposites'){ #select * from accounts where account=1 and transaction_type='Card' and date(stamp)='2022-10-29'; my $pdate; $results = $dbh->prepare("SELECT id,pettycash,name, DAYOFMONTH(date) day, MONTH(date) month, YEAR(date) year, last_tillid, date,f_lock FROM dcash WHERE f_status<100 and shop_id = $shop{id} and id=$R::id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $pdate = $ref->{date}; $temphtml .= "$pdate Deposits
    "; $temphtml .= $table{start}; $temphtml .= qq ~ # Description Document Credit Company / Group Name / Contact ~; my $results = $dbh->prepare("select a.*,t.clientgroup,t.name from accounts a LEFT JOIN tillclients t ON t.id=a.entityid where account=1 AND transaction_type='Card' AND date(stamp)=? ") or die $dbh->errstr(); $results->execute($pdate) or die $results->errstr(); my $count =0; while ($ref = $results->fetchrow_hashref()) { $count++; $temphtml .= qq ~ $count $ref->{description} $ref->{document} R $ref->{credit} $ref->{clientgroup} $ref->{name} ~; } $temphtml .=qq|
    |; $temphtml .=""; }#202305 detail_deposits END elsif ($R::subaction eq "editpdr") { %calc=(); #/RESET my $lockflag; $onload="document.form1.doc.focus();"; my $results = $dbh->prepare("SELECT id,name,DAYOFMONTH(date) day,MONTH(date) month,YEAR(date) year,f_lock FROM dcash WHERE f_status<100 and shop_id=$shop{id} and id=$R::id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $lockflag=$ref->{f_lock}; $temphtml .= "You are editing Promo, Debtors & Returns for $ref->{day} $months{$ref->{month}} $ref->{year} created by $ref->{name}

    (R: = REASON; CHK: = CHEQUE #)
    "; #/## COMMANDS PDR if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { my $results = $dbh->prepare("INSERT INTO pdrcash (dcash_id, shop_id, doc, promo, debtors, retrns, authorized, invoice, recordtype) values ('$R::id','$shop{id}','$R::doc', '$R::promo', '$R::debtors','$R::retrns', '$R::authorized',$R::tillinvoices_id,0) ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare(" update dcashinvoices set f_status=1, tillclients_id=$R::clients_id where tillinvoices_id=$R::tillinvoices_id and f_status<100 and shop_id=$shop{id}; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "DATA ADDED."; } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE pdrcash SET f_status=101 WHERE dcash_id=$R::id and id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "LINE DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { my $results = $dbh->prepare("UPDATE pdrcash SET doc='$R::doc', promo='$R::promo', debtors='$R::debtors', retrns='$R::retrns', authorized='$R::authorized', invoice='$R::tillinvoices_id', f_status=1 WHERE dcash_id=$R::id and id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); if ($R::clients_id) { $results = $dbh->prepare(" update dcashinvoices set f_status=1, tillclients_id=$R::clients_id where tillinvoices_id=$R::tillinvoices_id and f_status<100 and shop_id=$shop{id}; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } $mess = "DATA MODIFIED."; } #/## /COMMANDS #/## DRAW TABLE PDR my %client_names; $results = $dbh->prepare("SELECT concat(clientgroup,' -> ',name) name,id from $sharedclients.tillclients where f_status < 100 and shop_id=$sharedclients_shopid; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $client_names{$ref->{id}} = $ref->{name}; } $temphtml .= $table{start}; $temphtml .= qq ~ # Represented by
    (DESCRIPTION/NAME, ID of document) INVOICE CLIENT PROMO RETURNS DEBTORS Authorized by ~; $temphtml.=" :COMMANDS: "if ($lockflag == 1); $temphtml.=""; $results = $dbh->prepare(" SELECT pdrcash.*, dcinv.tillclients_id client_id, dcinv.dcashitems_id dcashitems_id, dcinv.accounts_total accounts_total, dcinv.discount_total discount_total, dcinv.returns_total returns_total FROM pdrcash left join dcashinvoices dcinv on dcinv.tillinvoices_id = pdrcash.invoice and dcinv.f_status<100 and dcinv.shop_id=$shop{id} WHERE pdrcash.shop_id=$shop{id} and pdrcash.f_status<100 and pdrcash.dcash_id=$R::id ORDER BY dcinv.tillinvoices_id ASC;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $count++; if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= " $count $ref->{doc} {invoice}','','status=yes,scrollbars=yes,width=700,height=400');\">$ref->{invoice} $client_names{$ref->{client_id}} ".pr($ref->{promo})." ".pr($ref->{retrns})." ".($ref->{debtors} != $ref->{accounts_total} and $ref->{debtors}>0 ? "(!) ":"").pr($ref->{debtors})." $ref->{authorized}"; $temphtml .= "{id}\" onclick=\"return confirm('DELETE LINE # $count ?');\">$icons{d} " if ($lockflag == 1 and $ref->{recordtype} != 1); $temphtml .= "{id}\">$icons{m} {dcashitems_id}\">Cashup" if ($lockflag == 1); $temphtml .= ""; } elsif($lockflag==1) { $temphtml .= qq ~ $count ~; if ($ref->{recordtype}) { $temphtml .= qq~ $ref->{invoice}~; } else { $temphtml .= qq~~; } $temphtml .= qq~ ~; if ($ref->{client_id}) { $temphtml .= ""; } $temphtml .= qq~ $ref->{promo} $ref->{retrns} ~; } } #/## TOTALS PDR #/comparation/substraction $results = $dbh->prepare("SELECT SUM(promo) promo, SUM(debtors) debtors, SUM(retrns) retrns FROM pdrcash WHERE f_status<100 and dcash_id=$R::id and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); #/$results->finish(); my $subresults = $dbh->prepare(" select sum(discount_total) pro, sum(accounts_total) accounts, sum(returns_total) retrns from dcashinvoices dcinv, dcashitems dci where dcinv.f_status < 100 and dci.f_status < 100 and dcinv.shop_id=$shop{id} and dci.shop_id=$shop{id} and dcinv.dcashitems_id = dci.id and dci.dcash_id=$R::id; ") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $calc{diff} = ($ref->{promo}+$ref->{debtors}+$ref->{retrns}) - ($ref1->{pro}+$ref1->{retrns}+$ref1->{accounts}); $calc{aspercash} = $ref1->{pro}+$ref1->{retrns}+$ref1->{accounts}; $temphtml .= " Total: "; if ($ref->{promo} - $ref1->{pro} != 0) {$cellcolor="style=\"background-color: $errorcolor\""} else {$cellcolor=""} $temphtml .= " ".pr($ref->{promo}).""; if ($ref->{retrns} - $ref1->{retrns} != 0) {$cellcolor="style=\"background-color: $errorcolor\""} else {$cellcolor=""} $temphtml .= " ".pr($ref->{retrns}).""; if ($ref->{debtors} - $ref1->{accounts} != 0) {$cellcolor="style=\"background-color: $errorcolor\""} else {$cellcolor=""} $temphtml .= " ".pr($ref->{debtors}).""; $temphtml .= "  "; if (sprintf("%.2f",$calc{diff}) == 0) {$linecolor=""} else {$linecolor="style=\"background-color: $errorcolor\""} $temphtml .= " Total as per cash-up ".pr($calc{aspercash})."
    Difference for account of Management ".pr($calc{diff})." "; if ($R::command ne "modify" and $lockflag==1) { $temphtml .= qq ~ * ~; $temphtml .= ""; $temphtml .= qq~ ~; } $temphtml .= qq ~ ~if ($lockflag == 1); $temphtml .= $table{end}; $temphtml .= "
    Jump to Cash-up
    "; $temphtml .= "
    "; $temphtml .= ""; $temphtml .= ""; } elsif ($R::subaction eq "unlock") { my $results = $dbh->prepare("SELECT id,name,DAYOFMONTH(date) day,MONTH(date) month,YEAR(date) year,f_lock FROM dcash WHERE f_status<100 and shop_id=$shop{id} and id=$R::id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $temphtml .= "You are unlocking CASH-UP for $ref->{day} $months{$ref->{month}} $ref->{year} created by $ref->{name}

    "; $onload="document.form1.name.focus();"; if ($R::command eq "Proceed") { if (! $R::name or ! $R::reason) { $mess .= "$error PLEASE PROVIDE NAME AND REASON!"; $formvars{name}=$R::name; $formvars{reason}=$R::reason; $temphtml .= getform("unlock", \%formvars); $temphtml =~ s/\@formtitle\@/UNLOCKING DAILY CASHUP/gsi; $temphtml =~ s/\@action\@/Daily Cash-up/gsi; $temphtml =~ s/\@subaction\@/unlock/gsi; $temphtml .= ""; } else { my $results = $dbh->prepare("select date from dcash where shop_id = $shop{id} and id = $R::id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $results = $dbh->prepare("INSERT INTO unlocked (shop_id,date,datestamp,name,reason,section) values ('$shop{id}','$ref->{date}',CURRENT_DATE,'$R::name',?,1);") or die $results->errstr(); $results->execute($R::reason) or die $results->errstr(); $results = $dbh->prepare("UPDATE dcash SET f_lock=1,f_status=1 where shop_id = $shop{id} and id = $R::id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $R::reason =~ s/\n/
    /sgi; $temphtml .= "Succeded by $R::name
    REASON: $R::reason

    "; $temphtml .= ""; } } else { $temphtml .= getform("unlock", undef); $temphtml =~ s/\@formtitle\@/UNLOCKING DAILY CASHUP/gsi; $temphtml =~ s/\@action\@/Daily Cash-up/gsi; $temphtml =~ s/\@subaction\@/unlock/gsi; $temphtml .= ""; } } else { #/ no subaction - just view the calendar #/ Main Cashup lists & delete action. #/## delete dcash if ($R::subaction eq "delete") { my $results = $dbh->prepare("SELECT id,name,DAYOFMONTH(date) day,MONTH(date) month,YEAR(date) year,date,f_lock FROM dcash WHERE f_status<100 and shop_id = $shop{id} and id=$R::id and f_lock =1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{id}) { my $pdate = $ref->{date}; #/TODO - delete everything from retail that is subclass to this day?? There musnt be anything my $results = $dbh->prepare("UPDATE dcash SET f_status=101 where shop_id = $shop{id} and id = $R::id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("UPDATE dcashitems SET f_status=101 where dcash_id = $R::id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("UPDATE purchases SET f_status=101 where date = '$pdate' and type = 3;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("UPDATE loans SET f_status=101 where date = '$pdate';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("UPDATE pdrcash SET f_status=101 where dcash_id = $R::id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess="
    Cash-up for $ref->{day} $months{$ref->{month}} $ref->{year} created by $ref->{name} was deleted."; } else {$mess="
    $error nonexisting record"} } #/## //delete dcash #/## lock dcash if ($R::subaction eq "lock") { my $results = $dbh->prepare("SELECT id,name,DAYOFMONTH(date) day,MONTH(date) month,YEAR(date) year,f_lock FROM dcash WHERE f_status<100 and shop_id = $shop{id} and id=$R::id and f_lock =1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{id}) { my $results = $dbh->prepare("UPDATE dcash SET f_lock=2,f_status=1 where shop_id = $shop{id} and id = $R::id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess="
    Cash-up for $ref->{day} $months{$ref->{month}} $ref->{year} created by $ref->{name} was locked."; } else {$mess="
    $error nonexisting record"} } #/## //lock dcash my $weekbg; $cellcolor = ''; my $yearresults = $dbh->prepare("SELECT DISTINCT YEAR(date) year FROM dcash WHERE f_status<100 and shop_id = $shop{id} order by date;") or die $dbh->errstr(); $yearresults->execute() or die $yearresults->errstr(); $temphtml .= "
    "; $temphtml .= "
    "; $temphtml .= ""; while ($ref = $yearresults->fetchrow_hashref()) { if ($ref->{year} == $today{year}) { $linecolor="bgcolor=$selectioncolor" } else { $linecolor="bgcolor=#FFFFFF"} $temphtml .= ""; if ($ref->{year} == $R::year) { my $monthresults = $dbh->prepare("SELECT DISTINCT MONTH(date) month FROM dcash WHERE f_status<100 and shop_id = $shop{id} and YEAR(date)='$ref->{year}' order by date;") or die $dbh->errstr(); $monthresults->execute() or die $monthresults->errstr(); while ($ref1 = $monthresults->fetchrow_hashref()) { #/print $ref->{"year"};print $ref1->{"month"}; if ($ref1->{month} == $today{month} and $ref->{year} == $today{year}) { $linecolor="bgcolor=$selectioncolor" } else { $linecolor="bgcolor=#FFFFFF"} $temphtml .= ""; if ($ref1->{month} == $R::month) { my $dayresults = $dbh->prepare("SELECT DISTINCT id,DAYOFMONTH(date) as day, name,f_lock,DAYNAME(date) as weekday, WEEK(date,3) as week, date FROM dcash WHERE f_status<100 and shop_id = $shop{id} and YEAR(date)='$ref->{year}' and MONTH(date)='$ref1->{month}' order by date;") or die $dbh->errstr(); $dayresults->execute() or die $dayresults->errstr(); while (my @ref2 = $dayresults->fetchrow_array()) { if ($ref2[5]%2) {$weekbg="bgcolor=$weekcolor"} else {$weekbg="";} if ($ref2[1] == $today{day} and $ref1->{month} == $today{month} and $ref->{year} == $today{year}) { $linecolor="bgcolor=$selectioncolor" } else { $linecolor="bgcolor=#FFFFFF"} $temphtml .= ""; if ($ref2[3] == 1) { my $lockflag=1; $cellcolor =""; $temphtml .= ""; $results = $dbh->prepare("SELECT sum(org_price) compare FROM purchases WHERE shop_id=$shop{id} and f_status<100 and date='$ref2[6]' and type=3;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $subref=$results->fetchrow_hashref(); $calc{pettycompare} = $subref->{compare}; my $results = $dbh->prepare("SELECT SUM(amount) FROM loans WHERE shop_id=$shop{id} and f_status<100 and date='$ref2[6]';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $subref = ($results->fetchrow_array())[0]; $calc{pettycompare} += $subref; $results = $dbh->prepare("SELECT SUM(amount) FROM creditors WHERE shop_id=$shop{id} and f_status<100 and date='$ref2[6]';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $subref = ($results->fetchrow_array())[0]; $calc{pettycompare} += $subref; $subresults = $dbh->prepare("SELECT pettycash compare FROM dcash WHERE shop_id=$shop{id} and f_status<100 and id=$ref2[0];") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref1=$subresults->fetchrow_hashref(); if (sprintf("%.2f",$calc{pettycompare}) != sprintf("%.2f",$subref1->{compare})) {$cellcolor="bgcolor=$errorcolor"; $lockflag=0} else {$cellcolor="";$lockflag=1 if($lockflag)} $temphtml .= ""; $results = $dbh->prepare("SELECT sum(promo) promo,sum(debtors) debtors,sum(retrns) retrns FROM pdrcash WHERE shop_id=$shop{id} and f_status<100 and dcash_id=$ref2[0];") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $subref=$results->fetchrow_hashref(); $results->finish(); $subresults = $dbh->prepare(" select sum(discount_total) promo, sum(accounts_total) debtors, sum(returns_total) retrns from dcashinvoices dcinv, dcashitems dci where dcinv.f_status < 100 and dci.f_status < 100 and dcinv.shop_id=$shop{id} and dci.shop_id=$shop{id} and dcinv.dcashitems_id = dci.id and dci.dcash_id=$ref2[0];") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref1=$subresults->fetchrow_hashref(); $subresults->finish(); if ($subref->{promo} != $subref1->{promo} or $subref->{debtors} != $subref1->{debtors} or $subref->{retrns} != $subref1->{retrns}) {$cellcolor="bgcolor=$errorcolor"; $lockflag=0} else {$cellcolor="";$lockflag=1 if($lockflag)} $temphtml .= ""; $calc{existance}=0; $results = $dbh->prepare("SELECT count(id) as totalcount FROM dcashitems WHERE shop_id=$shop{id} and f_status<100 AND dcash_id=$ref2[0];") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $subref=$results->fetchrow_hashref(); $calc{existance} += $subref->{totalcount}; $results->finish(); $results = $dbh->prepare("SELECT count(id) as totalcount FROM purchases WHERE shop_id=$shop{id} and f_status<100 AND date='$ref2[6]' and type=3;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $subref=$results->fetchrow_hashref(); $calc{existance} += $subref->{totalcount}; $results->finish(); $results = $dbh->prepare("SELECT count(id) as totalcount FROM pdrcash WHERE shop_id=$shop{id} and f_status<100 AND dcash_id=$ref2[0];") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $subref=$results->fetchrow_hashref(); $calc{existance} += $subref->{totalcount}; $results->finish(); if ( $calc{existance} == 0) { $temphtml .= ""; } else { $temphtml .= "";} if ($lockflag){ #/$ref->{year} $temphtml .= ""; } else { $temphtml .= "";} } else { $results = $dbh->prepare("SELECT sum(org_price) compare FROM purchases WHERE shop_id=$shop{id} and f_status<100 and date='$ref2[6]' and type=3;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $subref=$results->fetchrow_hashref(); $calc{pettycompare} = $subref->{compare}; my $results = $dbh->prepare("SELECT SUM(amount) FROM loans WHERE shop_id=$shop{id} and f_status<100 and date='$ref2[6]';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $subref = ($results->fetchrow_array())[0]; $calc{pettycompare} += $subref; $results = $dbh->prepare("SELECT SUM(amount) FROM creditors WHERE shop_id=$shop{id} and f_status<100 and date='$ref2[6]';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $subref = ($results->fetchrow_array())[0]; $calc{pettycompare} += $subref; $subresults = $dbh->prepare("SELECT pettycash compare FROM dcash WHERE shop_id=$shop{id} and f_status<100 and id=$ref2[0];") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref1=$subresults->fetchrow_hashref(); if (sprintf("%.2f",$calc{pettycompare}) != sprintf("%.2f",$subref1->{compare})) {$cellcolor="bgcolor=$errorcolor";} else {$cellcolor=""} #if($settings::clockview == 1) { if($sys_settings{'clockview'} ==1){ $temphtml .= "" } else { $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } $temphtml .= ""; } $temphtml .= ""; } } } } } $temphtml .= "
    Create new cashup
    DATE:Cash-up byActions:
    {year}\">".$ref->{year}."
    {year}&month=$ref1->{month}\">$months{$ref1->{month}}
    $ref2[1] $ref2[2]Cash-upPetty CashPromo, Debtors & Returns{month}} $ref->{year} ?');\">$icons{d} {month}} $ref->{year} ?');\">$icons{lock} Cashup LockedCash-upPetty CashPromo, Debtors & Returns$icons{unlock}
    "; } $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "Edit Waitrons") { my $temphtml; $onload="document.form1.name.focus();"; #/## /WAITRON EDIT COMMANDS if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { my $pinflag = ''; $results = $dbh->prepare(" select * from waitron where pin = ? and active=1 and f_status<100;") or die $dbh->errstr(); $results->execute($R::pin) or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{id}) { $pinflag .= "
    $ref->{name} user has the same pin."; } $results = $dbh->prepare(" select * from supervisor where pin = ? and active=1 and f_status < 101;") or die $dbh->errstr(); $results->execute($R::pin) or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{id}) { $pinflag .= "
    $ref->{name} super user has the same pin."; } if ($pinflag eq '') { if ( $R::name ){ $R::name=~ tr/a-z/A-Z/; #~ my $results = $dbh->prepare(" #~ update waitron set table_id = null where table_id = '$R::table_id' #~ ;") or die $dbh->errstr(); #~ $results->execute() or die $results->errstr(); my $results = $dbh->prepare("INSERT INTO waitron (top_category,table_id, shop_id,name, gender, passid, address, phone, active, pin,commission) values ('$R::top_category','$R::table_id', $shop{id},'$R::name','$R::gender','$R::passid','$R::address','$R::phone','1',?,'$R::commission');") or die $dbh->errstr(); $results->execute($R::pin) or die $results->errstr(); $mess = "DATA ADDED."; } } else { $mess = "ERROR PIN CODE PROBLEM $pinflag"; } } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE waitron SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "USER DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { my $pinflag = ''; $results = $dbh->prepare(" select * from waitron where pin = ? and active=1 and id != '$R::itemid' and f_status < 100;") or die $dbh->errstr(); $results->execute($R::pin) or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{id}) { $pinflag .= "
    $ref->{name} user has the same pin."; } $results = $dbh->prepare(" select * from supervisor where pin = ? and active=1 and f_status < 101;") or die $dbh->errstr(); $results->execute($R::pin) or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{id}) { $pinflag .= "
    $ref->{name} super user has the same pin."; } if ($pinflag eq '') { if ($R::name and $R::name !~ /!DEMO!/sgi){ $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare(" update waitron set table_id = null where table_id = '$R::table_id' ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("UPDATE waitron SET top_category='$R::top_category', table_id='$R::table_id', name='$R::name', gender='$R::gender', passid='$R::passid', address='$R::address', phone='$R::phone', active='$R::active', pin=?, commission='$R::commission', f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::pin) or die $results->errstr(); $mess = "DATA MODIFIED."; } } else { $mess = "ERROR PIN CODE PROBLEM $pinflag"; } } #/## /COMMANDS $template =~ s/\@title\@/Edit Users/sgi; $temphtml = "
    "; $temphtml .= $table{start}; $temphtml .= ""; $temphtml .= " Name Gender ID/PASSPORT NR Address Phone Status Commission % Pin QM Table Top Category :COMMANDS:"; $temphtml .= ""; my $tabledetails; $results = $dbh->prepare("SELECT * FROM tilltables WHERE shop_id = $shop{id} and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $tabledetails->{number}->{$ref->{id}} = $ref->{number}; $tabledetails->{type}->{ $ref->{id} } = $tilltabletype{ $ref->{type} }; $tabledetails->{description}->{ $ref->{id} } = $ref->{description} ; } $results = $dbh->prepare(" SELECT waitron.*, substring_index(group_concat(dcashitems.date order by dcashitems.date desc), ',', 1) last_active, substring_index(group_concat(TIMESTAMPDIFF(DAY,dcashitems.date,current_date) order by dcashitems.date desc), ',', 1) last_active_days, menu_categories.name top_name FROM waitron left join dcashitems on waitron.id = dcashitems.waitron_id and dcashitems.f_status < 100 left join menu_categories on waitron.top_category = menu_categories.id WHERE waitron.f_status<100 group by waitron.id ORDER BY active, name DESC; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { my $warning; if ($ref->{active} == 1 and $ref->{last_active_days} > 30 ) { $warning = " WARNING PLEASE DISABLE THIS USER - No activity for $ref->{last_active_days} days. "; } $ref->{pin} = '*hidden'; $temphtml .= ""; $temphtml .= "{last_active_days} days.\" NOWRAP ".( $ref->{name} =~ /!DEMO!/ ? "style=\"background-color: red\"" : "")."> ".($ref->{active} == 2 ? "not ACTIVE: " : "")."{id}&dcash_id=$R::dcash_id\">$ref->{name} $warning $gender{$ref->{gender}} $ref->{passid} $ref->{address} $ref->{phone} $wstatus{$ref->{active}} $ref->{commission} $ref->{pin} "; if ($ref->{table_id}) { $temphtml .= "$tabledetails->{number}->{$ref->{table_id}} ( $tabledetails->{type}->{$ref->{table_id}} ) $tabledetails->{description}->{$ref->{table_id}}"; } else { $temphtml .= "N/a"; } $temphtml .= ""; if ($ref->{top_category}) { $temphtml .= "$ref->{top_name}"; } else { $temphtml .= "MAIN"; } $temphtml .= ""; $temphtml .= ""; $subresults = $dbh->prepare("SELECT count(id) activity FROM dcashitems WHERE shop_id=$shop{id} and f_status<100 and waitron_id = $ref->{id};") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $subresults->finish(); my $activity; $activity = $ref1->{activity}; $subresults = $dbh->prepare("SELECT count(id) activity FROM tillordersdetails WHERE shop_id=$shop{id} and f_status<100 and waitron_id = $ref->{id};") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $subresults->finish(); $activity += $ref1->{activity}; if (! $activity) { $temphtml .= "{id}&dcash_id=$R::dcash_id\" onclick=\"return confirm('DELETE USER: $ref->{name} ?');\">$icons{d}"; } $temphtml .= " {id}&dcash_id=$R::dcash_id\">$icons{m}"; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; my (%gsel,%asel); $gsel{$ref->{gender}}="selected"; $asel{$ref->{active}}="selected"; $temphtml .= " {name}\" $calt> {passid}\" $calt> {address}\" $calt> {phone}\" $calt> {commission}\" $calt>% {pin}\" $calt>"; $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " * % "; $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= "
    Return to CASH-UP
    " if ($R::dcash_id ne ""); $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } #/ end Waitron editor elsif ($socketflag == 1 and $R::action eq "Edit Employees") { my $temphtml; $onload="document.form1.name.focus();"; #/## /Employees EDIT COMMANDS if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { if ($R::name ){ $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("INSERT INTO employees (shop_id,name, gender, passid, address, phone, active, pin) values ($shop{id},'$R::name','$R::gender','$R::passid','$R::address','$R::phone','1','$R::pin');") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "DATA ADDED."; } } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE employees SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "employees DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { if ($R::name ){ $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("UPDATE employees SET name='$R::name', gender='$R::gender', passid='$R::passid', address='$R::address', phone='$R::phone', active='$R::active', pin='$R::pin', f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "DATA MODIFIED."; } } #/## /COMMANDS $template =~ s/\@title\@/Edit employeess/sgi; $temphtml = "
    "; $temphtml .= $table{start}; $temphtml .= ""; $temphtml .= "NameGenderID #AddressPhoneStatusPin:COMMANDS:"; $temphtml .= ""; $results = $dbh->prepare("SELECT * FROM employees WHERE shop_id = $shop{id} and f_status<100 ORDER BY active, id DESC;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $ref->{pin} =~ tr/0-9/\*/s; $temphtml .= ""; $temphtml .= "$ref->{name}$gender{$ref->{gender}}$ref->{passid}$ref->{address}$ref->{phone}$wstatus{$ref->{active}}$ref->{pin}"; $temphtml .= ""; #/$subresults = $dbh->prepare("SELECT count(id) activity FROM dcashitems WHERE shop_id=$shop{id} and f_status<100 and waitron_id = $ref->{id};") or die $subresults->errstr(); #/$subresults->execute() or die $subresults->errstr(); #/$ref1 = $subresults->fetchrow_hashref(); #/$subresults->finish(); #/ #/activity on till side check if (1) { $temphtml .= "{id}&dcash_id=$R::dcash_id\" onclick=\"return confirm('DELETE USER: $ref->{name} ?');\">$icons{d}"; } $temphtml .= " {id}&dcash_id=$R::dcash_id\">$icons{m}"; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; my (%gsel,%asel); $gsel{$ref->{gender}}="selected"; $asel{$ref->{active}}="selected"; $temphtml .= " {name}\" $calt> {passid}\" $calt> {address}\" $calt> {phone}\" $calt> {pin}\" $calt> "; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " * "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } #/ end Employee editor elsif ($socketflag == 1 and $R::action eq "Repair") { my $dir = opendir(DDD,"/wwwroot/"); my @stfiles = grep {/\.STATION/igs} readdir(DDD); foreach my $file (@stfiles) { unlink "/wwwroot/$file"; } close DDD; my $temphtml; $template =~ s/\@title\@/Repair/sgi; $temphtml = "
    "; $temphtml .= "
    "; $temphtml .= "
    REPAIR/OPTIMIZE FINISHED
    "; my @repair_tables; $results = $dbh->prepare("show tables;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while (my @tarr = $results->fetchrow_array()) { push @repair_tables, $tarr[0]; } $results = $dbh->prepare("show tables from spaceusers;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while (my @tarr = $results->fetchrow_array()) { push @repair_tables, 'spaceusers.'.$tarr[0]; } $temphtml .= "
    REPAIR RESULTS
    "; $temphtml .= ""; $results = $dbh->prepare("repair table ".(join(",",@repair_tables))." $R::mode;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $temphtml .= ""; } $temphtml .= "
    TableOpMsg_typeMsg_text
    $ref->{Table}$ref->{Op}$ref->{Msg_type}$ref->{Msg_text}
    "; $temphtml .= "
    OPTIMIZE RESULTS
    "; $temphtml .= ""; $results = $dbh->prepare("optimize table ".(join(",",@repair_tables)).";") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $temphtml .= ""; } $temphtml .= "
    TableOpMsg_typeMsg_text
    $ref->{Table}$ref->{Op}$ref->{Msg_type}$ref->{Msg_text}
    "; $temphtml .= "
    "; $temphtml .= "
    PLEASE READ THE FOLLOWING:
    Please note that if your Msg_text column doesn't say OK you have lost data records in one of your intranet tables (eg. purchases, POS orders...) in case you get similar message (eg. number of rows changed) you should print this screen and then fax it to the head office. If you have more questions about the repair procedure and backup restoring please contact Anatoli or Bibi. Thank you for your time. Now you can continue working with the intranet and the POS. Everything should be back to normal."; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "Edit Supervisors") { my $temphtml; $onload="document.form1.name.focus();"; #/## /SUPERVISOR EDIT COMMANDS if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { my $pinflag = ''; $results = $dbh->prepare(" select * from waitron where pin = '$R::pin' and active=1 and f_status < 101;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{id}) { $pinflag .= "
    $ref->{name} user has the same pin."; } $results = $dbh->prepare(" select * from supervisor where pin = '$R::pin' and active=1 and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{id}) { $pinflag .= "
    $ref->{name} super user has the same pin."; } if ($pinflag eq '') { if ($R::name) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("INSERT INTO supervisor (shop_id,name, gender, passid, address, phone, active, pin) values ($shop{id},'$R::name','$R::gender','$R::passid','$R::address','$R::phone','1','$R::pin');") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "DATA ADDED."; } } else { $mess = "ERROR PIN CODE PROBLEM $pinflag"; } } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE supervisor SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "SUPERVISOR DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { my $pinflag = ''; $results = $dbh->prepare(" select * from waitron where pin = '$R::pin' and active=1 and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{id}) { $pinflag .= "
    $ref->{name} user has the same pin."; } $results = $dbh->prepare(" select * from supervisor where pin = '$R::pin' and active=1 and id != '$R::itemid' and f_status < 101;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{id}) { $pinflag .= "
    $ref->{name} super user has the same pin."; } if ($pinflag eq '') { if ($R::name) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("UPDATE supervisor SET name='$R::name', gender='$R::gender', passid='$R::passid', address='$R::address', phone='$R::phone', active='$R::active', pin='$R::pin', f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "DATA MODIFIED."; } } else { $mess = "ERROR PIN CODE PROBLEM $pinflag"; } } #/## /COMMANDS $template =~ s/\@title\@/Edit Supervisors/sgi; $temphtml = "
    "; $temphtml .= $table{start}; $temphtml .= ""; $temphtml .= "NameGenderID #AddressPhoneStatusPin:COMMANDS:"; $temphtml .= ""; $results = $dbh->prepare("SELECT * FROM supervisor WHERE shop_id = $shop{id} and f_status<100 ORDER BY active, id DESC;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $ref->{pin} =~ tr/0-9/\*/s; $temphtml .= ""; $temphtml .= "$ref->{name}$gender{$ref->{gender}}$ref->{passid}$ref->{address}$ref->{phone}$wstatus{$ref->{active}}$ref->{pin}"; $temphtml .= ""; $subresults = $dbh->prepare("SELECT count(id) activity FROM tillinvoices WHERE shop_id=$shop{id} and f_status<100 and supervised_by = $ref->{id};") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $subresults->finish(); #/activity on till side check if (! $ref1->{activity}) { $temphtml .= "{id}&dcash_id=$R::dcash_id\" onclick=\"return confirm('DELETE USER: $ref->{name} ?');\">$icons{d}"; } $temphtml .= " {id}&dcash_id=$R::dcash_id\">$icons{m}"; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; my (%gsel,%asel); $gsel{$ref->{gender}}="selected"; $asel{$ref->{active}}="selected"; $temphtml .= " {name}\" $calt> {passid}\" $calt> {address}\" $calt> {phone}\" $calt> {pin}\" $calt> "; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " * "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } #/ end Supervisor editor elsif ($socketflag == 1 and $R::action eq "Edit Tables") { my $temphtml; $onload="document.form1.number.focus();"; #/$onload="document.form1.name.focus();"; #/## /TABLES EDIT COMMANDS if (($R::command eq "Add Data" and $R::number) or ($R::command eq "" and $R::hcommand eq "Add Data")) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("delete from tilltables where f_status = 101;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare("INSERT INTO tilltables (shop_id,number, description, type, seats, location, ordering) values ($shop{id},'$R::number',?,'$R::type','$R::seats','$R::location', '$R::ordering');") or die $dbh->errstr(); $results->execute($R::description) or die $results->errstr(); $mess = "DATA ADDED."; } elsif ($R::command eq "delete" and '$R::itemid') { my $results = $dbh->prepare("select number from tilltables WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $number = $ref->{number}; my $data = eval(tvis_readtmp($database)); foreach my $stage (keys %{ $data->{stages} }) { delete $data->{stages}->{$stage}->{tables}->{$number}; } tvis_writetmp(Dumper($data), $database); $results = $dbh->prepare("delete from tilltables WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "TABLE DELETED."; } elsif (($R::command eq "Modify Data" and $R::number) or ($R::command eq "" and $R::hcommand eq "Modify Data")) { my $results = $dbh->prepare("UPDATE tilltables SET number='$R::number', description=?, type='$R::type', seats='$R::seats', location='$R::location', active='$R::active', f_status=1, ordering='$R::ordering' WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::description) or die $results->errstr(); $mess = "DATA MODIFIED."; if ($R::active == 2) { my $results = $dbh->prepare("select number from tilltables WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $number = $ref->{number}; my $data = eval(tvis_readtmp($database)); foreach my $stage (keys %{ $data->{stages} }) { delete $data->{stages}->{$stage}->{tables}->{$number}; } tvis_writetmp(Dumper($data), $database); } } #/## /COMMANDS $template =~ s/\@title\@/Edit Tables/sgi; $temphtml = "
    "; $temphtml .= " Edit Floor Plans

    "; $temphtml .= $table{start}; $temphtml .= ""; if ($tillmode != 2) { $temphtml .= "Table NumberDescriptionTypeNr. of SeatsLocationStatusPosition:COMMANDS:"; } else { $temphtml .= "Order PlaceholderDescriptionTypeLocationStatusPosition:COMMANDS:"; } $temphtml .= ""; $results = $dbh->prepare("SELECT * FROM tilltables WHERE shop_id = $shop{id} and f_status<100 ORDER BY active DESC, ordering ASC, number ASC;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; if ($tillmode != 2) { $temphtml .= "$ref->{number}$ref->{description}$tilltabletype{$ref->{type}}$ref->{seats}$tilltablelocation{$ref->{location}}$wstatus{$ref->{active}}$ref->{ordering}"; } else { $temphtml .= "$ref->{number}$ref->{description}$tilltabletype{$ref->{type}}$tilltablelocation{$ref->{location}}$wstatus{$ref->{active}}$ref->{ordering}"; } $temphtml .= ""; $subresults = $dbh->prepare("SELECT count(id) activity FROM tilltableops WHERE shop_id=$shop{id} and f_status<100 and table_id = $ref->{id};") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $subresults->finish(); #/activity on till side check if (! $ref1->{activity}) { $temphtml .= "{id}\" onclick=\"return confirm('DELETE TABLE: $ref->{number} ?');\">$icons{d}"; } $temphtml .= " {id}\">$icons{m}"; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; my (%tsel,%lsel,%asel); $tsel{$ref->{type}}="selected"; $lsel{$ref->{location}}="selected"; $asel{$ref->{active}}="selected"; $temphtml .= " {number}\" $calt> {description}\" $calt> "; if ($tillmode != 2) { $temphtml .= "{seats}\" $calt>"; } else { #$temphtml .= "{seats}\" $calt>"; } $temphtml .= " {ordering}\" name=ordering> "; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " "; if ($tillmode != 2) { $temphtml .= ""; } $temphtml .= " * "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } #/ end Tables editor #/# #/# STOCK #/# elsif ($socketflag == 1 and $R::action eq "Stock Acceptance") { my $temphtml; my $finalizeflag; #/SAVE CSTOCK QTY -> TIED HASH my @pars = $q->param; #/save if unsaved foreach (@pars) { if ($_ =~ /^(cs$tempdb{stocktype}_)(\d+)/) { $tempdb{"cs$tempdb{stocktype}_$2"}=$q->param("cs$tempdb{stocktype}_$2"); } } #/### FIFO's and things my $stocktype=$tempdb{stocktype}; #/get all stock in memory: name, bin, units my %stockdetails; $results = $dbh->prepare("select id,name,bin,units from stockitems where f_status<100 and type=$stocktype and shop_id=$shop{id} and stockitem <> 2;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockdetails{name}{$ref->{id}} = $ref->{name}; $stockdetails{bin}{$ref->{id}} = $ref->{bin}; $stockdetails{units}{$ref->{id}} = $ref->{units}; } #/get the last id from purchases at the moment; $results = $dbh->prepare("select max(id) id from purchases where f_status < 100 and shop_id=$shop{id}") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $max_pid = $ref->{id}; #/determine last pid for the stocktype from PREVIOUS STOCK $results = $dbh->prepare("select last_pid,date from cstock where f_status<100 and stocktype=$stocktype and shop_id=$shop{id} order by id desc limit 1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $last_pid = $ref->{last_pid}*1; my $last_date = $ref->{date}; $last_date = "1900-01-01" if (! $last_date); #/purchases sinse last pid excluding my %last_purchases; $results = $dbh->prepare("select si.id id, si.name name, si.units units, si.bin bin, sum(pu.qty) qty, sum(pu.price*pu.qty) totalprice, pu.price uprice from purchases pu,stockitems si where si.f_status<100 and pu.f_status<100 and si.shop_id=$shop{id} and pu.shop_id=si.shop_id and si.id=pu.stockitems_id and si.type=$stocktype and pu.id>$last_pid #/cs:last_pid and (pu.cnote != 1 or pu.cnote is NULL or pu.cnote = 0) group by si.id order by name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_purchases{$ref->{id}}{qty} = $ref->{qty}; $last_purchases{$ref->{id}}{value} = $ref->{totalprice}; } #/last closing stock qty and value my %last_closingstock; $results = $dbh->prepare("select si.id id, si.name name, sum(cs.qty) qty, sum(cs.value) stockvalue, sum(cs.value)/sum(cs.qty) uprice from cstock cs, stockitems si where si.f_status<100 and cs.f_status<100 and si.shop_id=$shop{id} and cs.shop_id=si.shop_id and si.id=cs.stockitems_id and si.type=$stocktype and cs.last_pid=$last_pid #/cs:last_pid and cs.date='$last_date' group by si.id order by si.name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_closingstock{$ref->{id}}{qty} = $ref->{qty}; $last_closingstock{$ref->{id}}{value} = $ref->{stockvalue}; } #/last credit notes - since last_pid my %last_creditnotes; $results = $dbh->prepare("select si.id id, si.name name, sum(pu.qty) qty, sum(pu.price*pu.qty) totalprice, pu.price uprice from purchases pu,stockitems si where si.f_status<100 and pu.f_status<100 and si.shop_id=$shop{id} and pu.shop_id=si.shop_id and si.id=pu.stockitems_id and si.type=$stocktype and pu.id>$last_pid #/cs:last_pid and pu.cnote = 1 group by si.id order by name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_creditnotes{$ref->{id}}{qty} = $ref->{qty}; $last_creditnotes{$ref->{id}}{value} = $ref->{totalprice}; } #/calculate the availables; my %availables; foreach my $id (keys %{$stockdetails{name}}) { my $available_qty; $available_qty = $last_closingstock{$id}{qty} + ($last_purchases{$id}{qty} - $last_creditnotes{$id}{qty}); #/$last_creditnotes{$ref->{id}}{qty} used because of need to store pvalue in this table next if ($available_qty <= 0 and ! $last_creditnotes{$id}{qty} and $show_noqty_stock == -1); $availables{$id} = $available_qty; } #/by bin my $sortage = 'name'; #/retreive all stockIDs with their FIFO last pids my %fifodetails; $results = $dbh->prepare("select stockitems_id id,debited_pid,credit_left from cstock where f_status<100 and cstock.shop_id=$shop{id} and date='$last_date' and stocktype=$stocktype;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $fifodetails{$ref->{id}}{debited_pid} = $ref->{debited_pid}; $fifodetails{$ref->{id}}{credit_left} = $ref->{credit_left}; } #/retreive debited_pid, credit_left from older stock, and not previous, because of missing record in previous. It is missing because the item had no availability foreach my $id ( keys %last_purchases ) { if (! exists $fifodetails{$id}) { $results = $dbh->prepare(" select debited_pid,credit_left from cstock where f_status<100 and shop_id=$shop{id} and stockitems_id=$id order by date desc limit 1; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $fifodetails{$id}{debited_pid} = $ref->{debited_pid}; $fifodetails{$id}{credit_left} = $ref->{credit_left}; } } my %purchases_for_use; foreach my $id (keys %availables) { $results = $dbh->prepare(" SELECT pu.id id, CASE WHEN pu.cnote != 1 or pu.cnote is NULL or pu.cnote = 0 then 0 WHEN pu.cnote = 1 then 1 END cnote, pu.qty qty, pu.price price from purchases pu where pu.f_status<100 and pu.shop_id=$shop{id} and pu.stockitems_id='$id' and pu.id>='$fifodetails{$id}{debited_pid}' and pu.qty > 0 ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $purchases_for_use{$id}{$ref->{id}}{qty} = $ref->{qty}; $purchases_for_use{$id}{$ref->{id}}{price} = $ref->{price}; $purchases_for_use{$id}{$ref->{id}}{cnote} = $ref->{cnote}; } } my %fiforesultz; foreach my $id (keys %availables) { ( $fiforesultz{$id}{available_value}, $fiforesultz{$id}{creditnotes_value}, $fiforesultz{$id}{credits_left}, $fiforesultz{$id}{debited_pid}, $fiforesultz{$id}{usage_qty}, $fiforesultz{$id}{usage_value}, $fiforesultz{$id}{cs_qty}, $fiforesultz{$id}{cs_value} ) = fifo_hash_for_use($id, $last_closingstock{$id}{qty}, $last_closingstock{$id}{value}, $fifodetails{$id}{debited_pid}, $fifodetails{$id}{credit_left}, \%last_creditnotes, \%last_purchases, $last_pid, \%purchases_for_use, \%tempdb ); } $results = $dbh->prepare(" select current_time stamp;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $Current_Timestamp = $ref->{stamp}; #/remove this in one month time. #$results = $dbh->prepare("alter table cstock change credit_left credit_left decimal(7,3);") or die $dbh->errstr(); #$results->execute() or die $results->errstr(); my %sqldate = dateforsql($R::date); $results = $dbh->prepare(" insert into cstock (shop_id, stockitems_id, stocktype, value, pvalue, last_pid, qty, debited_pid, credit_left, date) values ( '$shop{id}', ?, '$stocktype', ?, ?, '$max_pid', ?, ?, ?, '$sqldate{year}-$sqldate{month}-$sqldate{day} $Current_Timestamp'); ") or die $dbh->errstr(); foreach my $id (keys %availables) { #/pvalue is cnotes value $results->execute($id, $fiforesultz{$id}{cs_value}, $fiforesultz{$id}{creditnotes_value}, $fiforesultz{$id}{cs_qty}, $fiforesultz{$id}{debited_pid}, $fiforesultz{$id}{credits_left}) or die $results->errstr(); } #/## Done. #/DISPLAY SOME INFO ON THE SCREEN $template =~ s/\@title\@/FINISHED EDITING CLOSING STOCK/sgi; $temphtml = "
    "; $temphtml .= "Your Closing Stock is Finished Successfuly"; $temphtml .= "
    "; $tempdb{stockflag} = 2; #/todo (enable when both is finalized?) #/delete the saved stemps foreach (@pars) { if ($_ =~ /^(cs$tempdb{stocktype}_)(\d+)/) { delete $tempdb{"cs$tempdb{stocktype}_$2"}; } } $template =~ s/\@content\@/$temphtml/sgi; } #/ end Finalize Closing Stock elsif ($socketflag == 1 and $R::action eq "Cancel Closing Stock Edit") { my $temphtml; $template =~ s/\@title\@/EDITING CLOSING STOCK CANCELED/sgi; $temphtml = "
    "; $temphtml .= "Your Closing Stock Editing is Canceled"; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; $tempdb{stockflag} = 2; $results = $dbh->prepare(" SELECT DISTINCT pu.stockitems_id sid,si.name name, si.units units from purchases pu, stockitems si where pu.stockitems_id = si.id and si.type <=2 and pu.shop_id=$shop{id} and pu.f_status<100 and si.shop_id=$shop{id} and si.f_status<100 ORDER BY units,name;"); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { delete $tempdb{"cs$tempdb{stocktype}_$ref->{sid}"}; } } #/ Cancel Closing Stock Edit elsif ($socketflag == 1 and $R::action eq "Finalize Opening Stock") { my $temphtml; $template =~ s/\@title\@/FINISHED EDITING OPENING STOCK/sgi; $temphtml = "
    "; $temphtml .= "Your Opening Stock editor is locked successfuly"; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; $tempdb{stockflag} = 2; } #/ end Finalize Opening Stock elsif ($socketflag == 1 and $R::action eq "Edit Closing Stock") { $tempdb{stockflag} = 3; #/used in main menu to disable purchases && cashup my $finalizeflag = 1; my $sqlorder; #/type 1 = by name; type 2=by bin #/retreive perm stage #/$tempdb{cstockviewtype} = $R::viewtype if ($R::viewtype); #/permanent stage - viewtype #/$tempdb{cstockviewtype} = 1 if (! $tempdb{cstockviewtype}); #/retreive permanent stages #/$tempdb{stocktype} = $R::stocktype if ($R::stocktype); #/no permanent stages yet - init #/if (! $tempdb{stocktype}) {$tempdb{stocktype}=1}; my %ordertype = (1 => 'name', 2 => 'bin'); my $orderby = $ordertype{$tempdb{cstockviewtype}}; my $stocktype=$tempdb{stocktype}; fix_fifo( {dbh => $dbh, shop => \%shop }, $stocktype ) if $thisshop != 0; # fix fifo if not my $temphtml; my %calc; $template =~ s/\@title\@/Edit Closing Stock $cstockviewtypes{$tempdb{cstockviewtype}}/sgi; $temphtml = "
    "; $temphtml .= " $stocktypes{$database}{$tempdb{stocktype}} Stock Sheet

    "; #/COMMANDS my $copy_save_msg = ""; if ($R::command eq "Save Closing Stock") { my @pars = $q->param; foreach (@pars) { if ($_ =~ /^(cs$tempdb{stocktype}_)(\d+)/) { $tempdb{"cs$tempdb{stocktype}_$2"}=$q->param("cs$tempdb{stocktype}_$2"); } } #let's try copy here #insert into stockissue (date,direction,stocktype,stockitems_id,qty)values (?,?,?,?,?) #direction is 2 if($q->param('copypastesave_flag') ==1){ my @val = $q->param('stockitems_id'); my $f->{stockitems_id} = @val>1 ? \@val : $val[0]; my $ids = join(',',grep{/^\d+$/}@{&ARef($f->{stockitems_id})}); if($ids){ my %sqldate = dateforsql($R::date); $results = $dbh->prepare("SELECT id, bin, units,sku ,qty FROM stockitems WHERE id in($ids)"); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { my $id = $ref->{id}; my $cs1_count = $q->param("cs$tempdb{stocktype}_$id"); $dbh->do("insert into stockissue (date,direction,stocktype,stockitems_id,qty) values (?,?,?,?,?)",undef, "$sqldate{year}-$sqldate{month}-$sqldate{day}", 2, $stocktype, $ref->{id}, $cs1_count||0 ); } $copy_save_msg = "Selected stock items have been copied."; } } } sub ARef{ my $data=shift; $data=[] unless $data; $data=[$data] unless ref($data) eq 'ARRAY'; return $data; } #/All queries for the screen #/get all stock in memory: name, bin, units my %stockdetails; $results = $dbh->prepare(" SELECT si.id,concat(sc.name,' - ',si.name) name, bin, units,sku FROM stockitems si LEFT JOIN stockcats sc ON sc.id = si.stockcats_id WHERE si.f_status<100 and si.shop_id=$shop{id} and sc.f_status<100 and sc.shop_id=$shop{id} and si.type=$stocktype; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockdetails{name}{$ref->{id}} = $ref->{name}; $stockdetails{bin}{$ref->{id}} = $ref->{bin}; $stockdetails{units}{$ref->{id}} = $ref->{units}; $stockdetails{sku}{$ref->{id}} = $ref->{sku}; $stockdetails{stitem_id}{$ref->{id}} = $ref->{id}; } #/determine last pid for the stocktype $results = $dbh->prepare("select last_pid,date from cstock where stocktype=$stocktype and shop_id=$shop{id} and f_status<100 order by id desc limit 1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $last_pid = $ref->{last_pid}*1; my $last_date = $ref->{date}; $last_date = "1900-01-01" if (! $last_date); #/purchases sinse last pid excluding my %last_purchases; $results = $dbh->prepare("select si.id id, si.name name, si.units units, si.bin bin, sum(pu.qty) qty, sum(pu.org_price) totalprice, sum(pu.org_price)/sum(pu.qty) uprice from purchases pu,stockitems si where si.f_status<100 and pu.f_status<100 and si.shop_id=$shop{id} and pu.shop_id=si.shop_id and si.id=pu.stockitems_id and si.type=$stocktype and pu.id>$last_pid #/cs:last_pid and (pu.cnote != 1 or pu.cnote is NULL or pu.cnote = 0) group by si.id order by name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_purchases{$ref->{id}}{qty} = $ref->{qty}; $last_purchases{$ref->{id}}{value} = $ref->{totalprice}; } #/last closing stock qty and value my %last_closingstock; $results = $dbh->prepare("select si.id id, si.name name, sum(cs.qty) qty, sum(cs.value) stockvalue, sum(cs.value)/sum(cs.qty) uprice from cstock cs, stockitems si where cs.f_status<100 and si.f_status<100 and si.shop_id=$shop{id} and cs.shop_id=si.shop_id and si.id=cs.stockitems_id and si.type=$stocktype and cs.last_pid=$last_pid #/cs:last_pid and cs.date='$last_date' group by si.id order by si.name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_closingstock{$ref->{id}}{qty} = $ref->{qty}; $last_closingstock{$ref->{id}}{value} = $ref->{stockvalue}; } #/last credit notes - since last_pid my %last_creditnotes; $results = $dbh->prepare("select si.id id, si.name name, sum(pu.qty) qty, sum(pu.org_price) totalprice, sum(pu.org_price)/sum(pu.qty) uprice from purchases pu,stockitems si where pu.f_status<100 and si.f_status<100 and si.shop_id=$shop{id} and pu.shop_id=si.shop_id and si.id=pu.stockitems_id and si.type=$stocktype and pu.id>$last_pid #/cs:last_pid and pu.cnote = 1 group by si.id order by name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_creditnotes{$ref->{id}}{qty} = $ref->{qty}; $last_creditnotes{$ref->{id}}{value} = $ref->{totalprice}; } #/calculate the availables; my %availables; foreach my $id (keys %{$stockdetails{name}}) { my $available_qty = $last_closingstock{$id}{qty} + ($last_purchases{$id}{qty} - $last_creditnotes{$id}{qty}); next if ($available_qty <= 0 and $show_noqty_stock == -1); $availables{$id} = $available_qty; } #/by bin / by name my $sortage = $orderby; #///All queries #/ #/ PRINT CURRENT CLOSING STOCK EDITOR #/ $temphtml .= $table{start}; if($copy_save_msg){ $temphtml .= qq|$copy_save_msg|; } $temphtml .= ""; $temphtml .= qq| SKU STOCK ITEM BIN PREVIOUS STOCK PURCHASES CREDIT NOTES STOCK ON HAND BEFORE SAVE NEW STOCK USAGE |; foreach my $id ( sort {$stockdetails{$sortage}{$a} cmp $stockdetails{$sortage}{$b}} sort {$stockdetails{name}{$a} cmp $stockdetails{name}{$b}} keys %availables) { next if ($availables{$id} <= 0 and $show_noqty_stock == -1); if ( ($availables{$id} < 0) or (rn3($availables{$id} - $tempdb{"cs$tempdb{stocktype}_$id"}) < 0) ) { $finalizeflag = 0; } if ($tempdb{"cs$tempdb{stocktype}_$id"} ne "") {$linecolor=""} else {$linecolor="style=\"background-color: $errorcolor\""}; $temphtml .= ""; if($tempdb{"cs$tempdb{stocktype}_$id"} ne ""){ $temphtml .=qq||; }else{ $temphtml .=qq||; } $temphtml .= " $stockdetails{sku}{$id} $stockdetails{name}{$id} $bins{$database}{$stockdetails{bin}{$id}} ".($last_closingstock{$id}{qty}*1)." $units{$stockdetails{units}{$id}} ".($last_purchases{$id}{qty}*1)." $units{$stockdetails{units}{$id}} ".($last_creditnotes{$id}{qty}*1)." $units{$stockdetails{units}{$id}} ".($availables{$id} < 0 ? " " : "")."".rn3($availables{$id})." $units{$stockdetails{units}{$id}} ".$tempdb{"cs$tempdb{stocktype}_$id"}."
     $units{$stockdetails{units}{$id}}
    ".(rn3($availables{$id} - $tempdb{"cs$tempdb{stocktype}_$id"}) < 0 ? " " : "").(rn3($availables{$id} - $tempdb{"cs$tempdb{stocktype}_$id"}) )." $units{$stockdetails{units}{$id}}"; $temphtml .= ""; } $temphtml .= $table{end}; $temphtml .= qq~ ~; $temphtml .= qq|
    |; $temphtml .= " "; $temphtml .= qq~

    SELECT STOCK TAKE DATE: Calendar Pop-up ~; $temphtml .= "

    "; $temphtml .= "

    "; $temphtml .= "

    "; $temphtml .= qq|

    |; $temphtml .= ""; $temphtml .= "
    ";#variance_center $template =~ s/\@content\@/$temphtml/sgi; } #/ end CLOSING STOCK EDITOR elsif ($socketflag == 1 and $R::action eq "Stock Sheet") { my $temphtml; my %calc; my $sqlorder; #/type 1 = by name; type 2=by bin #/retreive perm stage $tempdb{cstockviewtype} = $R::viewtype if ($R::viewtype); #/permanent stage - viewtype $tempdb{cstockviewtype} = 1 if (! $tempdb{cstockviewtype}); #/retreive permanent stages $tempdb{stocktype} = $R::stocktype if ($R::stocktype); #/no permanent stages yet - init $tempdb{stocktype} = (sort {$a <=> $b} keys %{ $stocktypes{$database} } )[0] if (! $tempdb{stocktype}); my %ordertype = (1 => 'name', 2 => 'bin'); my $orderby = $ordertype{$tempdb{cstockviewtype}}; $template =~ s/\@title\@/View Stock $cstockviewtypes{$tempdb{cstockviewtype}}/sgi; $temphtml = "
    "; $temphtml .= ""; $temphtml .= "Filter by SKU, Category or Description:
    "; my $stocktype=$tempdb{stocktype}; #/All queries for the screen #/get all stock in memory: name, bin, units my %stockdetails; $results = $dbh->prepare(" SELECT si.sku,si.id,sc.name cat, si.name name, bin, units,cost FROM stockitems si LEFT JOIN stockcats sc ON sc.id = si.stockcats_id WHERE si.f_status<100 and si.shop_id=$shop{id} and sc.f_status<100 and sc.shop_id=$shop{id} and si.type=$stocktype; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockdetails{name}{$ref->{id}} = $ref->{name}; $stockdetails{bin}{$ref->{id}} = $ref->{bin}; $stockdetails{units}{$ref->{id}} = $ref->{units}; $stockdetails{cost}{$ref->{id}} = $ref->{cost}; $stockdetails{sku}{$ref->{id}} = $ref->{sku}; $stockdetails{cat}{$ref->{id}} = $ref->{cat} } #/determine last pid for the stocktype $results = $dbh->prepare("select last_pid,date from cstock where stocktype=$stocktype and shop_id=$shop{id} and f_status<100 order by id desc limit 1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $last_pid = $ref->{last_pid}*1; my $last_date = $ref->{date}; #/purchases sinse last pid excluding $last_date = "1900-01-01" if (! $last_date); my %last_purchases; $results = $dbh->prepare("select si.id id, si.name name, si.units units, si.bin bin, sum(pu.qty) qty, sum(pu.org_price) totalprice, sum(pu.org_price)/sum(pu.qty) uprice from purchases pu,stockitems si where si.f_status<100 and pu.f_status<100 and si.shop_id=$shop{id} and pu.shop_id=si.shop_id and si.id=pu.stockitems_id and si.type=$stocktype and pu.id>$last_pid #/cs:last_pid and (pu.cnote != 1 or pu.cnote is NULL or pu.cnote = 0) group by si.id order by name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_purchases{$ref->{id}}{qty} = $ref->{qty}; $last_purchases{$ref->{id}}{value} = $ref->{totalprice}; } #/last closing stock qty and value my %last_closingstock; $results = $dbh->prepare("select si.id id, si.name name, sum(cs.qty) qty, sum(cs.value) stockvalue, sum(cs.value)/sum(cs.qty) uprice from cstock cs, stockitems si where cs.f_status<100 and si.f_status<100 and si.shop_id=$shop{id} and cs.shop_id=si.shop_id and si.id=cs.stockitems_id and si.type=$stocktype and cs.last_pid=$last_pid #/cs:last_pid and cs.date='$last_date' group by si.id order by si.name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_closingstock{$ref->{id}}{qty} = $ref->{qty}; $last_closingstock{$ref->{id}}{value} = $ref->{stockvalue}; } #/last credit notes - since last_pid my %last_creditnotes; $results = $dbh->prepare("select si.id id, si.name name, sum(pu.qty) qty, sum(pu.org_price) totalprice, sum(pu.org_price)/sum(pu.qty) uprice from purchases pu,stockitems si where pu.f_status<100 and si.f_status<100 and si.shop_id=$shop{id} and pu.shop_id=si.shop_id and si.id=pu.stockitems_id and si.type=$stocktype and pu.id>$last_pid #/cs:last_pid and pu.cnote = 1 group by si.id order by name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_creditnotes{$ref->{id}}{qty} = $ref->{qty}; $last_creditnotes{$ref->{id}}{value} = $ref->{totalprice}; } #/calculate the availables; my %availables = (); foreach my $id (keys %{$stockdetails{name}}) { my $available_qty; $available_qty = $last_closingstock{$id}{qty} + ($last_purchases{$id}{qty} - $last_creditnotes{$id}{qty}); next if ($available_qty <= 0 and $show_noqty_stock == -1); $availables{$id} = $available_qty || 0; } #/by bin / by name my $sortage = $orderby; #///All queries $temphtml .= " LAST STOCK TAKE DATE: $last_date $stocktypes{$database}{$tempdb{stocktype}} Stock Sheet
    "; $temphtml .= "STOCK TYPE:
    "; foreach my $acctype (sort keys %{ $stocktypes_breakdown{$database} }) { $temphtml .= "($account_types{$acctype}: "; foreach (sort {$stocktypes{$database}{$a} cmp $stocktypes{$database}{$b}} keys %{ $stocktypes_breakdown{$database}{$acctype} } ) { $temphtml .= "[".($tempdb{stocktype} == $_ ? " $stocktypes{$database}{$_} " : "$stocktypes{$database}{$_}")."]"; } $temphtml .= ")
    "; } $temphtml .= "
    "; #THEORY #GRAND RETREIVAL #retreive ingredient details my %idetails; $results = $dbh->prepare("select id,name,stockitems_id,units from ritems;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ $idetails{$ref->{id}}{stockitems_id} = $ref->{stockitems_id}; $idetails{$ref->{id}}{units} = $ref->{units}; } my %latestyields; $results = $dbh->prepare(" select id ritem_id, yield from ritems;" ) or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $idetails{$ref->{ritem_id}}{yield} = $ref->{yield}; } my %stockuse; my %ingredientuse; my %pluuse; my %returns; $last_date = "1900-01-01" if (! $last_date); #print "'$last_date 06:00:00' ST: $tempdb{stocktype}"; #TO RETREIVE TOTAL PLU QTYs (based on QTY or YIELD column); my %onetoone; $results = $dbh->prepare(" select menu.id pluid, inv.isrefund, menu.stockid stockid, inv.voided voided, sum(qty) totalqty from tillordersdetails ttod, tillorders tto, menu, tillinvoices inv, tilltableops tabops, tilltables where ttod.f_status < 101 and tto.f_status <101 and ttod.stamp >= '$last_date 06:00:00' #and menu.type=1 and tabops.id = tto.tableops_id and tilltables.id = tabops.table_id and ttod.orders_id = tto.id and tto.confirm_status=3 and menu.type = '$tempdb{stocktype}' and ttod.menusource = 1 and menu.id = ttod.plu and inv.id = ttod.invoice and (inv.voided is NULL or inv.voided = 2 or inv.voided = 0) group by menu.id, inv.voided, inv.isrefund;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ if ( $ref->{isrefund} == 1 ) { $pluuse{$ref->{pluid}} += $ref->{totalqty}; } else { $pluuse{$ref->{pluid}} += $ref->{totalqty} if ($ref->{voided} != 2); $returns{$ref->{pluid}} += $ref->{totalqty} if ($ref->{voided} == 2); } $onetoone{$ref->{pluid}} = $ref->{stockid}; } # loop the PLUs in the following: foreach my $plu (keys %pluuse) { $results = $dbh->prepare(" SELECT rn.name name, rn.id id, mr.qty qty, ry.yield totaly from recipe_names rn, menu_recipes mr, recipe_yields ry where ry.recipe_id = rn.id and ry.yield_unit = mr.recipe_units and mr.menu_id=$plu and rn.id=mr.recipe_id ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ my %usage = &recipeingredients($ref->{id},$ref->{totaly}/$ref->{qty}, {dbh => $dbh} ); foreach my $ingred (keys %usage) { #print "|$idetails{$ingred}{stockitems_id} -- $stockuse{$idetails{$ingred}{stockitems_id}}"; # THE LiNK $stockuse{$idetails{$ingred}{stockitems_id}} += $pluuse{$plu}*$usage{$ingred}* #usage in the PLU ((100+(100-$idetails{$ingred}{yield}))/100)* #yield towards stockitem ${$unitalias{ $idetails{$ingred}{units} } }[1]; } } #deal with onetoones $stockuse{$onetoone{$plu}} += $pluuse{$plu} if {$onetoone{$plu} > 0}; } #foreach PLU #END #/ #/ PRINT CLOSING STOCK SHEET #/ $temphtml .= $table{startp}; $temphtml .= ""; $temphtml .= " SKU CODE CATEGORY STOCK ITEM PREVIOUS STOCK PURCHASES CREDIT NOTES STOCK ON HAND PLU USAGE THEORETICAL
    STOCK VALUE COUNT"; $temphtml .= ""; #/use Time::HiRes qw(gettimeofday); #/my ($starttime, $endtime, $elapsed); my $totalvalue = 0; foreach my $id ( sort {$stockdetails{sku}{$a} cmp $stockdetails{sku}{$b}} sort {$stockdetails{cat}{$a} cmp $stockdetails{cat}{$b}} sort {$stockdetails{name}{$a} cmp $stockdetails{name}{$b}} keys %availables) { if ($R::filter) { my $filter = $R::filter; if ( $stockdetails{sku}{$id} =~ /($filter)/i || $stockdetails{cat}{$id} =~ /($filter)/i || $stockdetails{name}{$id} =~ /($filter)/i ) {} else { next; } } $temphtml .= ""; $temphtml .= " $stockdetails{sku}{$id} $stockdetails{cat}{$id} $stockdetails{name}{$id} ".($last_closingstock{$id}{qty}*1)." $units{$stockdetails{units}{$id}} ".($last_purchases{$id}{qty}*1)." $units{$stockdetails{units}{$id}} ".($last_creditnotes{$id}{qty}*1)." $units{$stockdetails{units}{$id}} ".($availables{$id} < 0 ? "ERROR! " : "")."".pr($availables{$id})." $units{$stockdetails{units}{$id}} ".($stockuse{$id}*1)." $units{$stockdetails{units}{$id}} ".($availables{$id} - $stockuse{$id})." $units{$stockdetails{units}{$id}} $currency ".pr( ($availables{$id} - $stockuse{$id} ) * $stockdetails{cost}{$id} )." "; $temphtml .= ""; $totalvalue += ($availables{$id} - $stockuse{$id}) * $stockdetails{cost}{$id}; } $temphtml .= " Total Value of Stock on Hand: $currency ".pr($totalvalue)." "; $temphtml .= $table{end}; my $warning; if ($tempdb{stockflag} == 2) {$warning = "onClick=\"return confirm('YOU WILL NOT BE ALLOWED TO EDIT ANY MORE PURCHASES WHILE YOU ARE IN CLOSING STOCK EDITOR! ARE YOU SURE ?');\""} $temphtml .= "
    "; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "Closing Stock" or $R::action eq "Back to Closing Stock") { my $temphtml; my %calc; my $sqlorder; #/type 1 = by name; type 2=by bin #/retreive perm stage $tempdb{cstockviewtype} = $R::viewtype if $R::viewtype; #/permanent stage - viewtype $tempdb{cstockviewtype} = 1 if !$tempdb{cstockviewtype}; #/retreive permanent stages $tempdb{stocktype} = $R::stocktype if $R::stocktype; #/no permanent stages yet - init $tempdb{stocktype} = (sort {$a <=> $b} keys %{ $stocktypes{$database} })[0] if !$tempdb{stocktype}; my %ordertype = (1 => 'name', 2 => 'bin'); my $orderby = $ordertype{$tempdb{cstockviewtype}}; $template =~ s/\@title\@/View Stock $cstockviewtypes{$tempdb{cstockviewtype}}/sgi; $temphtml = "
    "; my $stocktype=$tempdb{stocktype}; #/All queries for the screen #/get all stock in memory: name, bin, units my %stockdetails; $results = $dbh->prepare(" SELECT si.id,concat(sc.name,' - ',si.name) name, bin, units, sku FROM stockitems si LEFT JOIN stockcats sc ON sc.id = si.stockcats_id WHERE si.f_status<100 and si.shop_id=$shop{id} and sc.f_status<100 and sc.shop_id=$shop{id} and si.type=$stocktype; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockdetails{name}{$ref->{id}} = $ref->{name}; $stockdetails{bin}{$ref->{id}} = $ref->{bin}; $stockdetails{units}{$ref->{id}} = $ref->{units}; $stockdetails{sku}{$ref->{id}} = $ref->{sku}; } #/determine last pid for the stocktype $results = $dbh->prepare("select last_pid,date from cstock where stocktype=$stocktype and shop_id=$shop{id} and f_status<100 order by id desc limit 1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $last_pid = $ref->{last_pid}*1; my $last_date = $ref->{date}; #/purchases sinse last pid excluding $last_date = "1900-01-01" if (! $last_date); my %last_purchases; $results = $dbh->prepare("select si.id id, si.name name, si.units units, si.bin bin, sum(pu.qty) qty, sum(pu.org_price) totalprice, sum(pu.org_price)/sum(pu.qty) uprice from purchases pu,stockitems si where si.f_status<100 and pu.f_status<100 and si.shop_id=$shop{id} and pu.shop_id=si.shop_id and si.id=pu.stockitems_id and si.type=$stocktype and pu.id>$last_pid #/cs:last_pid and (pu.cnote != 1 or pu.cnote is NULL or pu.cnote = 0) group by si.id order by name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_purchases{$ref->{id}}{qty} = $ref->{qty}; $last_purchases{$ref->{id}}{value} = $ref->{totalprice}; } #/last closing stock qty and value my %last_closingstock; $results = $dbh->prepare("select si.id id, si.name name, sum(cs.qty) qty, sum(cs.value) stockvalue, sum(cs.value)/sum(cs.qty) uprice from cstock cs, stockitems si where cs.f_status<100 and si.f_status<100 and si.shop_id=$shop{id} and cs.shop_id=si.shop_id and si.id=cs.stockitems_id and si.type=$stocktype and cs.last_pid=$last_pid #/cs:last_pid and cs.date='$last_date' group by si.id order by si.name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_closingstock{$ref->{id}}{qty} = $ref->{qty}; $last_closingstock{$ref->{id}}{value} = $ref->{stockvalue}; } #/last credit notes - since last_pid my %last_creditnotes; $results = $dbh->prepare("select si.id id, si.name name, sum(pu.qty) qty, sum(pu.org_price) totalprice, sum(pu.org_price)/sum(pu.qty) uprice from purchases pu,stockitems si where pu.f_status<100 and si.f_status<100 and si.shop_id=$shop{id} and pu.shop_id=si.shop_id and si.id=pu.stockitems_id and si.type=$stocktype and pu.id>$last_pid #/cs:last_pid and pu.cnote = 1 group by si.id order by name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_creditnotes{$ref->{id}}{qty} = $ref->{qty}; $last_creditnotes{$ref->{id}}{value} = $ref->{totalprice}; } #/calculate the availables; my %availables = (); foreach my $id (keys %{$stockdetails{name}}) { my $available_qty = $last_closingstock{$id}{qty} + ($last_purchases{$id}{qty} - $last_creditnotes{$id}{qty}); next if ($available_qty <= 0 and $show_noqty_stock == -1); $availables{$id} = $available_qty || 0; } #/by bin / by name my $sortage = $orderby; #///All queries $temphtml .= " $stocktypes{$database}{$tempdb{stocktype}} Stock Sheet"; $temphtml .= "STOCK TYPE:
    "; foreach my $acctype (sort keys %{ $stocktypes_breakdown{$database} }) { $temphtml .= "($account_types{$acctype}: "; foreach (sort {$stocktypes{$database}{$a} cmp $stocktypes{$database}{$b}} keys %{ $stocktypes_breakdown{$database}{$acctype} } ) { $temphtml .= "[".($tempdb{stocktype} == $_ ? " $stocktypes{$database}{$_} " : "$stocktypes{$database}{$_}")."]"; } $temphtml .= ")
    "; } $temphtml .= " | View by name | View by bin
    "; #/ #/ PRINT CLOSING STOCK SHEET #/ $temphtml .= $table{startp}; $temphtml .= ""; $temphtml .= "SKUSTOCK ITEM BIN PREVIOUS STOCK PURCHASES CREDIT NOTES STOCK ON HAND NEW STOCK"; $temphtml .= ""; #/use Time::HiRes qw(gettimeofday); #/my ($starttime, $endtime, $elapsed); foreach my $id ( sort {$stockdetails{$sortage}{$a} cmp $stockdetails{$sortage}{$b}} sort {$stockdetails{name}{$a} cmp $stockdetails{name}{$b}} keys %availables) { next if ($availables{$id} <= 0 and $show_noqty_stock == -1); $temphtml .= ""; $temphtml .= "$stockdetails{sku}{$id} $stockdetails{name}{$id} $bins{$database}{$stockdetails{bin}{$id}} ".($last_closingstock{$id}{qty}*1)." $units{$stockdetails{units}{$id}} ".($last_purchases{$id}{qty}*1)." $units{$stockdetails{units}{$id}} ".($last_creditnotes{$id}{qty}*1)." $units{$stockdetails{units}{$id}} ".($availables{$id} < 0 ? "ERROR! " : "")."".pr($availables{$id})." $units{$stockdetails{units}{$id}} $units{$stockdetails{units}{$id}}"; $temphtml .= ""; } $temphtml .= $table{end}; my $warning; if ($tempdb{stockflag} == 2) {$warning = "onClick=\"return confirm('YOU WILL NOT BE ALLOWED TO EDIT ANY MORE PURCHASES WHILE YOU ARE IN CLOSING STOCK EDITOR! ARE YOU SURE ?');\""} $temphtml .= "
    "; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } #/ end CLOSING STOCK SHEET elsif ($socketflag == 1 and $R::action eq "Opening Stock") { #/TODO - eventual combine with purchases and remove this action #/$R::lastpid=11875; #/***BIBI*** my $temphtml; my ($purtype); my $ostocklimit; $purtype=1; #/ opening stock $onload="document.form1.stockitems_id.focus();"; #/retreive permanent stages $tempdb{ostocktype} = $R::ostocktype if ($R::ostocktype); #/no permanent stages yet - init if (! $tempdb{ostocktype}) {$tempdb{ostocktype}=1}; if ($tempdb{ostocktype} == 2){ $template =~ s/\@title\@/Edit Opening Stock - Liqour/sgi; $ostocklimit = "and si.type=2 and si.stockitem <> 2"; } else { $template =~ s/\@title\@/Edit Opening Stock - Food/sgi; $ostocklimit = "and si.type=1 and si.stockitem <> 2"; } $R::lastpid=0 if (! $R::lastpid); $temphtml = "
    PASSWORD: last PID: "; if ($R::passwd eq "obi4amte") { #/## OSTOCK EDIT COMMANDS if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { my ($new_qty, $new_price); #/$new_qty = $R::org_qty*${unitalias{$R::org_units}}[1]; #/$new_price = pr($R::org_price/$new_qty); $new_qty=$R::org_qty; $new_price=$new_qty*$R::org_price; my $results = $dbh->prepare("INSERT INTO purchases (shop_id, stockitems_id, org_qty, org_price, org_units, qty, price, date, type, cnote) values ($shop{id}, $R::stockitems_id, $R::org_qty, $new_price, $R::org_units, $new_qty, $R::org_price,CURRENT_DATE(),$purtype,0);") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "DATA ADDED."; } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE purchases SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "STOCK DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { my %sqldate = dateforsql($R::date); my ($new_qty, $new_price); #/$new_qty = $R::org_qty*${unitalias{$R::org_units}}[1]; #/$new_price = pr($R::org_price/$new_qty); $new_qty=$R::org_qty; $new_price=$new_qty*$R::org_price; my $results = $dbh->prepare("UPDATE purchases SET stockitems_id='$R::stockitems_id', supplier_id='$R::supplier_id', org_qty='$R::org_qty', org_price='$new_price', qty='$new_qty', price='$R::org_price', invoice='$R::invoice', description='$R::description', cnote=0, f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "DATA MODIFIED."; } #/## /COMMANDS $temphtml .= "
    "; $temphtml .= "Food Opening Stock | Liqour Opening Stock"; my $results = $dbh->prepare("select sum(pu.org_price) total from purchases pu, stockitems si where si.stockitem <> 2 and pu.stockitems_id=si.id and pu.id>=$R::lastpid and pu.shop_id=$shop{id} and pu.f_status<100 and si.shop_id=$shop{id} and si.f_status<100 $ostocklimit and pu.type=1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $temphtml .= " | VALUE TOTAL: $currency".pr($ref->{total}); $temphtml .= "
    "; #/ DRAW TABLE OPURCH $temphtml .= $table{start}; $temphtml .= ""; $temphtml .= " Item Stock Qty Stock Units Stock Price Qty Units Price Value :COMMANDS:"; $temphtml .= ""; $results = $dbh->prepare(" SELECT pu.id id, pu.qty qty, pu.org_price org_price, pu.price price, price*qty value, pu.org_qty org_qty, pu.org_units org_units, si.type type, pu.stockitems_id stockitems_id, si.name item, si.units units, si.type stocktype FROM purchases pu, stockitems si WHERE pu.shop_id =$shop{id} and pu.f_status<100 and pu.id>=$R::lastpid and si.id=pu.stockitems_id and pu.type=1 and si.stockitem <> 2 $ostocklimit ORDER BY si.name ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; $temphtml .= " {stocktype}}>$ref->{item} $ref->{org_qty} ${ $unitalias{$ref->{org_units}} }[0] $ref->{org_price} $ref->{qty} $units{$ref->{units}} $ref->{price} $ref->{value} "; $temphtml .= ""; $temphtml .= "{id}\" onclick=\"return confirm('DELETE ITEM: $ref->{item} ?');\">$icons{d}"; $temphtml .= " {id}\">$icons{m}"; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; $temphtml .= " "; $temphtml .=" {org_qty}\" $calt_e3> * "; #/"; $temphtml .=" *** {price}\" $calt_e> * "; $temphtml .= "{id}>"; $temphtml .= ""; } } if ($R::command ne "modify" ) { $temphtml .= ""; $temphtml .= " "; $temphtml .=" * "; #/"; $temphtml .=" *** * "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= "
    "; } #/if passwd $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "Opening Stock" and $tempdb{stockflag} != 1) { $template =~ s/\@title\@/Error/sgi; my $temphtml = "

    Function disabled! You must finish editing your Closing Stock in order to use this function"; $template =~ s/\@content\@/$temphtml/sgi; }#/ end OPENING STOCK editor elsif ($socketflag == 1 and $R::action eq "creditors") { my $temphtml; my $lockflag=1; my $mydate; my $defaultdate; $onload="document.form1.amount.focus();"; $defaultdate = datefromsql($R::pdate) || $date; #/$onload="document.form1.stockitems_id.focus();"; $template =~ s/\@title\@/Edit Creditors/sgi; $temphtml = "

    "; if ($R::petty) { $subresults = $dbh->prepare("SELECT f_lock,DATE_FORMAT(date, '%e %M %Y') mydate from dcash where f_status<100 and shop_id=$shop{id} and date='$R::pdate';") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $subresults->finish(); $lockflag=$subref->{f_lock}; $mydate=$subref->{mydate}; $temphtml .= "PETTY CASH - $mydate
    "; } #/## CREDITOR EDIT COMMANDS if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { my $supplier_id; my $wholesaler_id; $supplier_id = undef; $wholesaler_id = undef; if ($R::supplier_id =~ /(w)(\d+)/) {$wholesaler_id=$2} elsif ($R::supplier_id =~ /(s)(\d+)/) {$supplier_id=$2} my $results = $dbh->prepare("INSERT INTO creditors (shop_id,amount,date,supplier_id,description) values (?,?,?,?,?);") or die $dbh->errstr(); $results->execute($shop{id},$R::amount,$R::pdate,$supplier_id,$R::description) or die $results->errstr(); $mess = "DATA ADDED."; } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE creditors SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "RECORD DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { my $supplier_id; my $wholesaler_id; $supplier_id = undef; $wholesaler_id = undef; if ($R::supplier_id =~ /(w)(\d+)/) {$wholesaler_id=$2} elsif ($R::supplier_id =~ /(s)(\d+)/) {$supplier_id=$2} my $results = $dbh->prepare("UPDATE creditors SET shop_id=?,amount=?,date=?,supplier_id=?,description=?, f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($shop{id},$R::amount,$R::pdate,$supplier_id,$R::description) or die $results->errstr(); $mess = "DATA MODIFIED."; } #/## /COMMANDS #/ SPLITS $temphtml .= "STOCK TYPE:
    "; foreach my $acctype (sort keys %{ $stocktypes_breakdown{$database} }) { $temphtml .= "($account_types{$acctype}: "; foreach (sort {$stocktypes{$database}{$a} cmp $stocktypes{$database}{$b}} keys %{ $stocktypes_breakdown{$database}{$acctype} } ) { $temphtml .= "[$stocktypes{$database}{$_}]"; } $temphtml .= ")
    "; } $temphtml .= " | Other Expences"; $temphtml .= " | Wages/Loans" if ($R::petty); $temphtml .= " | Creditors" if ($R::petty); $temphtml .= "
    "; #/ DRAW TABLE CREDITORS $temphtml .= $table{start}; $temphtml .= ""; $temphtml .= " Amount Supplier Description "; $temphtml .= ":COMMANDS:" if ($lockflag ==1); $temphtml .= ""; $results = $dbh->prepare("SELECT * from creditors where date='$R::pdate' and shop_id=$shop{id} and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; if ($ref->{supplier_id}) { $subresults = $dbh->prepare("SELECT name from suppliers where id=$ref->{supplier_id};") or die $dbh->errstr(); } else{ $subresults = $dbh->prepare("SELECT name from wholesalers where id=$ref->{wholesaler_id};") or die $dbh->errstr(); } $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $temphtml .= "$ref->{amount}$subref->{name}$ref->{description}"; $temphtml .= " {id}&pdate=$R::pdate&dcashid=$R::dcashid\" onclick=\"return confirm('DELETE ITEM: $ref->{item} ?');\">$icons{d} {id}&pdate=$R::pdate&dcashid=$R::dcashid\">$icons{m} " if ($lockflag ==1); $temphtml .= ""; } else { my %ssel; if (! $ref->{supplier_id}) { $ssel{"w".$ref->{wholesaler_id}}="SELECTED" } else { $ssel{"s".$ref->{supplier_id}}="SELECTED" } $temphtml .= ""; $temphtml .= " $currency {amount}\">{description}\"> "; $temphtml .= ""; $temphtml .= "{id}>"; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } } if ($R::petty) { #/## TOTALS PETTYCASH my %calc; my $results = $dbh->prepare("SELECT SUM(org_price) FROM purchases WHERE shop_id=$shop{id} and f_status<100 and date='$R::pdate' and type=3;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{amount} = $ref; $results = $dbh->prepare("SELECT SUM(amount) FROM loans WHERE shop_id=$shop{id} and f_status<100 and date='$R::pdate';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{amount} += $ref; $results = $dbh->prepare("SELECT SUM(amount) FROM creditors WHERE shop_id=$shop{id} and f_status<100 and date='$R::pdate';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{amount} += $ref; #/comparation/substraction $results = $dbh->prepare("SELECT pettycash FROM dcash WHERE shop_id=$shop{id} and f_status<100 and id=$R::dcashid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{diff} = $calc{amount} - $ref; $calc{aspercash} = $ref; if (sprintf("%.2f",$calc{diff}) == 0) {$linecolor=""} else {$linecolor=$errorcolor} $temphtml .= " Total as per Petty Cash ".pr($calc{amount})."
    Total as per cash-up ".pr($calc{aspercash})."
    Shortfall for account of the management ".pr($calc{diff})."
    Petty Cash Summary "; } #/ if petty #/commands add creditors if ($R::command ne "modify" and $lockflag==1) { $temphtml .= ""; $temphtml .= " $currency "; $temphtml .= ""; $temphtml .= ""; } $temphtml .= qq ~ ~ if ($lockflag ==1);; $temphtml .= $table{end}; if ($R::petty) { $temphtml .= "
    Back to Cash-up
    "; } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } #/creditors elsif ($socketflag == 1 and $R::action eq "loans") { my $temphtml; my $lockflag=1; my $mydate; my $defaultdate; $onload="document.form1.amount.focus();"; my (%waitrons, %allwaitrons); #/ prepare waitrons my $subresults = $dbh->prepare("SELECT id, name,active FROM waitron WHERE f_status<100 and shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $allwaitrons{$subref->{id}} = $subref->{name}; $waitrons{$subref->{id}} = $subref->{name} if ($subref->{active} == 1); } $defaultdate = datefromsql($R::pdate) || $date; #/$onload="document.form1.stockitems_id.focus();"; $template =~ s/\@title\@/Edit Wages\/Loans/sgi; $temphtml = "
    "; if ($R::petty) { $subresults = $dbh->prepare("SELECT f_lock,DATE_FORMAT(date, '%e %M %Y') mydate from dcash where f_status<100 and shop_id=$shop{id} and date='$R::pdate';") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $subresults->finish(); $lockflag=$subref->{f_lock}; $mydate=$subref->{mydate}; $temphtml .= "PETTY CASH - $mydate
    "; } #/## LOAN EDIT COMMANDS if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { my ($waitron_id,$wageperson,$wagetype); if ($R::type == 1) {$waitron_id=$R::waitron; $wageperson="NULL"; $wagetype="NULL"} else {$waitron_id = "NULL";$wageperson="'$R::person'"; $wagetype="'$R::wagetype'"} my $results = $dbh->prepare("INSERT INTO loans (shop_id,amount,date,loantype,waitron_id,wageperson,wagetype,description) values ($shop{id},'$R::amount','$R::pdate', '$R::type', ".$waitron_id.",".$wageperson.",".$wagetype.",?);") or die $dbh->errstr(); $results->execute($R::description) or die $results->errstr(); $mess = "DATA ADDED."; } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE loans SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "RECORD DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { my ($waitron_id,$wageperson,$wagetype); if ($R::type == 1) {$waitron_id=$R::waitron; $wageperson="NULL"; $wagetype="NULL"} else {$waitron_id = "NULL";$wageperson="'$R::person'"; $wagetype="$R::wagetype"} my $results = $dbh->prepare("UPDATE loans SET amount='$R::amount', loantype='$R::type', waitron_id=".$waitron_id.", wageperson=".$wageperson.", wagetype=".$wagetype.", description=?, f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::description) or die $results->errstr(); $mess = "DATA MODIFIED."; } #/## /COMMANDS #/ SPLITS $temphtml .= "STOCK TYPE:
    "; foreach my $acctype (sort keys %{ $stocktypes_breakdown{$database} }) { $temphtml .= "($account_types{$acctype}: "; foreach (sort {$stocktypes{$database}{$a} cmp $stocktypes{$database}{$b}} keys %{ $stocktypes_breakdown{$database}{$acctype} } ) { $temphtml .= "[$stocktypes{$database}{$_}]"; } $temphtml .= ")
    "; } $temphtml .= " | Other Expences"; $temphtml .= " | Wages/Loans" if ($R::petty); $temphtml .= " | Creditors" if ($R::petty); $temphtml .= "
    "; #/ DRAW TABLE LOANS $temphtml .= $table{start}; $temphtml .= ""; $temphtml .= " Amount Person Description "; $temphtml .= ":COMMANDS:" if ($lockflag ==1); $temphtml .= ""; $results = $dbh->prepare("SELECT * from loans where date='$R::pdate' and shop_id=$shop{id} and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; my $name; if ($ref->{loantype} == 1) { $name = $allwaitrons{$ref->{waitron_id}}; $name .= "*" if (! exists $waitrons{$ref->{waitron_id}}); $name .= " (waitron)"; } else {$name=$ref->{wageperson}." (other) [$wagetypes{$ref->{wagetype}}]"} $temphtml .= "$ref->{amount}$name$ref->{description}"; $temphtml .= " {id}&pdate=$R::pdate&dcashid=$R::dcashid\" onclick=\"return confirm('DELETE ITEM: $ref->{item} ?');\">$icons{d} {id}&pdate=$R::pdate&dcashid=$R::dcashid\">$icons{m} " if ($lockflag ==1); $temphtml .= ""; } else { my (%waitronsel, $name, %typesel); if ($ref->{loantype} == 1) { $waitronsel{$ref->{waitron_id}} = "selected"; $typesel{1}="checked"; } else {$name=$ref->{wageperson};$typesel{2}="checked";} $temphtml .= ""; $temphtml .= " $currency {amount}>
    User "; $listhtml .= "
    Other $listhtml
    {description}\"> "; $temphtml .= ""; $temphtml .= "{id}>"; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } } if ($R::petty) { #/## TOTALS PETTYCASH my %calc; my $results = $dbh->prepare("SELECT SUM(org_price) FROM purchases WHERE shop_id=$shop{id} and f_status<100 and date='$R::pdate' and type=3;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{amount} = $ref; $results = $dbh->prepare("SELECT SUM(amount) FROM loans WHERE shop_id=$shop{id} and f_status<100 and date='$R::pdate';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{amount} += $ref; $results = $dbh->prepare("SELECT SUM(amount) FROM creditors WHERE shop_id=$shop{id} and f_status<100 and date='$R::pdate';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{amount} += $ref; #/comparation/substraction $results = $dbh->prepare("SELECT pettycash FROM dcash WHERE shop_id=$shop{id} and f_status<100 and id=$R::dcashid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{diff} = $calc{amount} - $ref; $calc{aspercash} = $ref; if (sprintf("%.2f",$calc{diff}) == 0) {$linecolor=""} else {$linecolor=$errorcolor} $temphtml .= " Total as per Petty Cash ".pr($calc{amount})."
    Total as per cash-up ".pr($calc{aspercash})."
    Shortfall for account of the management ".pr($calc{diff})."
    Petty Cash Summary "; } #/ if petty #/commands add loan if ($R::command ne "modify" and $lockflag==1) { $temphtml .= ""; $temphtml .= " $currency
    User "; $listhtml .= "
    Other $listhtml
    "; $temphtml .= ""; $temphtml .= ""; } $temphtml .= qq ~ ~ if ($lockflag ==1);; $temphtml .= $table{end}; if ($R::petty) { $temphtml .= "
    Back to Cash-up
    "; } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } #/ end LOANS editor elsif ($socketflag == 1 and $R::action eq "Purchases") { if ($R::purdayslimit) { $tempdb{purdayslimit} = $R::purdayslimit; } $tempdb{purdayslimit} = 14 if (! $tempdb{purdayslimit}); my $temphtml; $R::ptype = (sort {$stocktypes{$database}{$a} cmp $stocktypes{$database}{$b}} keys %{ $stocktypes{$database} } )[0] if ((! $R::ptype) and (! $tempdb{stocktype})); $tempdb{stocktype} = $R::ptype if ($R::ptype); $R::ptype = $tempdb{stocktype}; my $lastinvoicenumber = undef; my $lastsupplier = undef; my $lastsuppliername = undef; my $totalforlastinvoice = undef; my $lastsupname; $temphtml .= qq~ ~; my ($sttype,$purtype,$last_cspid,$purlimit); my $lockflag=1; my $mydate; my $defaultdate; my $purtotalslimit; $purtotalslimit = "and pu.invoice in ($R::purtotalslimit)" if ($R::purtotalslimit ne ""); $onload="document.form1.stockitems_id.focus();"; $purtype = 2; #/default no petty cash my $clstocktype; $clstocktype = $R::ptype; $subresults = $dbh->prepare("SELECT last_pid last_pid,date from cstock where stocktype=$clstocktype and f_status<100 and shop_id=$shop{id} order by id desc limit 1;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $subresults->finish(); my $last_date = $subref->{date}; $last_date = "1900-01-01" if (! $last_date); $last_cspid = $subref->{last_pid}; my %last_qty; $subresults = $dbh->prepare("select stockitems_id,qty from cstock where date='$last_date' and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($ref = $subresults->fetchrow_hashref()) { $last_qty{$ref->{stockitems_id}} = $ref->{qty}; } $temphtml .= "
    "; #/calendar JS $temphtml .= qq~ ~; $sttype="and si.type = $R::ptype"; $purlimit = "and pu.id>'$last_cspid'"; $template =~ s/\@title\@/Edit $stocktypes{$database}{$R::ptype} Purchases/sgi; my %stockitem_names; my %stockitem_warnperc; $results = $dbh->prepare(" select concat(sc.name,' - ',si.name) name, si.id id, si.units units, si.warnperc from stockitems si LEFT JOIN stockcats sc ON sc.id = si.stockcats_id where si.shop_id=$shop{id} and sc.shop_id=si.shop_id and si.f_status<100 and sc.f_status<100 and si.type=$R::ptype and si.stockitem != 2 and si.name != '' ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while($ref = $results->fetchrow_hashref()) { $stockitem_names{$ref->{id}} = $ref->{name}.", ".$units{$ref->{units}}; $stockitem_warnperc{$ref->{id}} = $ref->{warnperc}; } if ($R::petty) { $subresults = $dbh->prepare("SELECT f_lock,DATE_FORMAT(date, '%e %M %Y') mydate from dcash where f_status<100 and shop_id=$shop{id} and date='$R::pdate';") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $subresults->finish(); $lockflag=$subref->{f_lock}; $mydate=$subref->{mydate}; $purlimit = "and pu.date='$R::pdate'"; #/ override after last closing stock $purtype = 3; $temphtml .= "PETTY CASH - $mydate
    "; } #/qty = org_qty * inv_units_alias_koef #/price = org_price / qty #/value=qty * price #/## PURCH EDIT COMMANDS if (($R::command eq "Add Data" and $R::supplier_id)) { $tempdb{ssc_pur_supplier_id} = $R::supplier_id; #/$tempdb{ssc_pur_stockitems_id} = $R::stockitems_id; $tempdb{ssc_pur_invoice} = $R::invoice; $tempdb{ssc_pur_date} = $R::date; $tempdb{ssc_pur_description} = $R::description; my %sqldate = dateforsql($R::date); $R::org_price *= 1; #/evaluate $R::org_qty *= 1; #/evaluate my ($new_qty, $new_price); $new_qty = $R::org_qty;#/*${unitalias{$R::org_units}}[1]; $new_price = $R::org_price/$R::org_qty; #/notused #/debug $temphtml .= "ORG_PRICE = $R::org_price"; #/remove VAT for single price if pettycash purchase of item having vat if ($R::petty ==1 and $R::vat==1) {$new_price = $new_price /((100 + $cvat)/100)} if ($R::discount>0) {$new_price = $new_price - $new_price*$R::discount/100} #$temphtml .= "WARN % $stockitem_warnperc{$R::stockitems_id}"; #warning system if ($stockitem_warnperc{$R::stockitems_id} > 0) { $results = $dbh->prepare(" select price,date,invoice from purchases where stockitems_id=$R::stockitems_id and shop_id=$shop{id} and f_status < 100 order by id desc limit 1; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{price}) { my $variance = pr ( 100 * ($new_price - $ref->{price})/$ref->{price} ); $variance *= -1 if ($variance < 0); #print "% $variance %"; if ($variance >= $stockitem_warnperc{$R::stockitems_id}) { $onload .= "alert('UNIT PRICE WARNING !!! Price variance more than $stockitem_warnperc{$R::stockitems_id} %: Last Price $currency ".pr($ref->{price})." from $ref->{date} INV: $ref->{invoice}, this price: $currency ".pr($new_price).", Variance $variance %."."');"; } } } # if variance perc defined my $results = $dbh->prepare("INSERT INTO purchases (othertype, shop_id, stockitems_id, supplier_id, org_qty, org_price, org_units, qty, price, discount, invoice, description,date,type,cnote,vat) values ('$R::othertype', $shop{id}, $R::stockitems_id, $R::supplier_id, $R::org_qty, $R::org_price, $R::org_units, $new_qty, $new_price, '$R::discount', '$R::invoice', ?, '$sqldate{year}-$sqldate{month}-$sqldate{day}',$purtype, '$R::cnote', '$R::vat');") or die $dbh->errstr(); $results->execute($R::description) or die $results->errstr(); $mess = "DATA ADDED."; #is this latest price ? $results = $dbh->prepare("select count(id) notlast from purchases where date > '$sqldate{year}-$sqldate{month}-$sqldate{day}' and shop_id=$shop{id} and f_status<100 and stockitems_id=$R::stockitems_id") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if (! $ref->{notlast}) { #retreive links $results = $dbh->prepare("select distinct id from ritems where stockitems_id=$R::stockitems_id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #update unit prices - ingredients; my %linkedritems; while ($ref = $results->fetchrow_hashref()) { $linkedritems{$ref->{id}} = 1; } foreach my $ritem_id (keys %linkedritems) { $results = $dbh->prepare("select id from ritem_prices where item_id='$ritem_id' order by id desc limit 1") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $id = $ref->{id}; if ($id) { # update existing price $results = $dbh->prepare("update ritem_prices set price='$new_price', supplier_id='$R::supplier_id', date='$sqldate{year}-$sqldate{month}-$sqldate{day}' where id='$id';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } else { #create new price record $results = $dbh->prepare("insert into ritem_prices (price,date,supplier_id,item_id) values ($new_price,'$sqldate{year}-$sqldate{month}-$sqldate{day}','$R::supplier_id','$ritem_id');") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } #$supplier_id } } } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE purchases SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "STOCK DELETED."; } elsif (($R::command eq "Modify Data" and $R::org_price > 0 and $R::supplier_id>0)) { my %sqldate = dateforsql($R::date); $R::org_price *= 1; #/evaluate $R::org_qty *= 1; #/evaluate my ($new_qty, $new_price); $new_qty = $R::org_qty;#/*${unitalias{$R::org_units}}[1]; $new_price = $R::org_price/$R::org_qty; #/notused #/remove VAT for single price if pettycash purchase of item having vat if ($R::petty==1 and $R::vat==1) {$new_price = $new_price /((100 + $cvat)/100)} if ($R::discount>0) {$new_price = $new_price - $new_price*$R::discount/100} my $results = $dbh->prepare("UPDATE purchases SET othertype='$R::othertype', stockitems_id=$R::stockitems_id, supplier_id=$R::supplier_id, org_qty=$R::org_qty, org_price=$R::org_price, org_units=$R::org_units, qty=$new_qty, price=$new_price, discount='$R::discount', invoice='$R::invoice', description=?, date='$sqldate{year}-$sqldate{month}-$sqldate{day}', cnote='$R::cnote', vat='$R::vat', f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::description) or die $results->errstr(); $mess = "DATA MODIFIED."; #is this latest price ? $results = $dbh->prepare("select count(id) notlast from purchases where date > '$sqldate{year}-$sqldate{month}-$sqldate{day}' and shop_id=$shop{id} and f_status<100 and stockitems_id=$R::stockitems_id") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if (! $ref->{notlast}) { #retreive links $results = $dbh->prepare("select distinct id from ritems where stockitems_id=$R::stockitems_id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #update unit prices - ingredients; my %linkedritems; while ($ref = $results->fetchrow_hashref()) { $linkedritems{$ref->{id}} = 1; } foreach my $ritem_id (keys %linkedritems) { $results = $dbh->prepare("select id from ritem_prices where item_id='$ritem_id' order by id desc limit 1") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $id = $ref->{id}; if ($id) { # update existing price $results = $dbh->prepare("update ritem_prices set price='$new_price', supplier_id='$R::supplier_id', date='$sqldate{year}-$sqldate{month}-$sqldate{day}' where id='$id';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } else { #create new price record $results = $dbh->prepare("insert into ritem_prices (price,date,supplier_id,item_id) values ($new_price,'$sqldate{year}-$sqldate{month}-$sqldate{day}','$R::supplier_id','$ritem_id');") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } #$supplier_id } } } #/## /COMMANDS $defaultdate = datefromsql($R::pdate) || $tempdb{ssc_pur_date} || $date; #/ SPLITS #/quick mode if ($R::command eq "Turn Quick Mode ON") { $tempdb{pqm} = 2; } elsif ($R::command eq "Turn Quick Mode OFF") { $tempdb{pqm} = 1; } $tempdb{pqm} = 2 if (! $tempdb{pqm}); my $qm = $tempdb{pqm}; $temphtml .= "Limiting purchases for days of last invoice date.
    " if (! $R::petty); $temphtml .= "STOCK TYPE:
    "; foreach my $acctype (sort keys %{ $stocktypes_breakdown{$database} }) { $temphtml .= "($account_types{$acctype}: "; foreach (sort {$stocktypes{$database}{$a} cmp $stocktypes{$database}{$b}} keys %{ $stocktypes_breakdown{$database}{$acctype} } ) { $temphtml .= "[".($tempdb{stocktype} == $_ ? " $stocktypes{$database}{$_} " : "$stocktypes{$database}{$_}")."]"; } $temphtml .= ")
    "; } $temphtml .= " | Other Expences"; $temphtml .= " | Wages/Loans" if ($R::petty); $temphtml .= " | Creditors" if ($R::petty); $temphtml .= "
    "; #/ DRAW TABLE PURCH $temphtml .= $table{start}; $temphtml .= ""; $temphtml .= " Item Supplier CN TAX Invoice Qty Invoice Units Invoice Price"; $temphtml .= "Discount (%) Qty Units U.Price Value" if ($qm != 2); $temphtml .= "Invoice"; $temphtml .= "description" if ($qm != 2); $temphtml .= "date"; $temphtml .= ":COMMANDS:" if ($lockflag ==1); $temphtml .= ""; #purchases will only show for two weeks - must be an override to this limitation my $purdatelimit = ""; #show last purchases condition if (! $R::petty) { $results = $dbh->prepare("select max(date) maxdate from purchases where f_status < 100 and shop_id=$shop{id}; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $lastexdate = $ref->{maxdate}; $purdatelimit = "and date <= '$lastexdate' and date >= DATE_SUB('$lastexdate',INTERVAL ".($tempdb{purdayslimit})." DAY)"; } #supplier names my %suppliers; $results = $dbh->prepare("select name,id from suppliers where shop_id=$shop{id} and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $suppliers{$ref->{id}} = $ref->{name}; } $results = $dbh->prepare(" SELECT pu.id id, pu.qty qty, pu.org_price org_price, pu.price nrprice, round(pu.price,2) price, round(price*pu.qty,2) value, pu.org_qty org_qty, pu.org_units org_units, pu.discount discount, pu.othertype othertype, pu.invoice invoice, pu.description description, DAYOFMONTH(pu.date) day, MONTH(pu.date) month, YEAR(pu.date) year, pu.date date, pu.stockitems_id stockitems_id, pu.supplier_id supplier_id, pu.cnote cnote, pu.vat vat, si.units units, si.type stocktype, si.units siunits, si.id sid FROM purchases pu, stockitems si WHERE pu.shop_id =$shop{id} and pu.f_status<100 $purdatelimit and si.shop_id =$shop{id} and si.f_status<100 and si.id=pu.stockitems_id and pu.type=$purtype $sttype $purlimit $purtotalslimit ORDER BY pu.date DESC, pu.invoice, pu.id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #/debug print $results->rows; while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { #/8->3 if (defined $lastinvoicenumber and ($lastinvoicenumber ne $ref->{invoice})) { $temphtml .= " $lastsupname Total: $currency".pr($totalforlastinvoice)." $lastinvoicenumber View this invoice only "; $totalforlastinvoice = 0; } $totalforlastinvoice += $ref->{nrprice}*$ref->{qty}; $lastinvoicenumber = $ref->{invoice}; $lastsupplier = $ref->{supplier_id}; $lastsuppliername = $suppliers{$ref->{supplier_id}}; $lastsupname=$suppliers{$ref->{supplier_id}}; next if ($R::totalsonly); $temphtml .= ""; $temphtml .= " {id}&pdate=$R::pdate&dcashid=$R::dcashid\">$stockitem_names{$ref->{sid}}"; if ($stocktypes_account_type{$database}{$tempdb{stocktype}} == 2) { $subresults = $dbh->prepare("select id,name,type,vtype,parent,grp from bufc where grp <> 1 and shop_id=$shop{id} and id = $ref->{othertype} and f_status < 100;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $temphtml .= "
    Allocation: $subref->{name}"; } $temphtml .=""; $temphtml .= " $suppliers{$ref->{supplier_id}} $cnote{$ref->{cnote}} $cnote{$ref->{vat}} $ref->{org_qty} $units{$ref->{units}} $ref->{org_price}"; $temphtml .= "$ref->{discount}% $ref->{qty} $units{$ref->{units}} $ref->{price} $ref->{value}" if ($qm != 2); $temphtml .= "$ref->{invoice}"; $temphtml .= "$ref->{description}" if ($qm != 2); $temphtml .= "$ref->{day}-$ref->{month}-$ref->{year} "; $temphtml .= " {item}\" href=\"index.cgi?purtotalslimit=$R::purtotalslimit&action=$R::action&subaction=$R::subaction&ptype=$R::ptype&petty=$R::petty&command=delete&itemid=$ref->{id}&pdate=$R::pdate&dcashid=$R::dcashid\" onclick=\"return confirm('DELETE ITEM: $ref->{item} ?');\">$icons{d} {item}\" href=\"index.cgi?purtotalslimit=$R::purtotalslimit&action=$R::action&subaction=$R::subaction&ptype=$R::ptype&petty=$R::petty&command=modify&itemid=$ref->{id}&pdate=$R::pdate&dcashid=$R::dcashid\">$icons{m} " if ($lockflag ==1); $temphtml .= ""; } else { #/ modify $temphtml .= ""; $temphtml .= " Item Supplier CN TAX Invoice Qty Invoice Units Invoice Price"; $temphtml .= "Discount (%) Qty Units U.Price Value" if ($qm != 2); $temphtml .= "Invoice"; $temphtml .= "description" if ($qm != 2); $temphtml .= "date"; $temphtml .= ":COMMANDS:" if ($lockflag ==1); $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    $icons{det}  quickfind» find next»
    "; if ($stocktypes_account_type{$database}{$tempdb{stocktype}} == 2) { $temphtml .= "
    Expence Category: "; my %otsel; $otsel{$ref->{othertype}} = "selected"; my %grps = (2=>"FIXED COSTS / EXPENSES",3=>"SALARIES & WAGES"); my %parentnames; my %childrenparents; my %childrennames; my %standalones; $subresults = $dbh->prepare(" select id,name,type,vtype,parent,grp from bufc where grp <> 1 and shop_id=$shop{id} and year=$budgetyear and f_status < 100;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { if (! $subref->{parent} and $subref->{vtype} == 3) { $parentnames{$subref->{grp}}{$subref->{id}} = $subref->{name}; } elsif (! $subref->{parent} and $subref->{vtype} != 3 and $subref->{type} == 1) { $standalones{$subref->{grp}}{$subref->{id}} = $subref->{name}; } elsif ($subref->{type} == 1) { push @{$childrenparents{$subref->{parent}}},$subref->{id}; $childrennames { $subref->{id} } = $subref->{name}; } } $temphtml .="quickfind» find next»
    "; } $temphtml .=""; $temphtml .=" {org_qty}\" $calt_e3> * "; $temphtml .=" {org_price}\" $calt_e> "; $temphtml .= " {discount}\" $calt_e> ****" if ($qm != 2); $temphtml .= " {invoice}\" $calt> "; $temphtml .= " {description}\" $calt> " if ($qm != 2); $temphtml .= "
    {day}-$ref->{month}-$ref->{year}\" $calt>$icons{cal} "; $temphtml .= ""; $temphtml .= "{id}>"; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } } $temphtml .= " $lastsupname Total: $currency".pr($totalforlastinvoice)." $lastinvoicenumber View this invoice only "; if ($R::petty) { #/## TOTALS PETTYCASH my %calc; my $results = $dbh->prepare("SELECT SUM(org_price) FROM purchases WHERE shop_id=$shop{id} and f_status<100 and date='$R::pdate' and type=3;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{amount} = $ref; $results = $dbh->prepare("SELECT SUM(amount) FROM loans WHERE shop_id=$shop{id} and f_status<100 and date='$R::pdate';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{amount} += $ref; $results = $dbh->prepare("SELECT SUM(amount) FROM creditors WHERE shop_id=$shop{id} and f_status<100 and date='$R::pdate';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{amount} += $ref; #/comparation/substraction $results = $dbh->prepare("SELECT pettycash FROM dcash WHERE shop_id=$shop{id} and f_status<100 and id=$R::dcashid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{diff} = $calc{amount} - $ref; $calc{aspercash} = $ref; if (sprintf("%.2f",$calc{diff}) == 0) {$linecolor=""} else {$linecolor=$errorcolor} $temphtml .= " Total as per Petty Cash ".pr($calc{amount})."
    Total as per cash-up ".pr($calc{aspercash})."
    Shortfall for account of the management ".pr($calc{diff})."
    Petty Cash Summary "; } #/ if petty #/commands add purchases if ($R::command ne "modify" and $lockflag==1) { #/ DRAW TABLE PURCH $temphtml .= ""; $temphtml .= " Item Supplier CN TAX Invoice Qty Invoice Units Invoice Price"; $temphtml .= "Discount (%) Qty Units U.Price Value" if ($qm != 2); $temphtml .= "Invoice"; $temphtml .= "description" if ($qm != 2); $temphtml .= "date"; $temphtml .= ":COMMANDS:" if ($lockflag ==1); $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    $icons{det}  quickfind» find next»
    "; if ($stocktypes_account_type{$database}{$tempdb{stocktype}} == 2) { $temphtml .= "
    Expence Category: "; my %otsel; #$otsel{$ref->{othertype}} = "selected"; my %grps = (2=>"FIXED COSTS / EXPENSES",3=>"SALARIES & WAGES"); my %parentnames; my %childrenparents; my %childrennames; my %standalones; $subresults = $dbh->prepare("select id,name,type,vtype,parent,grp from bufc where grp <> 1 and shop_id=$shop{id} and year=$budgetyear and f_status < 100;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { if (! $subref->{parent} and $subref->{vtype} == 3) { $parentnames{$subref->{grp}}{$subref->{id}} = $subref->{name}; } elsif (! $subref->{parent} and $subref->{vtype} != 3 and $subref->{type} == 1) { $standalones{$subref->{grp}}{$subref->{id}} = $subref->{name}; } elsif ($subref->{type} == 1) { push @{$childrenparents{$subref->{parent}}},$subref->{id}; $childrennames { $subref->{id} } = $subref->{name}; } } $temphtml .="quickfind» find next»
    "; } $temphtml .=""; $temphtml .= " * "; #/"; $temphtml .=" "; $temphtml .= " ****" if ($qm != 2); $temphtml .= " "; $temphtml .= " " if ($qm != 2); $temphtml .= "
    $icons{cal} "; $temphtml .= ""; $temphtml .= ""; } $temphtml .= qq ~ ~ if ($lockflag ==1);; $temphtml .= $table{end}; $temphtml .= "
    "; if ($tempdb{pqm} == 1) { $temphtml .= " | "; } elsif ($tempdb{pqm} == 2) { $temphtml .= "Quick Mode ACTIVE | "; } $temphtml .= "View invoice number: "; $temphtml .= ""; $temphtml .= " or View invoice totals."; if ($R::petty) { $temphtml .= "
    Back to Cash-up
    "; } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "Purchases" and $tempdb{stockflag} != 2) { $template =~ s/\@title\@/Error/sgi; my $temphtml = "

    Function disabled! You must finish editing your Closing Stock in order to use this function"; $template =~ s/\@content\@/$temphtml/sgi; } #/ end PURCHASES editor elsif ($socketflag == 1 and $R::action eq "Other Purchases") { my $lastinvoicenumber = undef; my $lastsupplier=undef; my $totalforlastinvoice = undef; my $lastsupname; my $temphtml; my ($sttype,$purtype,$last_cspid,$purlimit,$purtotalslimit); my $lockflag=1; my $mydate; my $defaultdate; $onload="document.form1.description.focus();"; $defaultdate = datefromsql($R::pdate) || $date; $temphtml .= qq~ ~; $purtype = 2; #/default no petty cash $subresults = $dbh->prepare("SELECT max(last_pid) last_pid from cstock where f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $subresults->finish(); $last_cspid = $subref->{last_pid}; $temphtml .= "

    "; #/calendar JS $temphtml .= qq~ ~; $template =~ s/\@title\@/Edit Other Purchases/sgi; if (!$R::pdate) { if (!$R::cpstart or !$R::cpend) {$R::cpstart=$date;$R::cpend=$date;} my %sqldate = dateforsql($R::cpstart); my %sqldate1 = dateforsql($R::cpend); $purlimit = "and date>='$sqldate{year}-$sqldate{month}-$sqldate{day}' and date<='$sqldate1{year}-$sqldate1{month}-$sqldate1{day}'"; } if ($R::petty) { $subresults = $dbh->prepare("SELECT f_lock,DATE_FORMAT(date, '%e %M %Y') mydate from dcash where f_status<100 and shop_id=$shop{id} and date='$R::pdate';") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $subresults->finish(); $lockflag=$subref->{f_lock}; $mydate=$subref->{mydate}; $purlimit = "and pu.date='$R::pdate'"; #/ override after last closing stock $purtype = 3; $temphtml .= "PETTY CASH - $mydate
    "; } else { #/ limit the purchases to smaller list $purtotalslimit = "limit 25"; #/ override after last closing stock } #/qty = org_qty * inv_units_alias_koef #/price = org_price / qty #/value=qty * price #/## PURCH EDIT COMMANDS if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { if ($R::othertype < 0) { $mess = "Error: Invalid Entry! Please re-enter the purchase!"; } else { my $supplier_id; my $wholesaler_id; $supplier_id = "NULL";$wholesaler_id = "NULL"; if ($R::supplier_id =~ /(w)(\d+)/) {$wholesaler_id=$2} elsif ($R::supplier_id =~ /(s)(\d+)/) {$supplier_id=$2} my %sqldate = dateforsql($R::date); $R::org_price *=1; #/eval $R::org_qty *=1; #/eval my ($new_qty, $new_price); $new_qty = $R::org_qty;#/;*${unitalias{$R::org_units}}[1]; $new_price = $R::org_price/$R::org_qty; #/remove VAT for single price if pettycash purchase of item having vat if ($R::petty and $R::vat) {$new_price = $new_price /((100 + $cvat)/100)} if ($R::discount) {$new_price = $new_price - $new_price*$R::discount/100} my $results = $dbh->prepare("INSERT INTO purchases (shop_id, stockitems_id, supplier_id,wholesaler_id, org_qty, org_price, org_units, qty, price, discount, invoice, description,date,type,cnote,othertype,vat) values (?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?,?);") or die $dbh->errstr(); $results->execute( $shop{id}, $supplier_id, $wholesaler_id, $R::org_qty, $R::org_price, $R::org_units, $new_qty, $new_price, $R::discount, $R::invoice, $R::description, "$sqldate{year}-$sqldate{month}-$sqldate{day}", $purtype, $R::cnote || '0', $R::othertype, $R::vat ) or die $results->errstr(); $mess = "DATA ADDED."; } } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE purchases SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "STOCK DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { if ($R::othertype < 0) { $mess = "Error: Invalid Entry! Please re-enter the purchase!"; } else { my $supplier_id; my $wholesaler_id; $supplier_id = "NULL";$wholesaler_id = "NULL"; if ($R::supplier_id =~ /(w)(\d+)/) {$wholesaler_id=$2} elsif ($R::supplier_id =~ /(s)(\d+)/) {$supplier_id=$2} my %sqldate = dateforsql($R::date); $R::org_price *=1; #/eval $R::org_qty *=1; #/eval my ($new_qty, $new_price); $new_qty = $R::org_qty;#/*${unitalias{$R::org_units}}[1]; $new_price = $R::org_price/$R::org_qty; #/remove VAT for single price if pettycash purchase of item having vat if ($R::petty and $R::vat) {$new_price = $new_price /((100 + $cvat)/100)} if ($R::discount) {$new_price = $new_price - $new_price*$R::discount/100} my $results = $dbh->prepare("UPDATE purchases SET stockitems_id=NULL, supplier_id=".$supplier_id.", wholesaler_id=".$wholesaler_id.", org_qty=$R::org_qty, org_price=$R::org_price, org_units=$R::org_units, qty=$new_qty, price=$new_price, discount='$R::discount', invoice='$R::invoice', description=?, date='$sqldate{year}-$sqldate{month}-$sqldate{day}', cnote='$R::cnote', vat='$R::vat', othertype=".$R::othertype.", f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::description) or die $results->errstr(); $mess = "DATA MODIFIED."; } } #/## /COMMANDS #/ SPLITS $temphtml .= "STOCK TYPE:
    "; foreach my $acctype (sort keys %{ $stocktypes_breakdown{$database} }) { $temphtml .= "($account_types{$acctype}: "; foreach (sort {$stocktypes{$database}{$a} cmp $stocktypes{$database}{$b}} keys %{ $stocktypes_breakdown{$database}{$acctype} } ) { $temphtml .= "[$stocktypes{$database}{$_}]"; } $temphtml .= ")
    "; } $temphtml .= " | Other Expences"; $temphtml .= " | Wages/Loans" if ($R::petty); $temphtml .= " | Creditors" if ($R::petty); $temphtml .= "
    "; #/ DRAW TABLE PURCH $temphtml .= $table{start}; $temphtml .= ""; $temphtml .= " Description Type Supplier CN TAX Invoice Qty Invoice Units Invoice Price Discount (%) Qty Units Price Value Invoice date"; $temphtml .= ":COMMANDS:" if ($lockflag ==1); $temphtml .= ""; $results = $dbh->prepare(" SELECT pu.id id, pu.qty qty, pu.org_price org_price, round(pu.price,2) price, round(price*qty,2) value, pu.org_qty org_qty, pu.org_units org_units, pu.discount discount, pu.othertype othertype, pu.invoice invoice, pu.description description, DAYOFMONTH(pu.date) day, MONTH(pu.date) month, YEAR(pu.date) year, pu.date date, pu.stockitems_id stockitems_id, pu.supplier_id supplier_id, pu.wholesaler_id wholesaler_id, pu.cnote cnote, pu.vat vat FROM purchases pu WHERE pu.shop_id=$shop{id} and pu.f_status<100 and pu.stockitems_id is null and pu.othertype is not null and pu.type=$purtype $purlimit ORDER BY pu.date,pu.invoice ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #/debug print $results->rows; while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { if (defined $lastinvoicenumber and ($lastinvoicenumber ne $ref->{invoice})) { $temphtml .= " $lastsupname Total: $currency".pr($totalforlastinvoice)." $lastinvoicenumber "; $totalforlastinvoice = 0; } $lastinvoicenumber = $ref->{invoice}; $lastsupplier = $ref->{supplier_id}; $totalforlastinvoice += $ref->{price}*$ref->{qty}; $temphtml .= ""; $temphtml .= " {id}&pdate=$R::pdate&dcashid=$R::dcashid\">$ref->{description}"; if ($ref->{othertype} != -1) { $subresults = $dbh->prepare(" SELECT name FROM bufc WHERE f_status<100 and year=$budgetyear and id=$ref->{othertype} and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $temphtml .="$subref->{name}" } else {$temphtml .="other"} my ($suptable,$supid,$suptype, $useshop, $supname); if (! $ref->{supplier_id}) {$suptable = 'wholesalers'; $supid=$ref->{wholesaler_id};$suptype=1; } else {$suptable = 'suppliers';$useshop="and shop_id=$shop{id}";$supid=$ref->{supplier_id};$suptype=2;} #/fetch supplier/wholesaler $subresults = $dbh->prepare(" SELECT name FROM $suptable WHERE id=$supid $useshop and f_status<100;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $supname = $subref->{name}; $lastsupname = $supname; $temphtml .= " $supname $cnote{$ref->{cnote}} $cnote{$ref->{vat}} $ref->{org_qty} ${ $unitalias{$ref->{org_units}} }[0] $ref->{org_price} $ref->{discount}% $ref->{qty} $units{$ref->{units}} $ref->{price} $ref->{value} $ref->{invoice} $ref->{day}-$ref->{month}-$ref->{year} "; $temphtml .= " {id}&pdate=$R::pdate&dcashid=$R::dcashid&cpstart=$R::cpstart&cpend=$R::cpend\" onclick=\"return confirm('DELETE ITEM: $ref->{item} ?');\">$icons{d} {id}&pdate=$R::pdate&dcashid=$R::dcashid&cpstart=$R::cpstart&cpend=$R::cpend\">$icons{m} " if ($lockflag ==1); $temphtml .= ""; } else { $temphtml .= ""; $temphtml .= " $icons{det} {description}\" $calt> "; my %otsel; $otsel{$ref->{othertype}} = "selected"; my %grps = (2=>"FIXED COSTS / EXPENSES",3=>"SALARIES & WAGES"); my %parentnames; my %childrenparents; my %childrennames; my %standalones; $subresults = $dbh->prepare("select id,name,type,vtype,parent,grp from bufc where grp <> 1 and shop_id=$shop{id} and year=$budgetyear and f_status < 100;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { if (! $subref->{parent} and $subref->{vtype} == 3) { $parentnames{$subref->{grp}}{$subref->{id}} = $subref->{name}; } elsif (! $subref->{parent} and $subref->{vtype} != 3 and $subref->{type} == 1) { $standalones{$subref->{grp}}{$subref->{id}} = $subref->{name}; } elsif ($subref->{type} == 1) { push @{$childrenparents{$subref->{parent}}},$subref->{id}; $childrennames { $subref->{id} } = $subref->{name}; } } $temphtml .="quickfind» find next» "; my (%ssel,%usel,$ct,$vt); $usel{$ref->{org_units}} = "SELECTED"; if (! $ref->{supplier_id}) { $ssel{"w".$ref->{wholesaler_id}}="SELECTED" } else { $ssel{"s".$ref->{supplier_id}}="SELECTED" } $temphtml .=" {org_qty}\" $calt_e3> "; $temphtml .=" {org_price}\" $calt_e> {discount}\" $calt_e> **** {invoice}\" $calt> {day}-$ref->{month}-$ref->{year}\" $calt> $icons{cal} "; $temphtml .= ""; $temphtml .= "{id}>"; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } } $temphtml .= " $lastsupname Total: $currency".pr($totalforlastinvoice)." $lastinvoicenumber "; if ($R::petty) { #/## TOTALS PETTYCASH my %calc; my $results = $dbh->prepare("SELECT SUM(org_price) FROM purchases WHERE shop_id=$shop{id} and f_status<100 and date='$R::pdate' and type=3;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{amount} = $ref; $results = $dbh->prepare("SELECT SUM(amount) FROM loans WHERE shop_id=$shop{id} and f_status<100 and date='$R::pdate';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{amount} += $ref; $results = $dbh->prepare("SELECT SUM(amount) FROM creditors WHERE shop_id=$shop{id} and f_status<100 and date='$R::pdate';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{amount} += $ref; #/comparation/substraction $results = $dbh->prepare("SELECT pettycash FROM dcash WHERE shop_id=$shop{id} and f_status<100 and id=$R::dcashid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = ($results->fetchrow_array())[0]; $calc{diff} = $calc{amount} - $ref; $calc{aspercash} = $ref; if (sprintf("%.2f",$calc{diff}) == 0) {$linecolor=""} else {$linecolor=$errorcolor} $temphtml .= " Total as per Petty Cash ".pr($calc{amount})."
    Total as per cash-up ".pr($calc{aspercash})."
    Shortfall for account of the management ".pr($calc{diff})."
    Petty Cash Summary "; } #/ if petty #/commands add purchases if ($R::command ne "modify" and $lockflag==1) { $temphtml .= ""; $temphtml .= " "; my %grps = (2=>"FIXED COSTS / EXPENSES",3=>"SALARIES & WAGES"); my %parentnames; my %childrenparents; my %childrennames; my %standalones; $subresults = $dbh->prepare("select id,name,type,vtype,parent,grp from bufc where grp <> 1 and shop_id=$shop{id} and year=$budgetyear and f_status < 100;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { if (! $subref->{parent} and $subref->{vtype} == 3) { $parentnames{$subref->{grp}}{$subref->{id}} = $subref->{name}; } elsif (! $subref->{parent} and $subref->{vtype} != 3 and $subref->{type} == 1) { $standalones{$subref->{grp}}{$subref->{id}} = $subref->{name}; } elsif ($subref->{type} == 1) { push @{$childrenparents{$subref->{parent}}},$subref->{id}; $childrennames { $subref->{id} } = $subref->{name}; } } $temphtml .=" quickfind» find next» "; $temphtml .=" "; $temphtml .=" **** $icons{cal} "; $temphtml .= ""; $temphtml .= ""; } $temphtml .= qq ~ ~ if ($lockflag ==1);; $temphtml .= $table{end}; if (!$R::pdate) {$temphtml .= "
    Please specify period: Start date: $icons{cal} --> End date: $icons{cal}
    "; } if ($R::petty) { $temphtml .= "
    Back to Cash-up
    "; } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } #/ end OTHER PURCHASES editor elsif ($socketflag == 1 and $R::action eq "Generic Calenedar") { my $year = (localtime(time))[5] + 1900; $year = $R::year if ($R::year); $template =~ s/\@title\@/Generic Calendar - $year/sgi; my $temphtml; $temphtml .= ""; $temphtml .= "
    Selected year: "; $temphtml .= " "; $temphtml .= ""; for my $month (0..11) { if ($month % 4 == 0 and $month > 0) {$temphtml .= ""} $temphtml .= ""; while ($ref = $results->fetchrow_hashref()) { $temphtml .= ""; $total += $ref->{total}; } $temphtml .= ""; $temphtml .= $table{end}; } else { $template =~ s/\@title\@/PLU STAFF MEALS REPORT/sgi; $temphtml = getform("period"); $temphtml .= ""; $temphtml .= ""; } } if ($R::subaction eq "plusales") { #Man,stupid enough , uh ? do not know sub functions ?????? $temphtml = "
    "; if ($R::command eq "Report") { my $report; my %tabopscovers; my %turnover; my $covers; my %cash; my $tcash; my %ccard; my $tccard; my %cheque; my $tcheque; my %account;my $taccount; my $bar; my $food; my $bev; my $returns; my %returnsfromwaitrons; my %void_reasons; my %returnsauthor; #supervisor my $retail; my $staffmeals; my %retail_food; my %retail_other; my %retail_prices; my %plus; my %cat_plus; my %cat_plutypes; my %cat_plucodes; my %cat_pluids; my %cat_plucost; my %mcatplus; my %mcatnames; my %mcattotals; my %mcattotals_qty; my %plutypes; my %wordsturnover; my @searchedwords; my $plustotal; my $lastcashuptillid; my $totalturnover; ##################################### REPORT $template =~ s/\@title\@/PLU SALES REPORT/sgi; my ($startdate, $enddate, $starttime, $endtime); my (%sqldate,%sqldate2); %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate2 = dateforsql($R::enddate); $enddate = $sqldate2{year}."-".$sqldate2{month}."-".$sqldate2{day}; $starttime = ($R::starttimeh ne "" ? $R::starttimeh : "00").":".($R::starttimem ne "" ? $R::starttimem : "00").":00"; $endtime = ($R::endtimeh ne "" ? $R::endtimeh : "00").":".($R::endtimem ne "" ? $R::endtimem : "00").":00"; #prepare condition my $condition; my $catcondition; my $selectedcatshtml; my $menutypecondition; my $tablecondition; if ($R::qtables) { $tablecondition = "and tilltables.number >= $R::starttable and tilltables.number <= $R::endtable"; $temphtml .= "Tables queried: $R::starttable to $R::endtable"; $temphtml .= "
    ERROR - WRONG TABLES SELECTION!
    " if ($R::endtable < $R::starttable); } else { $tablecondition = ""; } $condition = " and inv.stamp>=\"$startdate $starttime\" and inv.stamp<=\"$enddate $endtime\"" if ($R::startdate ne "" and $R::enddate ne ""); if ( $R::dstarttimeh ne "" and $R::dstarttimem ne "" and $R::dendtimeh ne "" and $R::dendtimem ne "" ) { $temphtml .= "TIME OF DAY FILTERED: FROM $R::dstarttimeh:$R::dstarttimem:00 TO $R::dendtimeh:$R::dendtimem:00
    "; if ( ($R::dendtimeh*60+$R::dendtimem) < ($R::dstarttimeh*60+$R::dstarttimem) ) { #over midnight $condition .= " and (time(inv.stamp) >= '$R::dstarttimeh:$R::dstarttimem:00' or time(inv.stamp) <= '$R::dendtimeh:$R::dendtimem:00') "; } else { #same day $condition .= " and (time(inv.stamp) >= '$R::dstarttimeh:$R::dstarttimem:00' and time(inv.stamp) <= '$R::dendtimeh:$R::dendtimem:00') "; } } my %clientnames; if ($R::clientgroup or (scalar @R::client) or $R::clientfolder or $R::clientcode) { my @match; my $clientcond; if (scalar @R::client) { $clientcond = "id in(".join(",",@R::client).")"} $temphtml .= "Clients matching your search: "; my @c_filter; push @c_filter, "code LIKE '" . $R::clientcode . "'" if $R::clientcode; push @c_filter, "clientfolder LIKE '" . $R::clientfolder . "'" if $R::clientfolder; push @c_filter, "clientgroup LIKE '" . $R::clientgroup . "'" if $R::clientgroup; my $cc_filters = " OR (" . join(" AND ",@c_filter) . ")" if scalar(@c_filter); my $SQL = qq|select id,name,code,clientgroup from $sharedclients.tillclients where $clientcond $cc_filters |; $results = $dbh->prepare($SQL) or die $dbh->errstr(); # TODO fix names #if (! $R::clientcode) { # $R::clientcode = "%"; #} #if (! $R::clientfolder) { # $R::clientfolder = "%"; #} #if (! $R::clientgroup) { # $R::clientgroup = "%"; #} $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { push @match,$ref->{id}; $temphtml .= "$ref->{code} - $ref->{clientgroup}, $ref->{name};"; $clientnames{$ref->{id}} = $ref->{name}; #TODO - later display matches } $temphtml .= "
    FOLDER FILTER: $R::clientfolder, GROUP/CLIENT FILTER: $R::clientgroup
    "; if (scalar @match) { $condition .= " and inv.client_id in (".join(",",@match).")"; } else { $condition .= " and inv.client_id in (-1)"; $temphtml .= "No Clients found."; } } $menutypecondition .= " and menu.type=$R::plutype " if ($R::plutype>0); $condition .= " and ttod.waitron_id=$R::waitron " if ($R::waitron>0); if (! $R::qcategory and @R::category) { my $categories .= join (",",@R::category); $catcondition = "and $menu_db.menu.menu_category in ($categories) "; $selectedcatshtml = "Selected menu category:"; $results = $dbh->prepare("select name from $menu_db.menu_categories where id in ($categories)") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $selectedcatshtml .= "
  • $ref->{name}"; } } elsif (! $R::qcategory and ! @R::category) { # $catcondition = "and menu.menu_category =-1 "; } $temphtml .= $selectedcatshtml; #search function my $searchstring; if ($R::search) { $R::search =~ s/"|'//gsi; my @searchwords = split (/\+/, $R::search); foreach (@searchwords) { $_ =~ s/(^\s|^\s+)|(\s+$|\s+$)//gsi; push @searchedwords, $_; $_ = "menu.name like \"%".$_."%\""; } $searchstring = "and (".join(" or ",@searchwords).")"; $temphtml .= "
    SEARCHING FOR: $R::search"; } $temphtml .= "
    SKU CODE FILTER: $R::sku"; $results = $dbh->prepare(" SELECT * FROM suppliers WHERE me = 1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $temphtml .= "
    Company Name: $ref->{name}
    "; #prepare menu my (%menu_details,%cat_names); $R::sku = "*" if !$R::sku; $R::sku =~ s/\*/\%/gsi; $results = $dbh->prepare(" select menu.id id, menu.name name, menu.type type, menu_categories.name cat_name, menu_categories.id cat_id from $menu_db.menu menu, $menu_db.menu_categories where menu.menu_category = menu_categories.id and menu.code like ? $menutypecondition $catcondition $searchstring ;") or die $dbh->errstr(); $results->execute($R::sku) or die $results->errstr(); while($ref = $results->fetchrow_hashref()) { $menu_details{$ref->{id}}{name} = $ref->{name}; $menu_details{$ref->{id}}{type} = $ref->{type}; $menu_details{$ref->{id}}{cat_id} = $ref->{cat_id}; $cat_names{$ref->{cat_id}} = $ref->{cat_name} } #debug print ( join(',',keys %menu_details) ); #/prepare menu my $menucondition; if (scalar keys %menu_details) { $menucondition = "and ttod.plu in (".join(',',keys %menu_details).")"; } else { $menucondition = "and ttod.plu in (-1)"; } if ($R::waitron>0){ $results = $dbh->prepare("select name from waitron where id = $R::waitron and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $temphtml .= "
    Queried Waitron: $ref->{name}
    "; } my $invoices; my $SQL = qq|select inv.account account, inv.cash cash, inv.ccard ccard, inv.cheque cheque, inv.id invoice, ((ttod.price - ttod.discount)*ttod.qty) price, ttod.price - ttod.discount uprice, ttod.discount, ttod.qty qty, ttod.plu, inv.id inv, inv.void_reason void_reason, inv.supervised_by supervised_by, inv.voided voided, tto.id orderid, tto.current_covers covers, tilltables.type ttype, ttod.name name, tilltables.number number from tillordersdetails ttod, tillorders tto, tillinvoices inv, tilltableops tabops, tilltables where ttod.shop_id=$shop{id} and tto.shop_id=$shop{id} and inv.shop_id=$shop{id} and tabops.shop_id=$shop{id} and tilltables.shop_id=$shop{id} and ttod.f_status < 101 and tto.f_status < 101 and inv.f_status < 101 and tabops.f_status < 101 and tilltables.f_status < 101 and tabops.id = tto.tableops_id and tilltables.id = tabops.table_id and ttod.orders_id = tto.id and tto.confirm_status=3 and ttod.plutype = 1 and ttod.menusource = 1 $tablecondition $menucondition and inv.id = ttod.invoice $condition and (inv.voided is NULL or inv.voided = 0);|; #logit($SQL); $results = $dbh->prepare(" select inv.account account, inv.cash cash, inv.ccard ccard, inv.cheque cheque, inv.id invoice, ((ttod.price - ttod.discount)*ttod.qty) price, ttod.price - ttod.discount uprice, ttod.discount, ttod.qty qty, ttod.plu, inv.id inv, inv.void_reason void_reason, inv.supervised_by supervised_by, inv.voided voided, tto.id orderid, tto.current_covers covers, tilltables.type ttype, ttod.name name, tilltables.number number from tillordersdetails ttod, tillorders tto, tillinvoices inv, tilltableops tabops, tilltables where ttod.shop_id=$shop{id} and tto.shop_id=$shop{id} and inv.shop_id=$shop{id} and tabops.shop_id=$shop{id} and tilltables.shop_id=$shop{id} and ttod.f_status < 101 and tto.f_status < 101 and inv.f_status < 101 and tabops.f_status < 101 and tilltables.f_status < 101 and tabops.id = tto.tableops_id and tilltables.id = tabops.table_id and ttod.orders_id = tto.id and tto.confirm_status=3 and ttod.plutype = 1 and ttod.menusource = 1 $tablecondition $menucondition and inv.id = ttod.invoice $condition and (inv.voided is NULL or inv.voided = 0) group by ttod.invoice") or die $dbh->errstr();#added "group by " --steven $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $invoices->{ $ref->{invoice} } = 1; } my $invoice_details; #invoice totals - before end foreach my $invoice (%{$invoices}) {## any purpose? wasting CPU ? -- croaked by steven #below comment off by Steven ** #**$results = $dbh->prepare(" #** select #** sum(ttod.qty*ttod.price) total, #** sum(ttod.qty*ttod.discount) totaldiscount, #** inv.discount invoicediscount #** from tillordersdetails ttod, tillinvoices inv #** where ttod.invoice = ? and inv.id = ttod.invoice #**") or die $dbh->errstr(); #**$results->execute($invoice) or die $results->errstr(); #**$ref = $results->fetchrow_hashref(); #~ $invoice_details->{$invoice}->{discount} = $ref->{invoicediscount} - $ref->{totaldiscount}; #~ $invoice_details->{$invoice}->{total} = $ref->{total}; #~ my $net_total = $invoice_details->{$invoice}->{total} - $ref->{totaldiscount}; #~ if ($net_total > 0) { #~ $invoice_details->{$invoice}->{discount_percent} = #~ $invoice_details->{$invoice}->{discount}/$net_total; #~ } } #~ open DDD, ">/dddd"; #~ print DDD Dumper(\$invoice_details); #~ close DDD; my $SQLL = qq| select inv.account account, inv.cash cash, inv.ccard ccard, inv.cheque cheque, inv.id invoice, menu.code, menu.stockid, ((ttod.price - ttod.discount)*ttod.qty) price, (ttod.price*ttod.qty) grossprice, (ttod.price) uprice, ttod.discount discount, tax.percent AS taxpercent, ttod.qty qty, ttod.plu, inv.id inv, inv.void_reason void_reason, inv.supervised_by supervised_by, inv.voided voided, tto.id orderid, tto.current_covers covers, tilltables.type ttype, ttod.name name, tilltables.number number from tillordersdetails ttod, tillorders tto, tillinvoices inv, tilltableops tabops, tilltables, menu LEFT JOIN menu_tax mtax on mtax.menu_id = menu.id LEFT JOIN tax ON tax.id = mtax.tax_id where ttod.shop_id=$shop{id} and tto.shop_id=$shop{id} and inv.shop_id=$shop{id} and tabops.shop_id=$shop{id} and tilltables.shop_id=$shop{id} and ttod.f_status < 101 and tto.f_status < 101 and inv.f_status < 101 and tabops.f_status < 101 and tilltables.f_status < 101 and menu.id = ttod.plu and tabops.id = tto.tableops_id and tilltables.id = tabops.table_id and ttod.orders_id = tto.id and tto.confirm_status=3 and ttod.plutype = 1 and ttod.menusource = 1 $tablecondition $menucondition and inv.id = ttod.invoice $condition and (inv.voided is NULL or inv.voided = 0)|; #logit($SQLL); $results = $dbh->prepare(" select inv.account account, inv.cash cash, inv.ccard ccard, inv.cheque cheque, inv.id invoice, menu.code, menu.stockid, ((ttod.price - ttod.discount)*ttod.qty) price, (ttod.price*ttod.qty) grossprice, (ttod.price) uprice, ttod.discount discount, tax.percent AS taxpercent, ttod.qty qty, ttod.plu, inv.id inv, inv.void_reason void_reason, inv.supervised_by supervised_by, inv.voided voided, tto.id orderid, tto.current_covers covers, tilltables.type ttype, ttod.name name, tilltables.number number from tillordersdetails ttod, tillorders tto, tillinvoices inv, tilltableops tabops, tilltables, menu LEFT JOIN menu_tax mtax on mtax.menu_id = menu.id LEFT JOIN tax ON tax.id = mtax.tax_id where ttod.shop_id=$shop{id} and tto.shop_id=$shop{id} and inv.shop_id=$shop{id} and tabops.shop_id=$shop{id} and tilltables.shop_id=$shop{id} and ttod.f_status < 101 and tto.f_status < 101 and inv.f_status < 101 and tabops.f_status < 101 and tilltables.f_status < 101 and menu.id = ttod.plu and tabops.id = tto.tableops_id and tilltables.id = tabops.table_id and ttod.orders_id = tto.id and tto.confirm_status=3 and ttod.plutype = 1 and ttod.menusource = 1 $tablecondition $menucondition and inv.id = ttod.invoice $condition and (inv.voided is NULL or inv.voided = 0);") or die $dbh->errstr(); $results->execute() or die $results->errstr(); my %plutax; while ($ref = $results->fetchrow_hashref()) { my $discount = $ref->{discount} / 1; my $invoice = $ref->{invoice}; #~ 14 + X = 34 if ($invoice_details->{$invoice}->{discount_percent} > 0) { $discount += $ref->{price} * $invoice_details->{$invoice}->{discount_percent}; } #~ $ref->{price} = $ref->{grossprice} - $discount; $mcatnames{ $menu_details{$ref->{plu}}{cat_id} } = $cat_names{ $menu_details{$ref->{plu}}{cat_id} }; $mcattotals{ $menu_details{$ref->{plu}}{cat_id} } += sprintf("%.2f",$ref->{price}); $mcattotals_qty{ $menu_details{$ref->{plu}}{cat_id} } += $ref->{qty}; $menu_details{$ref->{plu}}{name} = $ref->{name}; $plutax{$ref->{name}} = $ref->{taxpercent}; #categorized plus $mcatplus{ $menu_details{$ref->{plu}}{cat_id} }{ $menu_details{$ref->{plu}}{name} } += 1; $cat_plus{plunames}{ $menu_details{$ref->{plu}}{cat_id} }{ $menu_details{$ref->{plu}}{name} }{ $ref->{uprice} }{$discount} = 1; $cat_plus{pluqty}{ $menu_details{$ref->{plu}}{cat_id} }{ $menu_details{$ref->{plu}}{name} }{ $ref->{uprice} }{$discount} += $ref->{qty}; #$cat_plus{pluprices}{$mcatid}{$a}*$cat_plus{pluqty}{$mcatid}{$a} $cat_plus{allpluqty}{ $menu_details{$ref->{plu}}{cat_id} }{ $menu_details{$ref->{plu}}{name} } += $ref->{qty}; $cat_plus{pluprices}{ $menu_details{$ref->{plu}}{cat_id} }{ $menu_details{$ref->{plu}}{name} } = $ref->{uprice}; $cat_plus{plutotal}{ $menu_details{$ref->{plu}}{cat_id} }{ $menu_details{$ref->{plu}}{name} } += $ref->{price}; $cat_plutypes{ $menu_details{$ref->{plu}}{cat_id} }{ $menu_details{$ref->{plu}}{name} } = $menu_details{$ref->{plu}}{type}; $cat_plucodes{ $menu_details{$ref->{plu}}{cat_id} }{ $menu_details{$ref->{plu}}{name} } = $ref->{code}; $cat_pluids{ $menu_details{$ref->{plu}}{cat_id} }{ $menu_details{$ref->{plu}}{name} } = $ref->{plu}; if ($R::gpreport) { my $buyingprice; my $stockitem_id = $ref->{stockid}; if ($stockitem_id) { if ($R::enddate) { my %sqldate = dateforsql($R::enddate); my $querydate = "$sqldate{year}-$sqldate{month}-$sqldate{day}"; $subresults = $dbh->prepare(" select (purchases.price - purchases.discount) price from purchases,branch_documents bd where purchases.price != 0 and bd.current_stage != 1 and purchases.document_id = bd.id and (purchases.cnote != 1 or purchases.cnote is NULL or purchases.cnote = 0) and purchases.date <= ? and purchases.stockitems_id = ? order by purchases.date desc limit 1;") or die $subresults->errstr(); $subresults->execute($querydate, $stockitem_id) or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $buyingprice = $subref->{price}; } else { $subresults = $dbh->prepare(" select (purchases.price - purchases.discount) price from purchases where price != 0 and stockitems_id = ? order by date desc limit 1;") or die $subresults->errstr(); $subresults->execute($stockitem_id) or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $buyingprice = $subref->{price}; } } else { my %sqldate = dateforsql($R::enddate); my $querydate = "$sqldate{year}-$sqldate{month}-$sqldate{day}"; $querydate = '' if (! $R::enddate); $subresults = $dbh->prepare(" select rn.name, mr.id,mr.recipe_units units, mr.qty, mr.recipe_id,ry.yield yqty from menu_recipes mr, recipe_names rn,recipe_yields ry where ry.recipe_id = rn.id and mr.recipe_units = ry.yield_unit and mr.recipe_id = rn.id and mr.menu_id = ? ;") or die $subresults->errstr(); $subresults->execute($ref->{plu}) or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $buyingprice += daterecipecost($subref->{recipe_id},$dbh,$querydate) * ( $subref->{qty} / $subref->{yqty} ); } } $cat_plucost{ $menu_details{$ref->{plu}}{cat_id} }{ $menu_details{$ref->{plu}}{name} } = $buyingprice; } #flat version $plus{distictplunames}{ $menu_details{$ref->{plu}}{name} }{$ref->{uprice}} = 1; $plus{plutypes}{ $menu_details{$ref->{plu}}{name} } = $menu_details{$ref->{plu}}{type}; $plus{plunames}{ $menu_details{$ref->{plu}}{name} } = 1; $plus{pluqty}{ $menu_details{$ref->{plu}}{name} }{$ref->{uprice}} += $ref->{qty}; $plutypes{ $menu_details{$ref->{plu}}{name} } = $ref->{type}; $plus{pluprices}{ $menu_details{$ref->{plu}}{name} } = $ref->{uprice}; $plus{plutotal}{ $menu_details{$ref->{plu}}{name} } += $ref->{price}; $plus{covers}{$ref->{inv}}{$ref->{covers}} = 1; $plus{tables}{$ref->{number}} = 1; #distinct table numbers $plus{total} += $ref->{price}; $turnover{$ref->{type}} += $ref->{price}; if ($ref->{voided} == 2) { $returns += $ref->{price}; $returnsfromwaitrons{$ref->{inv}} = $R::autocash; $returnsauthor{$ref->{inv}} = $ref->{supervised_by}; $void_reasons{$ref->{inv}} = $ref->{void_reason}; } $bar += $ref->{price} if ($ref->{ttype} == 2 and $ref->{type} == 2); # 2 = bar liq only $staffmeals += $ref->{price} if ($ref->{ttype} == 4); # 4 = staff #retail food - detailed - RETAIL.type=99 if($ref->{type} == 3) { $retail_food{ $menu_details{$ref->{plu}}{name} } += $ref->{qty}; $retail_prices{ $menu_details{$ref->{plu}}{name} } = $ref->{uprice}} #retail other - detailed - RETAIL.type = 100 if($ref->{type} == 4) { $retail_other{ $menu_details{$ref->{plu}}{name} } += $ref->{qty}; $retail_prices{ $menu_details{$ref->{plu}}{name} } = $ref->{uprice} } } #fetch invoice totals ###################################### foreach my $tbill (keys %{$plus{covers}}) { $covers += $_ foreach (keys %{$plus{covers}{$tbill}} ); } my $emptyline; $temphtml .= "
    PLU SALES FOR "; if($R::startdate ne "" and $R::enddate ne "") { $temphtml .= "$R::startdate $starttime - $R::enddate $endtime"; } else { $temphtml .= "UNLIMITED PERIOD
    (report date: $datetime)
    "; $temphtml .= "DAYS COVERED: "; $results = $dbh->prepare("select count(distinct DATE_FORMAT(stamp, '%e %M %Y')) days from tillordersdetails;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $temphtml .= "$ref->{days}; "; $temphtml .= "COVERED PERIOD: "; $results = $dbh->prepare("select distinct DATE_FORMAT(min(stamp), '%e %M %Y') start from tillordersdetails;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $temphtml .= "$ref->{start} - "; $results = $dbh->prepare("select distinct DATE_FORMAT(max(stamp), '%e %M %Y') end from tillordersdetails;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $temphtml .= "$ref->{end}"; } $temphtml .= "
    "; $temphtml .= "
  • "; #/ Month Cell $temphtml .= ""; $temphtml .= "
    $mnames{$month}"; $temphtml .= "
    "; $temphtml .= ""; #/week days table $temphtml .= "" foreach (sort {$a<=>$b} keys %dnames); #/day titles $temphtml .= ""; $temphtml .= ""; my $shiftday = dayofweek(1,$month,$year) - 1; $temphtml .= ""x$shiftday; for my $day (1..( lastday($month+1,$year))) { if (($day+$shiftday) % 7 == 1) {$temphtml .= ""} $temphtml .= ""; my @sortedids; if ($R::command eq "sortbyvalue") { @sortedids = sort {$fiforesultz{$b}{usage_value} <=> $fiforesultz{$a}{usage_value}} keys %availables; } else { @sortedids = sort {$stockdetails{$sortage}{$a} cmp $stockdetails{$sortage}{$b}} keys %availables; } my $incrementalusage; my $lastincrementalusage; foreach my $id ( @sortedids ) { $incrementalusage += $fiforesultz{$id}{usage_value}; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $lastincrementalusage = $incrementalusage; } $temphtml .= $table{end}; #/calculate foodcost $temphtml .= "

    $dnames{$_}
    year + 1900; $year = $R::year if ($R::year); $template =~ s/\@title\@/Stock Issues Calendar - $year/sgi; my $temphtml; $temphtml .= ""; $temphtml .= "
    Selected year: "; $temphtml .= " "; #~ open(DDD,">/DDD"); #~ print DDD $year; #~ close(DDD); my %issues; $results = $dbh->prepare(" select GROUP_CONCAT(direction) direction, month(date) - 1 month,day(date) day from stockissue where year(date) = '$year' group by date ; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ foreach ( split ( ',', $ref->{direction} ) ) { $issues{$ref->{month}}{$ref->{day}}{$_} = 1; } } if ($R::month and $R::day) { $temphtml .= "
    "; $R::month ++; $results = $dbh->prepare(" select stockitems.type type, stocktypes.name name, stockissue.direction direction from stockissue, stockitems,stocktypes where stockitems.id = stockissue.stockitems_id and stocktypes.id = stockitems.type and stockissue.date = '$year-$R::month-$R::day' group by stockitems.type, stockissue.direction; ; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); my $linkdate = sprintf("%02d/%02d/%4d" , $R::day, $R::month,$year); while ($ref = $results->fetchrow_hashref()){ $temphtml .= "
  • Go to $year $R::month $R::day - $issuetypes{$ref->{direction}} / $stocktypes{$database}{$ref->{type}}"; } $temphtml .= "
  • "; } $temphtml .= ""; for my $month (0..11) { if ($month % 4 == 0 and $month > 0) {$temphtml .= ""} $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; my $searchingfor = "name like '$tempdb{stockletter}%'"; $searchingfor = "name like '%$R::searchstring%'" if $R::searchstring ne ""; if ($edit_stock_items) { $results = $dbh->prepare("SELECT * FROM stockitems WHERE $searchingfor and type='$tempdb{stocktype}' and shop_id = $shop{id} and f_status<100 ORDER BY stockcats_id,name;") or die $dbh->errstr(); }else { $results = $dbh->prepare("SELECT * FROM stockitems WHERE $searchingfor and stockitem<>2 and type='$tempdb{stocktype}' and shop_id = $shop{id} and f_status<100 ORDER BY stockcats_id,name;") or die $dbh->errstr(); }; $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $subresults = $dbh->prepare("SELECT count(id) activity FROM purchases WHERE shop_id=$shop{id} and f_status<100 and stockitems_id = $ref->{id};") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $subresults->finish(); my $activity = $ref1->{activity}; $subresults = $dbh->prepare(" SELECT count(id) linked FROM ritems WHERE stockitems_id = $ref->{id};") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $subresults->finish(); $activity += $ref1->{linked}; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; my (%usel,%binsel,%catsel); $usel{$ref->{units}}="selected"; $binsel{$ref->{bin}}="selected"; $catsel{$ref->{stockcats_id}}="selected"; $temphtml .= " "; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } } if ($R::command ne "modify" and $edit_stock_items > 0) { $temphtml .= ""; $temphtml .= ""; $temphtml .=""; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= "
    Jump to Suppliers | "; $temphtml .= " Jump to Categories | "; $temphtml .= " Jump to Bins | "; $temphtml .= " Jump to Stock Types "; if ($R::fpurchases) { if ($R::fpurchases == 1) { $temphtml .= "
    Back to Purchases
    "; } else {#/ back to opening stock $temphtml .= "
    Back to Opening Stock
    "; } } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } #/ end stockitems editor ################################### process Template part Start, POS Steven#################### elsif ( ($socketflag == 1 and ($R::a ne "" or $R::page ne "") ) || ($socketflag != 1 and ($R::a eq "getkey") ) ) { my $output; my $config = {EVAL_PERL => 1, COMPILE_DIR => "$tdir/.ttcs/", COMPILE_EXT => '.ttc', ABSOLUTE => 1, OUTPUT_PATH => "/wwwroot" }; my $p = MD5T->new($config); $config->{LOAD_TEMPLATES} = [$p]; $config->{PREFIX_MAP} = {default => 0}; #my $tt = Template->new($config); #~ my $ttemplate = Template->new(ABSOLUTE => 1,COMPILE_EXT => '.ttc', #~ EVAL_PERL => 1, #~ OUTPUT_PATH => "/wwwroot/tmp"); my $ttemplate = Template->new($config); my $vars = { lastday => sub { return lastday($_[0],$_[1]) }, uri_escape => sub { return uri_escape ($_[0])}, uri_unescape => sub { return uri_unescape ($_[0])}, gender => \%gender, sett => \%sys_settings, #$settings::anything, notecases => \%notecases, sprintf => \&sprintf, months => \%months, weekdays => \%weekdays, wdays => \@wdays, repeat_drop => \%alarm_repeats, repeat_words => \%alarm_repeats_when, priority_drop => \%priority, livevariance => $sys_settings{'livevariance'},#$settings::livevariance, account_types => \%account_types, direction => \%issuetypes, odbcdays => \%odbcdays, odbcdaysorder => \@odbcdayorder, lwpget => sub { return get($_[0]) }, iid => ${$leap->{iid}}, yam => sub { my $hashref; eval {$hashref = Load($_[0]);}; return $hashref; }, delfile => sub { unlink($_[0]); }, deldir => sub { rmdir($_[0]); }, stringtimefull => sub { return genericstringtimefull($_[0],1); }, stringtimeshort => sub { return stringtimeshort($_[0],1); }, copyfile => sub { return copyfile($_[0],$_[1]); }, fieldtype => {1 => "textfield", 2 => "textarea", 3 => "date", 4 => "dropdown", 5 => "file folder", 200 => "header"}, gethires => sub { return [gettimeofday]; }, interval => sub { my ($stime, $etime) = ($_[0],[gettimeofday]); return tv_interval($stime,$etime); }, sorter => sub { # usage [% sortkeys = sorter(hashofhashes,'text'?) my %h = %{$_[0]}; my @sortedkeys; if ($_[3] eq 'text') { @sortedkeys = sort {$h{$a}->{$_[1]} cmp $h{$b}->{$_[1]}} sort {$h{$a}->{$_[2]} cmp $h{$b}->{$_[2]}} keys %h; } else { @sortedkeys = sort {$h{$a}->{$_[1]} <=> $h{$b}->{$_[1]}} sort {$h{$a}->{$_[2]} <=> $h{$b}->{$_[2]}} keys %h; } return \@sortedkeys; }, dumper => sub { return print "
    ".Dumper($_[0])."
    " }, recipe_usage => sub { my $recipe_id = $_[0]; my $yield_units = $_[1]; my $recipe_usage_qty = $_[2]; my $qty = $_[3]; $results = $dbh->prepare("select * from recipe_yields where recipe_id = ? and yield_unit = ?; ;") or die $dbh->errstr(); $results->execute($recipe_id,$yield_units) or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $total_recipe_yield = $ref->{yield}; my $divider = $total_recipe_yield/$recipe_usage_qty; my %usage = &recipeingredients($recipe_id,$divider, {dbh => $dbh} ); #return Dumper(\%usage); my %stockusage; foreach my $ritem_id (keys %usage) { $results = $dbh->prepare(" select ritems.stockitems_id, ritems.yield ryield, ritems.units runits from ritems where id = ?; ;") or die $dbh->errstr(); $results->execute($ritem_id) or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{ryield} > 0) { $stockusage{$ref->{stockitems_id}} += $unitalias{$ref->{runits}}[1] * (100/$ref->{ryield}) * $usage{$ritem_id} * $qty ; } } return \%stockusage; }, recipe_cost => sub{ my $verbose = $_[1]; $verbose = 0 if ($verbose eq 'false'); my ($temphtml, $usagetotal) = recipecost($_[0],$dbh,$verbose); return $temphtml; }, myip => sub { my $ip; if ( $ENV{ HTTP_X_FORWARDED_FOR } ) { #ip behind proxy $ip = $ENV{ HTTP_X_FORWARDED_FOR}; } else { #plain $ip = $ENV{ REMOTE_ADDR }; } return $ip; }, cleardemo => sub { my $ret = cleardemo({ dbh => $dbh, shop_id => $shop{id}, database => $database, autocash => $_[0] }); return $ret; }, cashup => sub { my $ret = cashup({ dbh => $dbh, shop_id => $shop{id}, database => $database, cvat => $cvat, autocash => $_[0], theshift => $_[1], dcash_id => $_[2] }); return $ret; }, report => sub { my $ret = reportuser({ dbh => $dbh, shop_id => $shop{id}, database => $database, cvat => $cvat, autocash => $_[0], last_tillid => $_[1], shortreport => $_[2], reporttype => $_[3], printer => $_[4] }); return $ret; }, recipe_cost_cost => sub { my ($temphtml, $usagetotal) = recipecost($_[0],$dbh,0); return $usagetotal; }, validateID => sub{return validateID($_[0])}, tabletypes => \%tilltabletype, tilltablelocation => \%tilltablelocation, ageID => sub{return ageID($_[0])}, verify_id => $sys_settings{'validateid'},#$settings::validateid, calc_property => sub{ my $stockitem = $_[0]; calculate_stockitem_properties($stockitem, $dbh) }, calc_all_properties => sub{ calculate_allstockitem_properties($dbh) }, popup_drop => {1 => 'No', 2 => 'Yes'}, barcode_horiz => sub{ create_horizontal_label($_[0],$tdir.$_[1],$_[2],$_[3],$_[4],$_[5]); }, barcode_horiz_a => sub{ create_horizontal_label_a($_[0],$tdir.$_[1],$_[2],$_[3],$_[4],$_[5]); }, barcode_vert => sub{ create_vertical_label( $_[0],$tdir.$_[1],$_[2],$_[3],$_[4],$_[5],$_[6]); }, barcode_sheet => sub{ create_sheet_label($_[0],$tdir.$_[1],$_[2] ); }, w107barcode_sheet => sub{ create_w107sheet_label($_[0],$tdir.$_[1], $_[2],$_[3],$_[4],$_[5] ); }, createzebracard => sub{ my @data = ( { 'code' => $_[0], 'name' => $_[1] } ); createzebracard(\@data, $_[2],$shop{name}); }, loyalty_cards_sheet => sub{ create_loyalty_cards_sheet($_[0],$tdir.$_[1],$database ); }, create_loyalty_cards_sheet_with_photo =>sub{ create_loyalty_cards_sheet_with_photo($_[0],$tdir.$_[1],$database,$shop{name}); }, message => "", sessionusername => $username, profile => $profile, database => $database, dbhost => $dbhost, ccscreen => $sys_settings{'ccscreen'},#$settings::ccscreen, stocktypes => \%{$stocktypes{$database}}, bstartmonth => $sys_settings{'bstartmonth'},#$settings::bstartmonth, budgetyear => $budgetyear, psubst => \%psubst, dbuser => $dbuser, grps => {2=>"FIXED COSTS / EXPENSES",3=>"SALARIES & WAGES", 4=>'CAPITAL EXPENSES'}, dbpassword => $dbpassword, ENV => \%ENV, tdir => $tdir, mycgi => new Template::Plugin::CGI, date => $date, shopname => $shop{name}, active_drop => \%yes_no, redeem_options => {1 => "No", 2 => "Autoredeem all collected points", 3 => 'Autoredeem requested points only'}, sharedclients => $sharedclients, documents => \%documents, sbt_documents => \%sbt_documents, sbt_transaction_types => \%sbt_transaction_types, currency => $currency, cvat => $cvat, nvat => $btax{$database}{nvat}, pr => sub { return(pr($_[0])) }, pr2=> sub { return(pr2($_[0])) }, set_pucat => $sys_settings{'pucat'},#$settings::pucat, set_pucode => $sys_settings{'pucode'},#$settings::pucode, set_putype => $sys_settings{'putype'},#$settings::putype, units => \%units, unitalias => \%unitalias, cook => sub { if (defined $_[1]) { $session->param($database."$_[0]", $_[1]); return '' } else { return $session->param($database."$_[0]"); } }, slurp => sub { return slurpanyfile($_[0]) }, dbh => $dbh }; my $file; my $tempfile; if ($blamamura_mode == 1) { if (-f $tdir."Templates/a_$R::a.html" and ! $R::forcepage) { $file = $tdir."Templates/a_$R::a.html"; $tempfile = (slurpfile($file)) || "SpaceBiz: Template $file not found"; }elsif (-f $tdir."a_$R::a.html" and ! $R::forcepage) { $file = $tdir."a_$R::a.html"; $tempfile = (slurpfile($file)) || "SpaceBiz: Template $file not found"; } elsif (-f $tdir."Templates/$R::page.html") { $file = $tdir."Templates/$R::page.html"; $tempfile = (slurpfile($file)) || "SpaceBiz: Template $file not found"; } elsif (-f $tdir."$R::page.html") { $file = $tdir."$R::page.html"; $tempfile = (slurpfile($file)) || "SpaceBiz: Template $file not found"; }else { #unknown action 404 $file = $tdir."Templates/404.html"; $tempfile = slurpfile($file) || "SpaceBiz: Template $file not found"; } } elsif ($blamamura_mode == 2) { if ($Blamamura::template->{"a_".$R::a.".html"} ne '') { $file = "a_".$R::a.".html"; $tempfile = $Blamamura::template->{$file}; }elsif (-f $tdir."Templates/$R::page.html") { $file = $tdir."Templates/$R::page.html"; $tempfile = (slurpfile($file)) || "SpaceBiz: Template $file not found"; }elsif (-f $tdir."$R::page.html") { $file = $tdir."$R::page.html"; $tempfile = (slurpfile($file)) || "SpaceBiz: Template $file not found"; } else { $file = $tdir."Templates/a_".$R::a.".html"; $tempfile = "SPACE TEMPLATE TOOLKIT: Unknown template definition: \"$file\" for action \"$R::a\"
    ".$Blamamura::template->{$file}; } } my $temphtml = $ttemplate->process(\$tempfile, $vars, \$output) || die "Template process failed: ", $ttemplate->error(), "\n"; $template = ""; print $output; } # tempz elsif ($socketflag == 1 and $R::action eq "Edit Clients") { my $temphtml; $onload="document.form1.name.focus();"; $template =~ s/\@title\@/Edit Clients/sgi; $temphtml = "
    "; #/## SUPPLIER EDIT COMMANDS if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { if ($R::cardfootprint =~ /^(\%)(.*?)(\?\;)(\d+)(\D)/i) { $R::loyalnumber = $4 } $R::name=~ tr/a-z/A-Z/; $R::group = "NO GROUP" if (! $R::group); $R::discountpercent = 0 if ($R::type != 4); my $results = $dbh->prepare("INSERT INTO $sharedclients.tillclients (shop_id,name, note,clientgroup,type,address,telephone,cellphone,active, loyalnumber, expiremonth, expireyear, discountpercent, cardfootprint) values ($sharedclients_shopid,?,?,?,'$R::type',?,?,?,?,?,?,?,?,?);") or die $dbh->errstr(); $results->execute($R::name,$R::note,$R::group,$R::address,$R::telephone,$R::cellphone,$R::active,$R::loyalnumber,$R::emonth,$R::eyear,$R::discountpercent, $R::cardfootprint) or die $results->errstr(); $mess = "DATA ADDED."; } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE $sharedclients.tillclients SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "SUPPLIER DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { if ($R::cardfootprint =~ /^(\%)(.*?)(\?\;)(\d+)(\D)/i) { $R::loyalnumber = $4 } $R::group = "NO GROUP" if (! $R::group); $R::discountpercent = 0 if ($R::type != 4); $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("UPDATE $sharedclients.tillclients SET name=?, note=?, clientgroup=?, type='$R::type', telephone='$R::telephone', cellphone='$R::cellphone', address=?, loyalnumber=?, expiremonth=?, expireyear=?, discountpercent=?, cardfootprint=?, active='$R::active', f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::name,$R::note,$R::group,$R::address,$R::loyalnumber,$R::emonth,$R::eyear,$R::discountpercent, $R::cardfootprint) or die $results->errstr(); $mess = "DATA MODIFIED."; } #/## /COMMANDS #/ DRAW TABLE SUPPLIER my $block; $temphtml .= $table{start}; $block .= "
    "; $block .= " "; $block .= ""; $results = $dbh->prepare("SELECT * FROM $sharedclients.tillclients WHERE shop_id = $sharedclients_shopid and f_status<100 ORDER BY type,active,clientgroup,name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); my $prevtype; my $prevactive; if (! $results->rows) {$temphtml .= $block;} while ($ref = $results->fetchrow_hashref()) { if ($prevtype != $ref->{type}) { $temphtml .= ""; $temphtml .= $block; } if ($prevactive and $prevactive != $ref->{active} and $ref->{active} == 2) { $temphtml .= ""; } $prevactive = $ref->{active}; $prevtype = $ref->{type}; if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= "Note: Please use the POS system terminals to edit the take away customers."; $temphtml .= ""; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "Edit Stock Cats") { #/no permanent stages yet - init $tempdb{stocktype} = (sort {$a <=> $b} keys %{ $stocktypes{$database} } )[0] if (! $tempdb{stocktype}); $tempdb{stocktype} = $R::stocktype if ($R::stocktype>0); # provided by browser my $temphtml; $onload="document.form1.name.focus();"; $template =~ s/\@title\@/Edit Stock Categories/sgi; $temphtml = "
    "; $temphtml .= "STOCK TYPE:
    "; foreach my $acctype (sort keys %{ $stocktypes_breakdown{$database} }) { $temphtml .= "($account_types{$acctype}: "; foreach (sort {$stocktypes{$database}{$a} cmp $stocktypes{$database}{$b}} keys %{ $stocktypes_breakdown{$database}{$acctype} } ) { $temphtml .= "[".($tempdb{stocktype} == $_ ? " $stocktypes{$database}{$_} " : "$stocktypes{$database}{$_}")."]"; } $temphtml .= ")
    "; } $temphtml .= "

    "; #/## SUPPLIER EDIT COMMANDS if (($R::command eq "Add Data" and $R::name)) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("INSERT INTO stockcats (shop_id,name,stocktype_id) values ($shop{id},?,$tempdb{stocktype});") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA ADDED."; retreive_stockcats($database, $shop{id}); } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE stockcats SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "ITEM DELETED."; retreive_stockcats($database, $shop{id}); } elsif ($R::command eq "Modify Data" and $R::name) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("UPDATE stockcats SET name=?, f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA MODIFIED."; retreive_stockcats($database, $shop{id}); } #/## /COMMANDS #/ DRAW TABLE $temphtml .= $table{start}; $temphtml .= "
    "; $temphtml .= ""; $temphtml .= ""; my %parents; $results = $dbh->prepare("SELECT * FROM stockcats WHERE stocktype_id=$tempdb{stocktype} and shop_id = $shop{id} and f_status<100 and parent_id = 0 ORDER BY name ASC;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= "
    Jump to Stock Items
    "; $temphtml .= ""; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "Edit Stock Bins") { my $temphtml; $onload="document.form1.name.focus();"; $template =~ s/\@title\@/Edit Stock Bins/sgi; $temphtml = "
    "; #/## SUPPLIER EDIT COMMANDS if (($R::command eq "Add Data" and $R::name)) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("INSERT INTO stockbins (name) values (?);") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA ADDED."; retreive_bins($database, $shop{id}); } elsif ($R::command eq "delete") { my $results = $dbh->prepare("delete from stockbins WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "ITEM DELETED."; retreive_bins($database, $shop{id}); } elsif ($R::command eq "Modify Data" and $R::name) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("UPDATE stockbins SET name=? WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA MODIFIED."; retreive_bins($database, $shop{id}); } #/## /COMMANDS #/ DRAW TABLE $temphtml .= $table{start}; $temphtml .= "
    "; $temphtml .= ""; $temphtml .= ""; $results = $dbh->prepare("SELECT * FROM stockbins ORDER BY id DESC;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= "
    Jump to Stock Items
    "; $temphtml .= ""; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "Edit Depts") { my $temphtml; $onload="document.form1.name.focus();"; $template =~ s/\@title\@/Edit Departments/sgi; $temphtml = "
    "; #/## SUPPLIER EDIT COMMANDS if (($R::command eq "Add Data" and $R::name)) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("INSERT INTO stockdepts (shop_id,name) values ($shop{id},?);") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA ADDED."; } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE stockdepts SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "ITEM DELETED."; } elsif ($R::command eq "Modify Data" and $R::name) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("UPDATE stockdepts SET name=?, f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA MODIFIED."; } #/## /COMMANDS #/ DRAW TABLE $temphtml .= $table{start}; $temphtml .= "
    "; $temphtml .= ""; $temphtml .= ""; $results = $dbh->prepare("SELECT * FROM stockdepts WHERE shop_id = $shop{id} and f_status<100 ORDER BY id DESC;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= ""; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "Edit Stock Types") { my $temphtml; $onload="document.form1.name.focus();"; $template =~ s/\@title\@/Edit Stock Types/sgi; $temphtml = "
    "; #/## SUPPLIER EDIT COMMANDS if (($R::command eq "Add Data" and $R::name)) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("INSERT INTO stocktypes (shop_id,name,description,account_type) values ($shop{id},?,?,?);") or die $dbh->errstr(); $results->execute($R::name,$R::description,$R::account_type) or die $results->errstr(); $mess = "DATA ADDED."; retreive_stocktypes($database, $shop{id}); } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE stocktypes SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "ITEM DELETED."; retreive_stocktypes($database, $shop{id}); } elsif ($R::command eq "Modify Data" and $R::name) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("UPDATE stocktypes SET name=?, description=?, account_type=?, f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::name,$R::description,$R::account_type) or die $results->errstr(); $mess = "DATA MODIFIED."; retreive_stocktypes($database, $shop{id}); } #/## /COMMANDS #/ DRAW TABLE $temphtml .= $table{start}; $temphtml .= "
    "; $temphtml .= ""; $temphtml .= ""; $results = $dbh->prepare("SELECT * FROM stocktypes WHERE shop_id = $shop{id} and f_status<100 ORDER BY account_type,name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= "
    Jump to Stock Items
    "; $temphtml .= ""; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "Edit Suppliers") { my $temphtml; $onload="document.form1.name.focus();"; $template =~ s/\@title\@/Edit Suppliers/sgi; $temphtml = "
    "; #/## SUPPLIER EDIT COMMANDS if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("INSERT INTO suppliers (shop_id,name, note) values ($shop{id},?,'$R::note');") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA ADDED."; } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE suppliers SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "SUPPLIER DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("UPDATE suppliers SET name=?, note='$R::note', f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA MODIFIED."; } #/## /COMMANDS #/ DRAW TABLE SUPPLIER $temphtml .= $table{start}; $temphtml .= "
    "; $temphtml .= ""; $temphtml .= ""; $results = $dbh->prepare("SELECT * FROM suppliers WHERE shop_id = $shop{id} and f_status<100 ORDER BY id DESC;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= "
    Jump to Stock Items
    "; if ($R::fpurchases) { if ($R::fpurchases == 1) { $temphtml .= "
    Back to Purchases
    "; } else {#/ back to opening stock $temphtml .= "
    Back to Opening Stock
    "; } } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } #/ end supplier editor elsif ($socketflag == 1 and $R::action eq "Edit Wholesalers") { my $temphtml; $onload="document.form1.name.focus();"; $template =~ s/\@title\@/Edit Wholesalers/sgi; $temphtml = "
    "; #/## SUPPLIER EDIT COMMANDS if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("INSERT INTO wholesalers (name, note) values (?,'$R::note');") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA ADDED."; } elsif ($R::command eq "delete") { my $results = $dbh->prepare("DELETE FROM wholesalers WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "SUPPLIER DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { $R::name=~ tr/a-z/A-Z/; my $results = $dbh->prepare("UPDATE wholesalers SET name=?, note='$R::note' WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA MODIFIED."; } #/## /COMMANDS #/ DRAW TABLE wholesalers $temphtml .= $table{start}; $temphtml .= "
    "; $temphtml .= ""; $temphtml .= ""; $results = $dbh->prepare("SELECT * FROM wholesalers WHERE f_status<100 ORDER BY id DESC;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= ""; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } #/ end wholesaler editor elsif ($socketflag == 1 and $R::action eq "popup") { my $temphtml; my %calc; #if ($R::subaction eq "tillinvoice") if ($R::subaction eq "purchases") { my $temphtml; $template =~ s/\@title\@/Purchases Details/sgi; $temphtml = "
    "; $temphtml .= "Supplier: $R::name
    Invoice $R::invoice
    "; my $supplier_criteria; if ($R::supplier) { $supplier_criteria = " and supplier_id = '$R::supplier' "; } else { $supplier_criteria = " and wholesaler_id = '$R::wholesaler' "; } $results = $dbh->prepare("select distinct DATE_FORMAT(date, '%e %M %Y') date from purchases where invoice='$R::invoice' #and date >= '$R::startdate' and supplier_id='$R::supplier' #and date <= '$R::enddate' and shop_id=$shop{id} and f_status < 100 order by date desc limit 1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $temphtml .= " Invoice date: $ref->{date}"; } $temphtml .= "

    "; $temphtml .= $table{start}; $temphtml .= "
    "; my %stockitems; $results = $dbh->prepare(" SELECT si.id,concat(sc.name,' - ',si.name) name, bin, units FROM stockitems si LEFT JOIN stockcats sc ON sc.id = si.stockcats_id WHERE si.f_status<100 and si.shop_id=$shop{id} and sc.f_status<100 and sc.shop_id=$shop{id}; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockitems{$ref->{id}} = $ref->{name}." ($units{$ref->{units}})"; } my $total = 0; $results = $dbh->prepare(" select qty,price, qty*price total, description, stockitems_id,othertype from purchases where invoice='$R::invoice' #and date >= '$R::startdate' #and date <= '$R::enddate' and supplier_id='$R::supplier' and shop_id = $shop{id} and f_status < 100 $supplier_criteria;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($ref->{othertype} != 0 and ! $ref->{stockitems_id}) { $temphtml .= " "; $total += $ref->{total}; } else { $temphtml .= " "; $total += $ref->{total}; } } $temphtml .= ""; $temphtml .= $table{end}; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } if ($R::subaction eq "budetails") { my $temphtml; $R::budmonth ++; my $byear = $R::byear; $template =~ s/\@title\@/Expense Details/sgi; $temphtml = "
    "; $temphtml .= "Budget item $R::buditem ($months{$R::budmonth})

    "; my $total; $temphtml .= $table{start}; $temphtml .= "
    "; #~ ((YEAR(date)=$byear and MONTH(date) >$bstartmonth) #~ or #~ (YEAR(date)=$byear+1 and MONTH(date) <=$bstartmonth)) #~ and $results = $dbh->prepare("select p.price, p.org_qty, p.org_qty*p.price value, p.stockitems_id, p.description, p.invoice, IF(s.name is not null,s.name,'PETTY CASH') supplier, DATE_FORMAT(p.date, '%e %M %Y') date, p.cnote from purchases p left join suppliers s on s.id = p.supplier_id where MONTH(p.date) = '$R::budmonth' and p.f_status<100 and p.othertype = $R::budid and p.shop_id=$shop{id} order by p.date ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($ref->{cnote} == 1) { $ref->{value} = $ref->{value} * -1; $ref->{org_qty} = $ref->{org_qty} * -1; $ref->{price} = $ref->{price} * -1; } $total += $ref->{value}; $temphtml .= ""; } $temphtml .= ""; $temphtml .= $table{end}; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } if ($R::subaction eq "invoice") { my $temphtml; $template =~ s/\@title\@/Invoice Details $R::invoice/sgi; $temphtml = "
    "; $results = $dbh->prepare("select stamp from tillinvoices where id = '$R::invoice';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $temphtml .= "Time stamp: $ref->{stamp}
    "; my $total; $temphtml .= $table{start}; $temphtml .= "
    "; $results = $dbh->prepare("select name, sum(qty) qty, price uprice, discount, yield, sum(qty*price) total from tillordersdetails where shop_id=$shop{id} and invoice = '$R::invoice' group by name,price,discount order by total desc; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($ref->{yield} > 0) { $ref->{qty} = $ref->{yield}; $ref->{total} = $ref->{uprice} * $ref->{qty}; } $total += ( $ref->{total} - $ref->{discount} * $ref->{qty} ); $temphtml .= ""; } $temphtml .= ""; $temphtml .= $table{end}; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } if ($R::subaction eq "slipfeedback") { my $temphtml; $template =~ s/\@title\@/Feedback Forms Update/sgi; $results = $dbh->prepare("select name from waitron where id = $R::waitron_id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $waitron_name = $ref->{name}; my $lastcashuptillid; $results = $dbh->prepare(" select last_tillid from dcashitems where last_tillid < '$R::last_tillid' and waitron_id=$R::waitron_id and f_status<101 and shop_id=$shop{id} order by id desc limit 1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $previouscashuptillid = $ref->{last_tillid}*1; $lastcashuptillid = $R::last_tillid; #/till orders details lookup zone defined #/fetch all invoices printed and not voided by this waitron $results = $dbh->prepare(" select distinct inv.id invoicenr from tillordersdetails ttods, tillinvoices inv where inv.shop_id = $shop{id} and ttods.shop_id = $shop{id} and inv.waitron_id=$R::waitron_id and ttods.waitron_id=$R::waitron_id and (inv.voided is NULL or inv.voided=0) and ttods.invoice = inv.id and ttods.id <= '$lastcashuptillid' and ttods.id > '$previouscashuptillid' and ttods.f_status < 100 and inv.f_status < 100 group by inv.id ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); my @invoices = (); my $min_inv = 0; my $max_inv = 0; while ( $ref = $results->fetchrow_hashref() ) { push @invoices, $ref->{invoicenr}; $min_inv = $ref->{invoicenr} if ($ref->{invoicenr} < $min_inv); $max_inv = $ref->{invoicenr} if ($ref->{invoicenr} > $max_inv); } my $q_waitron_name = "$waitron_name"; my $q_invoice_id = ""; my $qnadata = slurpfile($qnafile); my $qnaprint = $qnadata; my $qna_id; my %questionz; #/qna init $qnaprint =~ /\[formid:(\d+)\]/sgi; $qna_id = $1; $qnaprint =~ s/\[formid:($qna_id)\]//gsi; $qnaprint =~ s/\[waitron\]/$q_waitron_name/gsi; $qnaprint =~ s/\[invoice\]/$q_invoice_id/gsi; $qnaprint =~ s/\[dwidth\]//gsi; $qnaprint =~ s/\[dheight\]//gsi; $qnaprint =~ s/\[normal\]//gsi; $qnaprint =~ s/\[underline\]//gsi; #/qna question fetch my @breaked = split (/\n|\r/, $qnaprint); $_ =~ s/\n|\r// foreach @breaked; my $cnt1 = 1; my $cnt2 = 1; foreach my $line (@breaked) { if ($line =~ /(\[qp\])/) { $questionz{questions}{$cnt1} = $'; $cnt1++; $cnt2 = 1; } elsif ($line =~ m/(\[q\])/gsi) { my $b = $line; while ($b =~ m/(\[q\])([^\[]*)/gsi) { $questionz{answers}{$cnt1-1}{$cnt2} = $2; $cnt2++; } #~ $questionz{answers}{$cnt1-1}{$cnt2} = $'."x1"; #~ $cnt2++; } } #/printer #/update command surfing if ($R::command eq "Save Selection") { my %existing; $results = $dbh->prepare(" select * from slipfeedback where waitron_id = '$R::waitron_id' and till_invoice >= $min_inv and till_invoice <= $max_inv and shop_id = $shop{id} and f_status < 100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ( $ref = $results->fetchrow_hashref() ) { $existing{$ref->{till_invoice}}{$ref->{question_id}}{$ref->{answer_id}} = 1; } my %submitted; my @pars = $q->param; #/save if unsaved foreach my $par (@pars) { if ($par =~ /in_(\d+)_qa_(\d+)/) { my $inv = $1; my $ques = $2; my $ans = $q->param($par); #/print "$inv,$ques,$ans "; if (exists $existing{$inv}{$ques} and $ans > 0) { $results = $dbh->prepare("update slipfeedback set answer_id=$ans where shop_id=$shop{id} and waitron_id=$R::waitron_id and till_invoice=$inv and question_id=$ques;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } elsif (exists $existing{$inv}{$ques} and $ans == 0) { $results = $dbh->prepare("update slipfeedback set f_status=101 where shop_id=$shop{id} and waitron_id=$R::waitron_id and till_invoice=$inv and question_id=$ques;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } elsif ((! exists $existing{$inv}{$ques}) and $ans > 0 ) { $results = $dbh->prepare("insert into slipfeedback (waitron_id,till_invoice,question_id,answer_id,shop_id,f_status,form_id) values ('$R::waitron_id','$inv','$ques','$ans','$shop{id}','1','$qna_id');") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } $existing{$inv}{$ques}{$ans} = 1; #/print "$1 $2 $ans."; } } } #/query existing data; my %existingdata; $results = $dbh->prepare(" select * from slipfeedback where waitron_id = '$R::waitron_id' and till_invoice >= $min_inv and till_invoice <= $max_inv and shop_id = $shop{id} and f_status < 100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ( $ref = $results->fetchrow_hashref() ) { $existingdata{$ref->{till_invoice}}{$ref->{question_id}}{$ref->{answer_id}} = 1; } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; #/ Month Cell $temphtml .= ""; $temphtml .= "
    $mnames{$month}"; $temphtml .= "
    "; $temphtml .= ""; #/week days table $temphtml .= "" foreach (sort {$a<=>$b} keys %dnames); #/day titles $temphtml .= ""; $temphtml .= ""; my $shiftday = dayofweek(1,$month,$year) - 1; $temphtml .= ""x$shiftday; for my $day (1..( lastday($month+1,$year))) { if (($day+$shiftday) % 7 == 1) {$temphtml .= ""} $temphtml .= ""; my %stockitemsinfo; $results = $dbh->prepare("select si.sku,sc.name cat, si.name, si.id, si.units,si.type from stockitems si LEFT JOIN stockcats sc ON sc.id = si.stockcats_id where si.type='$tempdb{stocktype}' and si.stockitem = 1 and si.f_status <100 and si.shop_id='$shop{id}' and sc.f_status <100 and sc.shop_id=si.shop_id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockitemsinfo{$ref->{id}}{cat} = $ref->{cat}; $stockitemsinfo{$ref->{id}}{name} = $ref->{name}; $stockitemsinfo{$ref->{id}}{units} = $ref->{units}; $stockitemsinfo{$ref->{id}}{type} = $ref->{type}; } #MainLoop $results = $dbh->prepare(" select stockissue.lockflag lockflag, stockissue.id id, stockissue.stockitems_id stockitems_id, stockissue.qty qty, stockcats.name cat, stockitems.sku, stockitems.name from stockissue, stockitems left join stockcats on stockcats.id=stockitems.stockcats_id where stockissue.shop_id=$shop{id} and stockissue.f_status <100 and stockitems.shop_id=$shop{id} and stockitems.f_status <100 and stockitems.stockitem = 1 and stockitems.type='$tempdb{stocktype}' and stockissue.stockitems_id=stockitems.id and stockissue.date = '$sqldate{year}-$sqldate{month}-$sqldate{day}' and stockissue.direction = $R::direction order by stockissue.lockflag, stockitems.sku, stockcats.name, stockitems.name ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); my $evening_records = $results->rows; while ($ref = $results->fetchrow_hashref()) { my $linecolor = "#FFFFFF"; my $editflag = 1; if ($R::direction == 2) { $linecolor = "#00A3FB"; } elsif ($R::direction == 1 and $ref->{lockflag} == 0) { $linecolor = "#FBBC00"; $editflag = 1; } elsif ($R::direction == 1 and $ref->{lockflag} == 1) { $linecolor = "#F5FF3C"; $editflag = 0; } elsif ($R::direction == 1 and $ref->{lockflag} == 2) { $linecolor = "#8AFF3C"; $editflag = 0; } if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; } else { $onload="document.form1.qty.focus();"; my %ssel = ($ref->{stockitems_id} => 'selected'); $temphtml .= ""; $temphtml .= ""; } } if ($R::command ne "modify" and $finalflag and $finalizedflag) { if ($R::bulk == 1) { #THEORETICAL STOCK ON HAND my $stocktype = $tempdb{stocktype}; #/get all stock in memory: name, bin, units my %stockdetails; $results = $dbh->prepare(" SELECT si.sku,si.id,sc.name cat, si.name name, bin, units,cost FROM stockitems si LEFT JOIN stockcats sc ON sc.id = si.stockcats_id WHERE si.f_status<100 and si.shop_id=$shop{id} and sc.f_status<100 and sc.shop_id=$shop{id} and si.type=$stocktype; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockdetails{name}{$ref->{id}} = $ref->{name}; $stockdetails{bin}{$ref->{id}} = $ref->{bin}; $stockdetails{units}{$ref->{id}} = $ref->{units}; $stockdetails{cost}{$ref->{id}} = $ref->{cost}; $stockdetails{sku}{$ref->{id}} = $ref->{sku}; $stockdetails{cat}{$ref->{id}} = $ref->{cat} } #/determine last pid for the stocktype $results = $dbh->prepare(" select stockissue.date date,stockissue.direction direction from stockitems,stockissue where stockitems.id = stockissue.stockitems_id and stockitems.type=$stocktype order by date desc limit 1; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $lastvdate = $ref->{date}; my $lastvdirection = $ref->{direction}; my %last_purchases; $results = $dbh->prepare(" select si.id id, si.name name, si.units units, si.bin bin, sum(pu.qty) qty, sum(pu.org_price) totalprice, sum(pu.org_price)/sum(pu.qty) uprice from purchases pu,stockitems si where si.f_status<100 and pu.f_status<100 and si.shop_id=$shop{id} and pu.shop_id=si.shop_id and si.id=pu.stockitems_id and si.type=$stocktype and pu.date>='$lastvdate' #/cs:last_pid and (pu.cnote != 1 or pu.cnote is NULL or pu.cnote = 0) group by si.id order by name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_purchases{$ref->{id}}{qty} = $ref->{qty}; } #/last closing stock qty and value my %last_closingstock; $results = $dbh->prepare(" select sum(stockissue.qty) qty,stockissue.stockitems_id from stockitems,stockissue where stockissue.date='$lastvdate' and stockissue.direction = '$lastvdirection' and stockitems.id = stockissue.stockitems_id and stockitems.type=$stocktype and stockissue.f_status < 100 group by stockissue.stockitems_id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_closingstock{$ref->{stockitems_id}}{qty} = $ref->{qty}; } #/last credit notes - since last_pid my %last_creditnotes; $results = $dbh->prepare("select si.id id, si.name name, sum(pu.qty) qty, sum(pu.org_price) totalprice, sum(pu.org_price)/sum(pu.qty) uprice from purchases pu,stockitems si where pu.f_status<100 and si.f_status<100 and si.shop_id=$shop{id} and pu.shop_id=si.shop_id and si.id=pu.stockitems_id and si.type=$stocktype and pu.date>='$lastvdate' #/cs:last_pid and pu.cnote = 1 group by si.id order by name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_creditnotes{$ref->{id}}{qty} = $ref->{qty}; $last_creditnotes{$ref->{id}}{value} = $ref->{totalprice}; } #/calculate the availables; my %availables = (); foreach my $id (keys %{$stockdetails{name}}) { my $available_qty; $available_qty = $last_closingstock{$id}{qty} + ($last_purchases{$id}{qty} - $last_creditnotes{$id}{qty}); next if ($available_qty <= 0 and $show_noqty_stock == -1); $availables{$id} = $available_qty || 0; } #THEORY #GRAND RETREIVAL #retreive ingredient details my %idetails; $results = $dbh->prepare("select id,name,stockitems_id,units from ritems;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ $idetails{$ref->{id}}{stockitems_id} = $ref->{stockitems_id}; $idetails{$ref->{id}}{units} = $ref->{units}; } my %latestyields; $results = $dbh->prepare(" select id ritem_id, yield from ritems;" ) or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $idetails{$ref->{ritem_id}}{yield} = $ref->{yield}; } my %stockuse; my %ingredientuse; my %pluuse; my %returns; #print "'$last_date 06:00:00' ST: $tempdb{stocktype}"; #TO RETREIVE TOTAL PLU QTYs (based on QTY or YIELD column); my %onetoone; $results = $dbh->prepare(" select menu.id pluid, inv.isrefund, menu.stockid stockid, inv.voided voided, sum(qty) totalqty from tillordersdetails ttod, tillorders tto, menu, tillinvoices inv, tilltableops tabops, tilltables where ttod.f_status < 101 and tto.f_status <101 and ttod.stamp >= '$lastvdate 06:00:00' #and menu.type=1 and tabops.id = tto.tableops_id and tilltables.id = tabops.table_id and ttod.orders_id = tto.id and tto.confirm_status=3 and menu.type = '$tempdb{stocktype}' and ttod.menusource = 1 and menu.id = ttod.plu and inv.id = ttod.invoice and (inv.voided is NULL or inv.voided = 2 or inv.voided = 0) group by menu.id, inv.voided, inv.isrefund;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ if ( $ref->{isrefund} == 1 ) { $pluuse{$ref->{pluid}} += $ref->{totalqty}; } else { $pluuse{$ref->{pluid}} += $ref->{totalqty} if ($ref->{voided} != 2); $returns{$ref->{pluid}} += $ref->{totalqty} if ($ref->{voided} == 2); } $onetoone{$ref->{pluid}} = $ref->{stockid}; } # loop the PLUs in the following: foreach my $plu (keys %pluuse) { $results = $dbh->prepare(" SELECT rn.name name, rn.id id, mr.qty qty, ry.yield totaly from recipe_names rn, menu_recipes mr, recipe_yields ry where ry.recipe_id = rn.id and ry.yield_unit = mr.recipe_units and mr.menu_id=$plu and rn.id=mr.recipe_id ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ my %usage = &recipeingredients($ref->{id},$ref->{totaly}/$ref->{qty}, {dbh => $dbh} ); foreach my $ingred (keys %usage) { #print "|$idetails{$ingred}{stockitems_id} -- $stockuse{$idetails{$ingred}{stockitems_id}}"; # THE LiNK $stockuse{$idetails{$ingred}{stockitems_id}} += $pluuse{$plu}*$usage{$ingred}* #usage in the PLU ((100+(100-$idetails{$ingred}{yield}))/100)* #yield towards stockitem ${$unitalias{ $idetails{$ingred}{units} } }[1]; } } #deal with onetoones $stockuse{$onetoone{$plu}} += $pluuse{$plu} if {$onetoone{$plu} > 0}; } #foreach PLU #END $temphtml =qq~ ~; my %items; $results = $dbh->prepare(" select stockissue.date, concat(stockcats.name,' - ',stockitems.name), stockissue.stockitems_id, stockitems.units from stockissue, stockcats,stockitems where stockitems.id = stockissue.stockitems_id and stockcats.id = stockitems.stockcats_id and stockitems.type = ? and stockissue.date = ( select date from stockissue,stockitems where stockissue.stockitems_id = stockitems.id and stockitems.type = ? order by date desc limit 1 ) group by stockitems.id ;") or die $dbh->errstr(); $results->execute($tempdb{stocktype},$tempdb{stocktype}) or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $items{$ref->{stockitems_id}} = 1; } $results = $dbh->prepare(" select purchases.date, stockitems.name, stockitems.id, stockitems.units from purchases, stockitems where purchases.stockitems_id = stockitems.id and stockitems.type = ? and purchases.date >= ( select date from stockissue,stockitems where stockissue.stockitems_id = stockitems.id and stockitems.type = ? order by date desc limit 1 ) group by stockitems.id ;") or die $dbh->errstr(); $results->execute($tempdb{stocktype},$tempdb{stocktype}) or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $items{$ref->{id}} = 1; } $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; $temphtml .= ""; } } $temphtml .= $table{end}; $temphtml .= "
    FINALIZING NOT DONE FOR DATE: $notfinalizeddate
    " if (! $finalizedflag); $results = $dbh->prepare(" select count(id) counter from stockprep where shop_id=$shop{id} and f_status<100 and date='$sqldate{year}-$sqldate{month}-$sqldate{day}'; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $evening_records += $ref->{counter}; $temphtml .= "
    PREP SHEET CONTAINS $ref->{counter} RECORDS. GO TO PREP SHEET
    "; if (! $R::undo) { $temphtml .= "
    $dnames{$_}
    prepare(" delete from stockissue where date='$undodate' and direction = 1 and lockflag = 2;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $results = $dbh->prepare(" insert into unlocked (section,name,reason,date,datestamp) values (3,?,?,'$undodate',current_date);") or die $dbh->errstr(); $results->execute($R::name,"TH.STOCK: $stocktypes{$database}{$tempdb{stocktype}} \n REASON: \n".$R::reason) or die $results->errstr(); } $onload="document.form1.input1.focus();"; my $temphtml; #ajaxedithtml $temphtml .= qq~ ~; $temphtml .= " View issues calendar.
    "; #/calendar JS $temphtml .= qq~ ~; #autocomplete $temphtml .= qq~ ~; #/retreive permanent stages $tempdb{stocktype} = $R::stocktype if ($R::stocktype); #/no permanent stages yet - init if (! $tempdb{stocktype}) {$tempdb{stocktype}=1}; #my %plustocktypes = (1=>'1,2,3',2=>'4'); #query helper $template =~ s/\@title\@/Edit Stock Issue - $stocktypes{$database}{$tempdb{stocktype}}/sgi; $temphtml .= "
    "; $temphtml .= "STOCK TYPE:
    "; my $acctype = 1; $temphtml .= "($account_types{$acctype}: "; foreach (sort {$stocktypes{$database}{$a} cmp $stocktypes{$database}{$b}} keys %{ $stocktypes_breakdown{$database}{$acctype} } ) { $temphtml .= "[".($tempdb{stocktype} == $_ ? " $stocktypes{$database}{$_} " : "$stocktypes{$database}{$_}")."]"; } $temphtml .= ")
    "; $temphtml .= "

    "; if ($R::date and $R::direction) { #finalize here: if ($R::finalize == 1) { #retreive preped stock first my %oldsqldate = dateforsql($R::today); my $reportdate = "$oldsqldate{year}-$oldsqldate{month}-$oldsqldate{day}"; my %latestyields; my %idetails; $results = $dbh->prepare("select id,name,stockitems_id,units from ritems;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ $idetails{$ref->{id}}{stockitems_id} = $ref->{stockitems_id}; $idetails{$ref->{id}}{units} = $ref->{units}; } $results = $dbh->prepare(" select id ritem_id, yield from ritems;" ) or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $idetails{$ref->{ritem_id}}{yield} = $ref->{yield}; } my %closingpreps; $results = $dbh->prepare("select sum(qty) qty, ingredient_id from stockprep where date='$reportdate' and ingredient_id > 0 and ingredient_id is not null and shop_id=$shop{id} and f_status<100 group by ingredient_id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $closingpreps{ $idetails{$ref->{ingredient_id}}{stockitems_id} } += $ref->{qty}* ((100+(100-$idetails{$ref->{ingredient_id}}{yield}))/100)* #yield towards stockitem ${$unitalias{ $idetails{$ref->{ingredient_id}}{units} } }[1];; } #recipes prep $results = $dbh->prepare(" select sum(sp.qty) qty, sp.recipe_id recipe_id, sp.recipe_units recipe_units, ry.yield yield from stockprep sp, recipe_yields ry where sp.recipe_units = ry.yield_unit and sp.recipe_id=ry.recipe_id and sp.date='$reportdate' and sp.recipe_id > 0 and sp.recipe_id is not null and sp.shop_id=$shop{id} and sp.f_status<100 group by sp.recipe_id,sp.recipe_units; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ my %usage = &recipeingredients($ref->{recipe_id}, $ref->{yield}, {dbh => $dbh} ); foreach my $ingred (keys %usage) { $closingpreps{$idetails{$ingred}{stockitems_id}} += $ref->{qty}*$usage{$ingred}* ((100+(100-$idetails{$ingred}{yield}))/100)* #yield towards stockitem ${$unitalias{ $idetails{$ingred}{units} } }[1]; } } my $insertdate = "$sqldate{year}-$sqldate{month}-$sqldate{day}"; $results = $dbh->prepare(" select count(*) counter from stockissue, stockitems where stockitems.id = stockissue.stockitems_id and stockitems.type='$tempdb{stocktype}' and stockissue.date = '$insertdate' and stockissue.f_status < 100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if (! $ref->{counter}) { foreach my $id (sort {$a <=> $b} keys %closingpreps) { $results = $dbh->prepare(" insert into stockissue (date,stockitems_id,direction,qty,shop_id,lockflag) values ('$insertdate',$id,1,$closingpreps{$id},$shop{id},1); ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #print "
    #insert into stockissue (date,stockitems_id,direction,qty,shop_id,lockflag) #values #('$insertdate',$id,1,$closingpreps{$id},$shop{id},1); #"; } $results = $dbh->prepare(" INSERT into stockissue (stockitems_id,qty,shop_id,date,direction,lockflag) SELECT stockitems_id,sum(qty),$shop{id}, '$insertdate', 1, 2 from stockissue where date='$reportdate' and direction=2 and f_status<100 and shop_id=$shop{id} group by stockitems_id; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } else { $temphtml .= "
    ERROR FINALIZING FOR $insertdate
    "; } # todo - if allowed by mode - insert-update from the SQL script for evening to morning issue } $results = $dbh->prepare("select stockissue.* from stockissue, stockitems si where si.id = stockissue.stockitems_id and si.type = ? and stockissue.f_status<100 order by date desc limit 1 ;") or die $dbh->errstr(); $results->execute($tempdb{stocktype}) or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $undoflag; $undoflag = 1 if ($ref->{date} eq "$sqldate{year}-$sqldate{month}-$sqldate{day}" and $ref->{direction} == 1 and $ref->{lockflag} == 2 ); $results = $dbh->prepare("select count(stockissue.id) counter from stockissue, stockitems si where si.id = stockissue.stockitems_id and si.type = ? and stockissue.f_status<100 and date>'$sqldate{year}-$sqldate{month}-$sqldate{day}' ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); #ISSUE my $finalflag;# flag whether we are not trying to edit historical info # if YES we are not editing history $finalflag = 1 if (! $ref->{counter}); my $finalizedflag = 0; my $notfinalizeddate; #check whether there is no stock outstanding if ($finalflag == 1) { #this is the last day #verify only prep $results = $dbh->prepare(" select distinct date from stockprep where date < '$sqldate{year}-$sqldate{month}-$sqldate{day}' and shop_id=$shop{id} and f_status < 100 order by date desc limit 1; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $lastprepdate = $ref->{date}; $notfinalizeddate = $lastprepdate; if ($lastprepdate ne '') { $results = $dbh->prepare(" select count(id) counter from stockissue where shop_id=$shop{id} and lockflag=1 and f_status <100 and date > '$lastprepdate' ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{counter}) { $finalizedflag = 1; } else { #prep not finalized! $finalizedflag = -1; } } else { #no prep for finalize $finalizedflag = 1; # no previous records found } #verify for finalization if closing stock #is also finalized as opening for next day if ($copycstock) { #mode = yes $results = $dbh->prepare(" select distinct date from stockissue where date < '$sqldate{year}-$sqldate{month}-$sqldate{day}' and direction = 2 and shop_id=$shop{id} and f_status < 100 order by date desc limit 1; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $lastcstockdate = $ref->{date}; if ($lastcstockdate ne '') { $results = $dbh->prepare(" select count(id) counter from stockissue where shop_id=$shop{id} and lockflag=2 and f_status <100 and date > '$lastcstockdate' ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{counter}) { $finalizedflag = 3 if ($finalizedflag != -1); } else { $finalizedflag = -2; } } } } #command if ($R::command eq "Add" and $R::stockitems_id and $R::qty ne '') { $results = $dbh->prepare(" insert into stockissue (direction,shop_id,date,stockitems_id,qty) values ($R::direction,$shop{id},'$sqldate{year}-$sqldate{month}-$sqldate{day}',$R::stockitems_id,$R::qty) ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #$ref = $results->fetchrow_hashref(); $temphtml .= "Item added
    "; } elsif ($R::command eq "Save All") { my @pars = $q->param; #/save if unsaved foreach (@pars) { if ($_ =~ /^(st_)(\d+)/) { my $item = $2; my $qty = $q->param("$_"); if ($item > 0 and $qty ne '') { $results = $dbh->prepare(" insert into stockissue (direction,shop_id,date,stockitems_id,qty) values ($R::direction,$shop{id},'$sqldate{year}-$sqldate{month}-$sqldate{day}',$item,$qty) ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } } } $temphtml .= "Items added
    "; } elsif ($R::command eq "Modify Record" and $R::itemid and $R::qty ne '') { $results = $dbh->prepare(" update stockissue set qty='$R::qty' where id = '$R::itemid'; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $temphtml .= "Item updated
    "; } elsif ($R::command eq "Delete" and $R::itemid) { $results = $dbh->prepare("delete from stockissue where id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $temphtml .= "Item deleted
    "; } $temphtml .= $table{start}; $temphtml .= "
    SKU CATEGORY STOCK ITEM QTY UNIT COMMAND
    $ref->{sku} $ref->{cat} $ref->{name} {id}."\">$ref->{qty} $units{ $stockitemsinfo{$ref->{stockitems_id}}{units} } {id}."\">"; $temphtml .= qq~ $icons{d} ~ if ($editflag and $finalflag and $finalizedflag); $temphtml .= "
    $ref->{sku} $ref->{cat} $ref->{name} $issuetypes{$R::direction}
    Qty {qty}\" name=qty>
    -
    "; foreach my $id ( sort {$stockitemsinfo{$a}{cat} cmp $stockitemsinfo{$b}{cat}} sort {$stockitemsinfo{$a}{name} cmp $stockitemsinfo{$b}{name}} keys %items) { $temphtml .= ""; } $temphtml .= ""; $temphtml .= "
    Stock ItemTheoretical
    Stock on Hand
    Closing StockVariance
    $stockitemsinfo{$id}{cat} - $stockitemsinfo{$id}{name}, $units{$stockitemsinfo{$id}{units}} ".(($availables{$id} - $stockuse{$id}) * 1)." N/a
    quickfind» find next»
    Stock item
    $issuetypes{$R::direction}
    Qty
    -
    quickfind» find next»
    Stock item
    $issuetypes{$R::direction}
    Qty
    Bulk Add Sheet | Import DigiTot | Import DigiTag | Import CipherLab | Par Levels
    Undo This Closing Stock
    " if ($undoflag and $R::direction == 1); } else { $temphtml .= "
    Please sign the undo:

    Name: Reason:
    "; } $temphtml .= ""; #### QUERY WHETHER WE CAN DO A FINALIZE if ($R::direction == 2 and $finalflag and $evening_records) { my $tomorrow; $results = $dbh->prepare("select DATE_FORMAT( DATE_ADD('$sqldate{year}-$sqldate{month}-$sqldate{day}',INTERVAL 1 DAY) , '%d/%m/%Y') tomorrow ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $tomorrow=$ref->{tomorrow}; $temphtml .= "
    FINALIZE AND THEN OPEN $tomorrow "; } } else { $temphtml .= " $R::action: PLEASE SELECT DATE AND SHEET BELOW!"; } my %dsel = ("$R::direction" => "selected"); $temphtml .= ""; $temphtml .= ""; $temphtml .= "

    OPTIONS: STOCK TYPE: $stocktypes{$database}{$tempdb{stocktype}} | Select Day: $icons{cal} | Select Sheet:
    "; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } # Edit Stock Issue elsif ($socketflag == 1 and $R::action eq "Edit Prep Issue") { $onload="document.form1.input1.focus();"; my %sqldate = dateforsql($R::date); my $temphtml; $temphtml .= "
    GO TO: $date Morning Issue | $date Evening Issue"; $R::mode=1 if (! $R::mode); $temphtml .= "

    SELECT MODE: ".($R::mode==1 ? "COMPONENTS" : "COMPONENTS")." or ".($R::mode==2 ? "PRODUCTS" : "PRODUCTS")."

    "; $results = $dbh->prepare("select count(id) counter from stockissue where shop_id=$shop{id} and f_status<100 and date>'$sqldate{year}-$sqldate{month}-$sqldate{day}' ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); #PREP my $finalflag; # flag whether we are not trying to edit historical info # if YES we are not editing history $finalflag = 1 if (! $ref->{counter}); #/calendar JS $temphtml .= qq~ ~; #autocomplete $temphtml .= qq~ ~; $template =~ s/\@title\@/Edit Prep Items - $stocktypes{$database}{$tempdb{stocktype}}/sgi; $temphtml .= "
    "; if ($R::date) { my %stockitem; if ($R::mode == 1) { #command if ($R::command eq "Add" and $R::ingredient_id and $R::qty) { $results = $dbh->prepare(" insert into stockprep (shop_id,date,ingredient_id,qty) values ($shop{id},'$sqldate{year}-$sqldate{month}-$sqldate{day}',$R::ingredient_id,$R::qty) ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #$ref = $results->fetchrow_hashref(); $temphtml .= "Item added
    "; } elsif ($R::command eq "Delete" and $R::itemid) { $results = $dbh->prepare("update stockprep set f_status=101 where id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $temphtml .= "Item deleted
    "; } $temphtml .= $table{start}; $temphtml .= "
    "; my %stockitemsinfo; $results = $dbh->prepare("select name,id,units from ritems where stockitems_id > 0 and stockitems_id is not null;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockitemsinfo{$ref->{id}}{name} = $ref->{name}; $stockitemsinfo{$ref->{id}}{units} = $ref->{units}; } #MainLoop $results = $dbh->prepare(" select stockitems.id sid, stockitems.name name, stockitems.units unit, stockprep.id id, stockprep.qty qty, ritems.id rid from stockprep, ritems, stockitems where stockitems.f_status<100 and stockitems.shop_id=$shop{id} and stockitems.id = ritems.stockitems_id and stockprep.shop_id=$shop{id} and stockprep.f_status <100 and stockprep.ingredient_id=ritems.id and stockprep.date = '$sqldate{year}-$sqldate{month}-$sqldate{day}' order by ritems.name,stockprep.id ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockitem{$ref->{sid}}{name} = $ref->{name}; $stockitem{$ref->{sid}}{units} = $ref->{unit}; $temphtml .= ""; } if ($finalflag) { $temphtml .= ""; } $temphtml .= $table{end}; } elsif ($R::mode==2) { #recipes $temphtml .= &ajaxfunctions; #command if ($R::command eq "Add" and $R::recipe_id and $R::qty and $R::recipe_units) { $results = $dbh->prepare(" insert into stockprep (shop_id,date,recipe_id,recipe_units,qty) values ($shop{id},'$sqldate{year}-$sqldate{month}-$sqldate{day}',$R::recipe_id,$R::recipe_units,$R::qty) ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #$ref = $results->fetchrow_hashref(); $temphtml .= "Item added
    "; } elsif ($R::command eq "Delete" and $R::itemid) { $results = $dbh->prepare("update stockprep set f_status=101 where id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $temphtml .= "Item deleted
    "; } $temphtml .= $table{start}; $temphtml .= "
    "; my %recipeinfo; $results = $dbh->prepare(" select rn.name name,rn.id rid, ry.yield_unit units from recipe_names rn, recipe_yields ry where rn.id=ry.recipe_id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $recipeinfo{$ref->{rid}}{name} = $ref->{name}; $recipeinfo{$ref->{rid}}{units}{$ref->{units}} = 1; } #MainLoop $results = $dbh->prepare(" select * from stockprep where recipe_id > 0 and recipe_id is not null and shop_id=$shop{id} and f_status < 100 and stockprep.date = '$sqldate{year}-$sqldate{month}-$sqldate{day}' order by id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $temphtml .= ""; } if ($finalflag) { $temphtml .= ""; } $temphtml .= $table{end}; } $temphtml .= "
    SHOW THEORETICAL STOCK FROM THIS PREP SHEET BASED ON YIELD.
    "; if ($R::viewstock) { my %stockitem; $results = $dbh->prepare(" select concat(sc.name,' - ',si.name) name, si.id, si.units,si.type from stockitems si LEFT JOIN stockcats sc ON sc.id = si.stockcats_id where si.type='$tempdb{stocktype}' and si.stockitem = 1 and si.f_status <100 and si.shop_id='$shop{id}' and sc.f_status <100 and sc.shop_id=si.shop_id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockitem{$ref->{id}}{name} = $ref->{name}; $stockitem{$ref->{id}}{units} = $ref->{units}; $stockitem{$ref->{id}}{type} = $ref->{type}; } my $reportdate = "$sqldate{year}-$sqldate{month}-$sqldate{day}"; my %latestyields; my %idetails; $results = $dbh->prepare("select id,name,stockitems_id,units from ritems;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ $idetails{$ref->{id}}{stockitems_id} = $ref->{stockitems_id}; $idetails{$ref->{id}}{units} = $ref->{units}; } $results = $dbh->prepare(" select id ritem_id, yield from ritems;" ) or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $idetails{$ref->{ritem_id}}{yield} = $ref->{yield}; } my %closingpreps; $results = $dbh->prepare("select sum(qty) qty, ingredient_id from stockprep where date='$reportdate' and ingredient_id > 0 and ingredient_id is not null and shop_id=$shop{id} and f_status<100 group by ingredient_id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $closingpreps{ $idetails{$ref->{ingredient_id}}{stockitems_id} } += $ref->{qty}* ((100+(100-$idetails{$ref->{ingredient_id}}{yield}))/100)* #yield towards stockitem ${$unitalias{ $idetails{$ref->{ingredient_id}}{units} } }[1];; } #recipes prep $results = $dbh->prepare(" select sum(sp.qty) qty, sp.recipe_id recipe_id, sp.recipe_units recipe_units, ry.yield yield from stockprep sp, recipe_yields ry where sp.recipe_units = ry.yield_unit and sp.recipe_id=ry.recipe_id and sp.date='$reportdate' and sp.recipe_id > 0 and sp.recipe_id is not null and sp.shop_id=$shop{id} and sp.f_status<100 group by sp.recipe_id,sp.recipe_units; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ my %usage = &recipeingredients($ref->{recipe_id}, $ref->{yield}, {dbh => $dbh} ); foreach my $ingred (keys %usage) { $closingpreps{$idetails{$ingred}{stockitems_id}} += $ref->{qty}*$usage{$ingred}* ((100+(100-$idetails{$ingred}{yield}))/100)* #yield towards stockitem ${$unitalias{ $idetails{$ingred}{units} } }[1];; } } $temphtml .= "
    THEORETICAL STOCK:"; $temphtml .= $table{start}; $temphtml .= "
    "; foreach my $id (sort {$stockitem{$a}{name} cmp $stockitem{$b}{name}} keys %closingpreps) { $temphtml .= ""; } $temphtml .= $table{end}; } $temphtml .= "
    Legend: Closing Stock Opening Stock Opening Stock from Prep Opening Stock from Cl.Stock
    INGREDIENT ITEMQTYUNITCOMMAND
    $stockitemsinfo{$ref->{rid}}{name} (link to $ref->{name}, $units{$ref->{unit}}) $ref->{qty} $unitalias{ $stockitemsinfo{$ref->{rid}}{units} }[0] "; $temphtml .= "{rid}}{name}?');\" href=\"index.cgi?action=$R::action&mode=$R::mode&direction=$R::direction&date=$R::date&command=Delete&itemid=$ref->{id}\">$icons{d}" if ($finalflag); $temphtml .= "
    quickfind» find next»
    Ingredient
    Qty -
    RECIPE ITEMQTYUNITCOMMAND
    $recipeinfo{$ref->{recipe_id}}{name} $ref->{qty} $unitalias{ $ref->{recipe_units} }[0] "; $temphtml .= "{recipe_id}}{name}?');\" href=\"index.cgi?action=$R::action&mode=$R::mode&direction=$R::direction&date=$R::date&command=Delete&itemid=$ref->{id}\">$icons{d}" if ($finalflag); $temphtml .= "
    quickfind» find next»
    Ingredient
    Qty
    STOCK ITEMQTY
    $stockitem{$id}{name}, $units{$stockitem{$id}{units}} $closingpreps{$id}
    "; } else { $temphtml .= " $R::action: PLEASE SELECT DATE AND SHEET BELOW!"; } my %dsel = ("$R::direction" => "selected"); $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "

    Select Day: $icons{cal} |
    "; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } # Edit Ingredient Issue elsif ($socketflag == 1 and $R::action eq "Edit Stock Items") { #override stockeditor if ($usertype == 1) { $edit_stock_items = 1 } else { $edit_stock_items = -1 } #print "Debug Usertype: $usertype edit_stock_items $edit_stock_items"; my $temphtml; retreive_stockcats($database, $shop{id}); #/retreive permanent stages $tempdb{stocktype} = $R::stocktype if ($R::stocktype); $tempdb{stockletter} = $R::stockletter if ($R::stockletter); #/no permanent stages yet - init if (! $tempdb{stocktype}) {$tempdb{stocktype}= (sort {$a <=> $b} keys %{ $stocktypes{$database} } )[0]}; if (! $tempdb{stockletter}) {$tempdb{stockletter} ="A"}; $onload="document.form1.name.focus();"; $template =~ s/\@title\@/Edit Stock Items - $stocktypes{$database}{$tempdb{stocktype}}/sgi; $temphtml = "
    "; #/## FOOD & LIQOUR EDIT COMMANDS if (($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) and $R::name) { $R::name=~ tr/a-z/A-Z/; my ($stockitem,$listeditem); if (! $R::stockitem) {$stockitem=2} else {$stockitem=1} my $results = $dbh->prepare("INSERT INTO stockitems (shop_id,name, type, units, stockitem, bin, stockcats_id, minqty,maxqty, warnperc) values ($shop{id},?,'$tempdb{stocktype}','$R::units','$stockitem','$R::bin', '$R::stockcats_id', '$R::minqty','$R::maxqty', '$R::warnperc');") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA ADDED."; $tempdb{stockletter} = substr($R::name,0,1) if ($R::name); } elsif ($R::command eq "delete") { my $results = $dbh->prepare("UPDATE stockitems SET f_status=101 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "STOCK DELETED."; } elsif (($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) and $R::name) { $R::name=~ tr/a-z/A-Z/; my ($stockitem,$listeditem); if (! $R::stockitem) {$stockitem=2} else {$stockitem=1} if ($edit_stock_items) { my $results = $dbh->prepare("UPDATE stockitems SET name=?, type='$tempdb{stocktype}', units='$R::units', stockitem='$stockitem', bin='$R::bin', stockcats_id = '$R::stockcats_id', minqty = '$R::minqty', maxqty = '$R::maxqty', warnperc = '$R::warnperc', f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); } else { #/ stockitem editor will allow only editing of stock's bin, no adding and deleting functions my $results = $dbh->prepare("UPDATE stockitems SET type='$tempdb{stocktype}', bin='$R::bin', f_status=1 WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } $mess = "DATA MODIFIED."; } #/## /COMMANDS $temphtml .= "STOCK TYPE:
    "; foreach my $acctype (sort keys %{ $stocktypes_breakdown{$database} } ) { $temphtml .= "($account_types{$acctype}: "; foreach (sort {$stocktypes{$database}{$a} cmp $stocktypes{$database}{$b}} keys %{ $stocktypes_breakdown{$database}{$acctype} } ) { $temphtml .= "[".($tempdb{stocktype} == $_ ? " $stocktypes{$database}{$_} " : "$stocktypes{$database}{$_}")."]"; } $temphtml .= ")
    "; } if ($R::searchstring eq "") { $temphtml .= "
    Legend: Prepared Stock Theoretical Stock
    "; foreach (("0".."9","A".."Z")) { $results = $dbh->prepare("SELECT count(id) count FROM stockitems WHERE name like '$_%' and stockitem <> 2 and type='$tempdb{stocktype}' and shop_id = $shop{id} and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $temphtml .= "{count} > 0) { $temphtml .= " title=\"$ref->{count} items\">$_"; } else {$temphtml .= ">$_";} $temphtml .= ""; } $temphtml .= "
    "; } $temphtml .= "
    Search for "; $temphtml .= " "; $temphtml .= "

    "; #/ DRAW TABLE stockitems $temphtml .= $table{start}; $temphtml .= "
    Category Description / Name Units Bin Min QTY Max QTY Warning % Stock Item? :COMMANDS:
    $stockcats{$database}{$tempdb{stocktype}}{$ref->{stockcats_id}}".($ref->{stockitem} == 1 ? "" : "")."$ref->{name} $units{$ref->{units}}".($ref1->{linked} > 0 ? " [linked to component]" :"")." $bins{$database}{$ref->{bin}} $ref->{minqty} $ref->{maxqty} $ref->{warnperc} $isstockitem{$ref->{stockitem}}"; #/check for usage of the stock - Disabled on 8/3/2004 2:36PM if ($activity==0 and $edit_stock_items > 0) { $temphtml .= "{id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\" onclick=\"return confirm('DELETE ITEM: $ref->{name} ?');\">$icons{d}"; } $temphtml .= " {id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\">$icons{m}" if ($edit_stock_items > 0); $temphtml .= "
    {name}\" $calt> {minqty}\" $calt> {maxqty}\" $calt> {warnperc}\" $calt>
    {minqty}\" $calt> {maxqty}\" $calt> {warnperc}\" $calt>
    Name Group / Company Type Card Number Card Expiration Loyalty Discount % Note Landline Cellphone Address Active :COMMANDS:
    $clienttypes{ $ref->{type} }
    $clienttypes{ $ref->{type} } : DISABLED
    {active} == 2 ? 'style="background:pink;"': "")."> {id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\">$ref->{name} $ref->{clientgroup} $clienttypes{$ref->{type}} $ref->{loyalnumber} $ref->{expiremonth}/$ref->{expireyear} $ref->{discountpercent} % $ref->{note} $ref->{telephone} $ref->{cellphone} $ref->{address} $yesno{$ref->{active}}"; #/check for usage of the supplier $subresults = $dbh->prepare("SELECT id activity FROM tillinvoices WHERE shop_id=$shop{id} and f_status<100 and client_id = $ref->{id} order by id desc limit 1;") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $subresults->finish(); if ($ref1->{activity}==0) { $temphtml .= "{id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\" onclick=\"return confirm('DELETE ITEM: $ref->{name} ?');\">$icons{d} "; } $temphtml .= " {id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\">$icons{m}"; $temphtml .= "
    {name}\" $calt> {clientgroup}\" $calt> Manual Entry {loyalnumber}\" $calt>
    Swipe Card (Clear): {cardfootprint}\" name=cardfootprint >
    MM {emonth}\" $calt>
    YY {eyear}\" $calt>
    {discountpercent}\" $calt> {note}\" $calt> {telephone}\" $calt> {cellphone}\" $calt> {address}\" $calt>
    Manual Entry
    Swipe Card (Clear):
    MM
    YY
    Name:COMMANDS:
    $ref->{name}"; #/check for usage of the supplier $subresults = $dbh->prepare("SELECT count(id) activity FROM stockitems WHERE shop_id=$shop{id} and f_status<100 and stockcats_id = $ref->{id};") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $subresults->finish(); if ($ref1->{activity}==0) { $temphtml .= "{id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\" onclick=\"return confirm('DELETE ITEM: $ref->{name} ?');\">$icons{d} "; } $temphtml .= " {id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\">$icons{m}"; $temphtml .= "
    {name}\" $calt>
    Name:COMMANDS:
    $ref->{name}"; #/check for usage of the supplier $subresults = $dbh->prepare("SELECT count(id) activity FROM stockitems WHERE shop_id=$shop{id} and f_status<100 and bin = $ref->{id};") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $subresults->finish(); if ($ref1->{activity}==0) { $temphtml .= "{id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\" onclick=\"return confirm('DELETE ITEM: $ref->{name} ?');\">$icons{d} "; } $temphtml .= " {id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\">$icons{m}"; $temphtml .= "
    {name}\" $calt>
    Name:COMMANDS:
    $ref->{name}"; #/check for usage of the supplier $subresults = $dbh->prepare("SELECT id activity FROM purchases WHERE shop_id=$shop{id} and f_status<100 and department = $ref->{id} order by id desc limit 1;") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); my $activity = $ref1->{activity}; $subresults = $dbh->prepare("SELECT id activity FROM cstock WHERE shop_id=$shop{id} and f_status<100 and department = $ref->{id} order by id desc limit 1;") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $activity += $ref1->{activity}; # to retreive from tillinvoices $subresults = $dbh->prepare("SELECT id activity FROM tillinvoices WHERE shop_id=$shop{id} and f_status<100 and department = $ref->{id} order by id desc limit 1;") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $activity += $ref1->{activity}; if ($activity==0) { $temphtml .= "{id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\" onclick=\"return confirm('DELETE ITEM: $ref->{name} ?');\">$icons{d} "; } $temphtml .= " {id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\">$icons{m}"; $temphtml .= "
    {name}\" $calt>
    NameDescriptionAccounting Type:COMMANDS:
    $ref->{name}$ref->{description}$account_types{$ref->{account_type}}"; #/check for usage of the supplier $subresults = $dbh->prepare("SELECT id activity FROM stockitems WHERE shop_id=$shop{id} and f_status<100 and type = $ref->{id} order by id desc limit 1;") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $subresults->finish(); if ($ref1->{activity}==0) { $temphtml .= "{id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\" onclick=\"return confirm('DELETE ITEM: $ref->{name} ?');\">$icons{d} "; } $temphtml .= " {id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\">$icons{m}"; $temphtml .= "
    {name}\" $calt> {description}\" $calt>
    NameNote:COMMANDS:
    $ref->{name} $ref->{note}"; #/check for usage of the supplier $subresults = $dbh->prepare("SELECT count(id) activity FROM purchases WHERE shop_id=$shop{id} and f_status<100 and supplier_id = $ref->{id};") or die $subresults->errstr(); $subresults->execute() or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $subresults->finish(); if ($ref1->{activity}==0) { $temphtml .= "{id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\" onclick=\"return confirm('DELETE ITEM: $ref->{name} ?');\">$icons{d} "; } $temphtml .= " {id}&ptype=$R::ptype&pdate=$R::pdate&dcashid=$R::dcashid&fpurchases=$R::fpurchases\">$icons{m}"; $temphtml .= "
    {name}\" $calt> {note}\" $calt>
    NameNote:COMMANDS:
    $ref->{name} $ref->{note}"; #/TODO - check for usage of the supplier #/$subresults = $dbh->prepare("SELECT count(id) activity FROM dcashitems WHERE f_status<100 and waitron_id = $ref->{id};") or die $subresults->errstr(); #/$subresults->execute() or die $subresults->errstr(); #/$ref1 = $subresults->fetchrow_hashref(); #/$subresults->finish(); #/if (! $ref1->{activity}) { if (1) { $temphtml .= "{id}\" onclick=\"return confirm('DELETE ITEM: $ref->{name} ?');\">$icons{d}"; } $temphtml .= " {id}\">$icons{m}"; $temphtml .= "
    {name}\" $calt> {note}\" $calt>
    Name Qty U.Price (excl) Total (excl)
    $ref->{description} (expenses) $ref->{qty} $currency ".pr($ref->{price})." $currency ".pr($ref->{total})."
    $stockitems{$ref->{stockitems_id}} $ref->{qty} $currency ".pr($ref->{price})." $currency ".pr($ref->{total})."
    Total (excl): $currency ".pr($total)."
    Date Supplier Invoice Description Qty Price Total
    $ref->{date} $ref->{supplier} $ref->{invoice} $ref->{description} $ref->{org_qty} ".pr($ref->{price})." ".pr($ref->{value})."
    Total Excl: ".pr($total)."
    Item Qty U.Price Discount Total
    $ref->{name} ".($ref->{qty})." $currency $ref->{uprice} $currency ".pr( $ref->{discount} )." $currency ".pr( $ref->{total} - $ref->{discount} * $ref->{qty} )."
    Total: ".pr($total)."
    "; foreach my $invoice (sort @invoices) { $temphtml .= ""; } $temphtml .= "
    $waitron_name
    CHK # $invoice"; foreach my $question ( sort keys %{$questionz{questions}}) { $temphtml .= ""; } $temphtml .= "
    $question. $questionz{questions}{$question} (N/A)
    "; foreach my $answer ( sort keys %{ $questionz{answers}{$question} } ) { $temphtml .= "     $questionz{answers}{$question}{$answer}
    "; } $temphtml .= "
    You can just close this window when finished.
    "; $template =~ s/\@content\@/$temphtml/sgi; } if ($R::subaction eq "change_store") { my $temphtml; if ($R::shopid ne "" or $R::shopid > 0) { $tempdb{current_shop_id} = $R::shopid; $template =~ s/\@onload\@/javascript:window.opener.top.mainframe.location.reload(); window.close();/sgi; } $template =~ s/\@title\@/Select Branch/sgi; $temphtml = "
    "; foreach (sort {$a<=>$b} keys %shopname) { #/$temphtml .= "$shopname{$_}
    "; $temphtml .= "
    $shopname{$_}
    "; } $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } if ($R::subaction eq "cstockpreview") { my $temphtml; my %calc1; $template =~ s/\@title\@/CLOSING STOCK PREVIEW/sgi; $temphtml = "
    "; $temphtml .= " Sort by usage value


    "; my $stocktype=$tempdb{stocktype}; #/get all stock in memory: name, bin, units my %stockdetails; $results = $dbh->prepare(" SELECT si.id,concat(sc.name,' - ',si.name) name, bin, units FROM stockitems si LEFT JOIN stockcats sc ON sc.id = si.stockcats_id WHERE si.f_status<100 and si.shop_id=$shop{id} and sc.f_status<100 and sc.shop_id=$shop{id} and si.type=$stocktype; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockdetails{name}{$ref->{id}} = $ref->{name}; $stockdetails{bin}{$ref->{id}} = $ref->{bin}; $stockdetails{units}{$ref->{id}} = $ref->{units}; } #/determine last pid for the stocktype from PREVIOUS STOCK $results = $dbh->prepare(" select last_pid,date, date(date) date_only from cstock where f_status<100 and stocktype=$stocktype and shop_id=$shop{id} order by id desc limit 1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $last_pid = $ref->{last_pid}*1; my $last_date = $ref->{date}; my $last_date_only = $ref->{date_only}; $last_date = "1900-01-01" if (! $last_date); #~ print "Last stock date: $last_date"; my $turnoverdivider; #/ TURNOVER #GROSS AND DEDUCTABLES NET $results = $dbh->prepare(" select sum(dci.s_fee) sfee_total, sum(dcinv.dcinv_turnover_total - dcinv.vat_total) turnover_total from dcash, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 where dcash.date >= '$last_date_only' and dcash.date < CURRENT_DATE #/ tuesday ??????? and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 # group by dci.id # order by dci.id ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $total_turnover = $ref->{turnover_total}; #~ print " DCASH TOTALTURNOVER $total_turnover"; $results = $dbh->prepare(" select sum(dci.s_fee) sfee_total from dcash, dcashitems dci where dcash.date >= '$last_date_only' and dcash.date < CURRENT_DATE #/ tuesday ??????? and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $total_service_fees = $ref->{sfee_total}; #COSTCENTER TURNOVER my %sqldate = dateforsql($R::date); $subresults = $dbh->prepare(" select sum(dctov.turnover_total) costcenter_turnover, sum(dctov.vat_total) costcenter_vat, sum(dctov.returns_total) costcenter_returns, sum(dctov.staffpromo_total) costcenter_staffpromo, sum(dctov.discounts_total) costcenter_discounts from dcash, dcashitems dci, dcashinvoices dcinv, dcashturnover dctov where dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcinv.shop_id=dcash.shop_id and dctov.shop_id=dcash.shop_id and dcash.f_status<100 and dci.f_status<100 and dcinv.f_status<100 and dctov.f_status<100 and dcash.date >= '$last_date_only' and dcash.date < '$sqldate{year}-$sqldate{month}-$sqldate{day}' #/ tuesday ??????? and dctov.costcenter_id=$tempdb{stocktype} and dcash.id = dci.dcash_id and dci.id = dcinv.dcashitems_id and dcinv.id = dctov.dcashinvoices_id"); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $costcenter_vat = $subref->{costcenter_vat}; my $costcenter_net = $subref->{costcenter_turnover}; my $costcenter_returns = $subref->{costcenter_returns}; my $costcenter_staffpromo = $subref->{costcenter_staffpromo}; my $costcenter_discounts = $subref->{costcenter_discounts}; #factors my $costcenter_factor = $costcenter_net/$total_turnover if ($total_turnover); my $costcenter_sfee = $costcenter_factor*$total_service_fees; $calc1{turnover} = $costcenter_net; $calc1{noni_turnover} = $costcenter_net - $costcenter_sfee - $costcenter_returns - $costcenter_staffpromo - $costcenter_discounts; #//turnover #/purchases sinse last pid excluding my %last_purchases; $results = $dbh->prepare("select si.id id, si.name name, si.units units, si.bin bin, sum(pu.qty) qty, sum(pu.price*pu.qty) totalprice, pu.price uprice from purchases pu,stockitems si where si.f_status<100 and pu.f_status<100 and si.shop_id=$shop{id} and pu.shop_id=si.shop_id and si.id=pu.stockitems_id and si.type=$stocktype and pu.id>$last_pid #/cs:last_pid and (pu.cnote != 1 or pu.cnote is NULL or pu.cnote = 0) group by si.id order by name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_purchases{$ref->{id}}{qty} = $ref->{qty}; $last_purchases{$ref->{id}}{value} = $ref->{totalprice}; } #/last closing stock qty and value my %last_closingstock; $results = $dbh->prepare("select si.id id, si.name name, sum(cs.qty) qty, sum(cs.value) stockvalue, sum(cs.value)/sum(cs.qty) uprice from cstock cs, stockitems si where si.f_status<100 and cs.f_status<100 and si.shop_id=$shop{id} and cs.shop_id=si.shop_id and si.id=cs.stockitems_id and si.type=$stocktype and cs.last_pid=$last_pid #/cs:last_pid and cs.date='$last_date' group by si.id order by si.name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_closingstock{$ref->{id}}{qty} = $ref->{qty}; $last_closingstock{$ref->{id}}{value} = $ref->{stockvalue}; } #/last credit notes - since last_pid my %last_creditnotes; $results = $dbh->prepare("select si.id id, si.name name, sum(pu.qty) qty, sum(pu.price*pu.qty) totalprice, pu.price uprice from purchases pu,stockitems si where si.f_status<100 and pu.f_status<100 and si.shop_id=$shop{id} and pu.shop_id=si.shop_id and si.id=pu.stockitems_id and si.type=$stocktype and pu.id>$last_pid #/cs:last_pid and pu.cnote = 1 group by si.id order by name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $last_creditnotes{$ref->{id}}{qty} = $ref->{qty}; $last_creditnotes{$ref->{id}}{value} = $ref->{totalprice}; } #/calculate the availables; my %availables; foreach my $id (keys %{$stockdetails{name}}) { my $available_qty; $available_qty = $last_closingstock{$id}{qty} + ($last_purchases{$id}{qty} - $last_creditnotes{$id}{qty}); next if ($available_qty <= 0 and $show_noqty_stock == -1); $availables{$id} = $available_qty; } #/by bin my $sortage = 'name'; #/retreive all stockIDs with their FIFO last pids my %fifodetails; $results = $dbh->prepare("select stockitems_id id,debited_pid,credit_left from cstock where f_status<100 and shop_id=$shop{id} and date='$last_date' #/cs:last_pid and stocktype=$stocktype;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $fifodetails{$ref->{id}}{debited_pid} = $ref->{debited_pid}; $fifodetails{$ref->{id}}{credit_left} = $ref->{credit_left}; } #/retreive debited_pid, credit_left from older stock, and not previous, because of missing record in previous. It is missing because the item had no availability foreach my $id ( keys %last_purchases ) { if (! exists $fifodetails{$id}) { $results = $dbh->prepare(" select debited_pid,credit_left from cstock where f_status<100 and shop_id=$shop{id} and stockitems_id=$id order by date desc limit 1; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $fifodetails{$id}{debited_pid} = $ref->{debited_pid}; $fifodetails{$id}{credit_left} = $ref->{credit_left}; } } my %purchases_for_use; foreach my $id (keys %availables) { $results = $dbh->prepare(" SELECT pu.id id, CASE WHEN pu.cnote != 1 or pu.cnote is NULL or pu.cnote = 0 then 0 WHEN pu.cnote = 1 then 1 END cnote, pu.qty qty, pu.price price from purchases pu where pu.f_status<100 and pu.shop_id=$shop{id} and pu.stockitems_id='$id' and pu.id>='$fifodetails{$id}{debited_pid}' and pu.qty > 0 ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $purchases_for_use{$id}{$ref->{id}}{qty} = $ref->{qty}; $purchases_for_use{$id}{$ref->{id}}{price} = $ref->{price}; $purchases_for_use{$id}{$ref->{id}}{cnote} = $ref->{cnote}; } } #/fifo_hash_for_use(963); #/fifo_hash_for_use(1431); #/fifo_hash_for_use($_) foreach (keys %availables); my %fiforesultz; my $maxusage; foreach my $id (keys %availables) { #/print join("UUU",keys %{$purchases_for_use{$id}}) if ($id==891); ( $fiforesultz{$id}{available_value}, $fiforesultz{$id}{creditnotes_value}, $fiforesultz{$id}{credits_left}, $fiforesultz{$id}{debited_pid}, $fiforesultz{$id}{usage_qty}, $fiforesultz{$id}{usage_value}, $fiforesultz{$id}{cs_qty}, $fiforesultz{$id}{cs_value} ) = fifo_hash_for_use($id, $last_closingstock{$id}{qty}, $last_closingstock{$id}{value}, $fifodetails{$id}{debited_pid}, $fifodetails{$id}{credit_left}, \%last_creditnotes, \%last_purchases, $last_pid, \%purchases_for_use, \%tempdb ); #/totals $calc1{total_usage} += $fiforesultz{$id}{usage_value}; $calc1{total_ostock} += $last_closingstock{$id}{value}; $calc1{total_purch} += $last_purchases{$id}{value}; $calc1{total_cnotes} += $fiforesultz{$id}{creditnotes_value}; $calc1{total_cnotesorg} += $last_creditnotes{$id}{value}; #/not in use $calc1{total_avail} += $fiforesultz{$id}{available_value}; $calc1{total_cs} += $fiforesultz{$id}{cs_value}; $maxusage = $fiforesultz{$id}{usage_value} if ($maxusage < $fiforesultz{$id}{usage_value}); } my @colorz = blender("#FFFFFF","#0000FF",255); #/display preview my %ordertype = (1 => 'name', 2 => 'bin'); my $orderby = $ordertype{$tempdb{cstockviewtype}}; $temphtml .= $table{startp}; $temphtml .= "
    Previous Stock Purchases Credit Notes Total Availability Stock on Hand Usage   Cost
    $stockdetails{name}{$id}, $units{$stockdetails{units}{$id}} "; $temphtml .= "(purchases details)" if ($previewpurchases); if ($R::purdetails == $id and rn3($fiforesultz{$id}{usage_qty}) > 0 ) { #/$temphtml .= "
    #/
    stockitems_id = $id [".join("+",keys %{$purchases_for_use{$id}})."]
    #/debited start pid $fifodetails{$id}{debited_pid} creditleft $fifodetails{$id}{credit_left} #/
    #/debited end pid $fiforesultz{$id}{debited_pid} creditleft $fiforesultz{$id}{credits_left}"; my %purdetails; my %bottomline; $results = $dbh->prepare(" select * from purchases where shop_id=$shop{id} and f_status<100 and (cnote = 0 or cnote is null or cnote != 1) and stockitems_id='$id' and id >= '$fifodetails{$id}{debited_pid}' and id <= '$fiforesultz{$id}{debited_pid}';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($fifodetails{$id}{debited_pid} != $fiforesultz{$id}{debited_pid}) { if ($ref->{id} == $fifodetails{$id}{debited_pid}) { $purdetails{$ref->{id}}{qty} = $fifodetails{$id}{credit_left}; } elsif ($ref->{id} == $fiforesultz{$id}{debited_pid}) { $purdetails{$ref->{id}}{qty} = $ref->{qty} - $fiforesultz{$id}{credits_left}; } else { $purdetails{$ref->{id}}{qty} = $ref->{qty}; } } else { $purdetails{$ref->{id}}{qty} = $fifodetails{$id}{credit_left} - $fiforesultz{$id}{credits_left}; } $purdetails{$ref->{id}}{invoice} = $ref->{invoice}; $purdetails{$ref->{id}}{date} = $ref->{date}; $purdetails{$ref->{id}}{price} = $ref->{price}; } my %fifo_credit_notes; if ($last_creditnotes{$R::purdetails}{qty} > 0) { #/$temphtml.= "
    CSTOCK STORED CNOTES VALUE: $current{i_credit_notes}{$R::purdetails}
    "; my $tocredit = $last_creditnotes{$R::purdetails}{qty}; my @deletepids; foreach my $pid (sort {$a<=>$b} keys %purdetails) { if (rn3($tocredit) > $purdetails{$pid}{qty}) { $tocredit -= $purdetails{$pid}{qty}; $fifo_credit_notes{$R::purdetails} += $purdetails{$pid}{qty}*$purdetails{$pid}{price}; delete $purdetails{$pid}; } else { $purdetails{$pid}{qty} -= $tocredit; $fifo_credit_notes{$R::purdetails} += $tocredit*$purdetails{$pid}{price}; $tocredit = 0; } } } $temphtml .= "

    Calculated FIFO cnotes value = $currency $fifo_credit_notes{$R::purdetails}
    "; $temphtml .= ""; foreach my $pid (sort {$a<=>$b} keys %purdetails) { $bottomline{usage_value} += $purdetails{$pid}{price}*$purdetails{$pid}{qty}; $bottomline{qty} += $purdetails{$pid}{qty}; $temphtml .= " $last_pid ? "class=ccel" : "")."> "; } $temphtml .= ""; $temphtml .= "
    Invoice Date Unit Price Usage Usage Value
    $purdetails{$pid}{invoice} $purdetails{$pid}{date} $currency ".pr($purdetails{$pid}{price})." ".rn3($purdetails{$pid}{qty})." $units{$stockdetails{units}{$R::purdetails}} $currency ".pr($purdetails{$pid}{qty}*$purdetails{$pid}{price})."
    Total avg. $currency "; $temphtml .= pr($bottomline{usage_value}/$bottomline{qty}) if ($bottomline{qty}>0); $temphtml .=" ".rn3($bottomline{qty})." $units{$stockdetails{units}{$R::purdetails}} $currency ".pr($bottomline{usage_value})."
    "; } #/ if invoice details when usage elsif ($R::purdetails == $id and rn3($fiforesultz{$id}{usage_qty}) <= 0) { $temphtml .= " NO USAGE TO SHOW..."; } $temphtml .= "
    Previous Stock
    QTY: $last_closingstock{$id}{qty} $units{$stockdetails{units}{$id}}
    VALUE: $currency ".pr($last_closingstock{$id}{value})."
    Purchases
    QTY: $last_purchases{$id}{qty} $units{$stockdetails{units}{$id}}
    VALUE: $currency ".pr($last_purchases{$id}{value})."
    Credit Notes
    QTY: $last_creditnotes{$id}{qty} $units{$stockdetails{units}{$id}}
    VALUE: $currency ".pr($fiforesultz{$id}{creditnotes_value})."
    Total Availability
    QTY: $availables{$id} $units{$stockdetails{units}{$id}}
    VALUE: $currency ".pr($fiforesultz{$id}{available_value}).($availables{$id} < 0 ? "
    WRONG VALUE
    ." :"")."
    Stock on Hand
    QTY: $fiforesultz{$id}{cs_qty} $units{$stockdetails{units}{$id}}
    VALUE: $currency ".pr($fiforesultz{$id}{cs_value}).($availables{$id} < 0 ? "
    WRONG VALUE
    ." :"")."
    Usage
    QTY: $fiforesultz{$id}{usage_qty} $units{$stockdetails{units}{$id}}
    VALUE: $currency ".pr($fiforesultz{$id}{usage_value}).(($availables{$id} < 0 or $fiforesultz{$id}{usage_qty} < 0)? "
    WRONG VALUE
    ." :"")."
    $fifodetails{$id}{debited_pid} - $fiforesultz{$id}{debited_pid} debited_pid #/
    $fifodetails{$id}{credit_left} - ".rn3($fiforesultz{$id}{credits_left})." credit_left $temphtml .= ($colorz[int($fiforesultz{$id}{usage_value}/$maxusage*255)]) if ($maxusage); $temphtml .= "\" title=\""; $temphtml .= (pr($fiforesultz{$id}{usage_value}/$calc1{total_usage}*100)) if ($calc1{total_usage}); $temphtml .= " % of total usage value $currency"; $temphtml .= (pr($fiforesultz{$id}{usage_value}/$fiforesultz{$id}{usage_qty})) if ($fiforesultz{$id}{usage_qty}>0); $temphtml .= " avg uprice\"> 
    Overall "; if ($calc1{turnover}) {$temphtml .= (pr($incrementalusage/$calc1{turnover}*100));} $temphtml .= " %
    This item "; $temphtml .= (pr($fiforesultz{$id}{usage_value}/$calc1{turnover}*100)) if ($calc1{turnover}); $temphtml .= "%
    "; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; if ($calc1{turnover}>0) { $calc1{cost} = $calc1{total_usage} / $calc1{turnover} * 100; $temphtml .= ""; } else { $temphtml .= ""; } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; if ($calc1{noni_turnover}>0) { $calc1{noni_cost} = $calc1{total_usage} / $calc1{noni_turnover} * 100; $temphtml .= ""; } else { $temphtml .= ""; } $temphtml .= "
    Opening Stock $currency ".pr($calc1{total_ostock})."

    Purchases since
    last closing stock
    $currency ".pr($calc1{total_purch})."
    Credit notes since
    last closing stock
    $currency ".pr($calc1{total_cnotes})."
    Total Availability
    $currency ".pr($calc1{total_avail})."
    Stock on Hand $currency ".pr($calc1{total_cs})."

    Usage $currency ".pr($calc1{total_usage})."
    Turnover $currency ".pr($calc1{turnover})."
    COST ".pr($calc1{cost})." %
    COST Error!!!

    Non-Income Turnover $currency ".pr($calc1{turnover} - $calc1{noni_turnover})."
    Returns $currency ".pr($costcenter_returns)."
    Discounts $currency ".pr($costcenter_discounts)."
    Staff Promo $currency ".pr($costcenter_staffpromo)."
    Service Fees $currency ".pr($costcenter_sfee)."
    NET Turnover $currency ".pr($calc1{noni_turnover})."
    NET COST TO COMPANY ".pr($calc1{noni_cost})." %
    COST TO COMPANY Error!!!
    "; $temphtml .= ""; $template =~ s/\@content\@/$temphtml/sgi; } #/cstock previewer if ($R::subaction eq "cashup") { # UNUSED my $formhtml; my $sttype; $temphtml = "
    "; $onsubmit = "onSubmit=\"if(check_s_fee()) {alterdata();} return false;\""; $onload = "getdata();document.form1.waitron_id.focus();"; $template =~ s/\@title\@/purchase/sgi; $template =~ s/.*?//sgi; $formhtml = getform("cashup-pop"); my $listhtml; #/retreive dropdowns $listhtml = ""; $formhtml =~ s/\@waitron_id\@/$listhtml/sgi; $temphtml .= $formhtml; $temphtml .= "
    "; } #/ cashup detach if ($R::subaction eq "purchase") { # UNUSED my $formhtml; my $sttype; $temphtml = "
    "; if ($R::ptype eq "liqour") { $sttype="and si.type =2"; } else { #/normal purchases food $sttype="and si.type =1"; } $onsubmit = "onSubmit=\"alterdata();return false;\""; $onload = "getdata();document.form1.stockitems_id.focus();"; $template =~ s/\@title\@/purchase/sgi; $template =~ s/.*?//sgi; $formhtml = getform("purchases-pop"); my $listhtml; #/retreive dropdowns $listhtml = ""; $formhtml =~ s/\@stockitems_id\@/$listhtml/sgi; $listhtml = ""; $formhtml =~ s/\@supplier_id\@/$listhtml/sgi; $listhtml = "*"; #/$listhtml = ""; $formhtml =~ s/\@org_units\@/$listhtml/sgi; $temphtml .= $formhtml; $temphtml .= "
    "; } #/ purchase detach if ($R::subaction eq "otherpurchase") { # UNUSED my $formhtml; $temphtml = "
    "; $onsubmit = "onSubmit=\"alterdata();return false;\""; $onload = "getdata();document.form1.description.focus();"; $template =~ s/\@title\@/purchase/sgi; $template =~ s/.*?//sgi; $formhtml = getform("otherpurchases-pop"); my $listhtml; #/retreive dropdowns $listhtml =""; $formhtml =~ s/\@othertype\@/$listhtml/sgi; $listhtml = ""; $formhtml =~ s/\@supplier_id\@/$listhtml/sgi; $listhtml = "*"; #/$listhtml = ""; $formhtml =~ s/\@org_units\@/$listhtml/sgi; $temphtml .= $formhtml; $temphtml .= "
    "; } #/ other purchase detach if ($R::subaction eq "sfeepay") { $temphtml = "
    "; $template =~ s/\@title\@/Payment to $R::name/sgi; my %sqldate; %sqldate = dateforsql($R::date) if ($R::command eq "Pay"); if ($R::command eq "Pay" and $R::paid and $sqldate{day} and $sqldate{month} and $sqldate{year} and $R::document) { my $results = $dbh->prepare("INSERT INTO sfeepaid (shop_id, waitron_id, amount, date, document) values ($shop{id}, '$R::waitron', '$R::paid', '$sqldate{year}-$sqldate{month}-$sqldate{day}',?);") or die $dbh->errstr(); $results->execute($R::document) or die $results->errstr(); $mess = "$icons{i} Amount of $currency ".pr($R::paid)." was paid."; $temphtml .=""; } else { $onload="document.form1.paid.focus();"; #/calendar JS $temphtml .= qq~ ~; $mess= "Please fill out the required information." if ($R::command); $temphtml .= "Amount owed: $currency".pr($R::owed).""; $temphtml .= "
    "; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    Amoun paid $currency
    Document Ref.#
    Date of document $icons{cal}
    "; $temphtml .="
    "; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } #/else $temphtml .= "
    "; } $template =~ s/\@content\@/$temphtml/sgi; } #/ END POPUP ACTION elsif ($socketflag == 1 and $R::action eq "reports") { my $temphtml; if ($R::subaction eq "feedback") { if ($R::command eq "Report" and $R::startdate and $R::enddate) { my $abrevi = $sys_settings{'abrev'};#$settings::abrev; $temphtml = "
    "; $template =~ s/\@title\@/Customer Feedback/sgi; my ($startdate, $enddate, $starttime, $endtime); my (%sqldate,%sqldate2); %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate2 = dateforsql($R::enddate); $enddate = $sqldate2{year}."-".$sqldate2{month}."-".$sqldate2{day}; #/ '$startdate 3:00:00' #/ '$enddate 3:00:00' my %association = ( "fbg" => "", "fis" => "-fis", "fbgnam" => "-fbgnam", "ami" => "-ami", "ups" => "-ups", "rjs" => "-rjs", "lpz" => "-lpz", "cab" => "-cab", "tbc" => "-tbc", "$sys_settings{'abrev'}" => "-$sys_settings{'abrev'}"#"-$settings::abrev" ); my %brands = ( "fbg" => "The Famous Butchers Grill", "fbgnam" => "The Famous Butchers Grill - International", "fis" => "The Cape Fish Company", "ami" => "Amici Restaurants", "rjs" => "RJ's Steakhouse", "ups" => "Upstairs Asian Fusion", "lpz" => "La Pizzacia", "cab" => "The Cabin", "tbc" => "Tropical Breeze", "$sys_settings{'abrev'}" => $sys_settings{'brand'},#"$settings::brand" ); my @databases_order = ($sys_settings{'abrev'});#($settings::abrev); my $qna_id; my %questionz; { #/QUESTIONARE FORMS SLURP #/temporary version my $qnafile = "/wwwroot/extranet/data/qna.txt"; open(IN, "< $qnafile") or die "can't open $qnafile: $!"; binmode (IN); seek(IN, 0, 0); sysread (IN, my $slurp, -s IN); close(IN); my $qnadata = $slurp; my $qnaprint = $qnadata; #/qna init $qnaprint =~ /\[formid:(\d+)\]/sgi; $qna_id = $1; $qnaprint =~ s/\[formid:($qna_id)\]//gsi; $qnaprint =~ s/\[waitron\]//gsi; $qnaprint =~ s/\[invoice\]//gsi; $qnaprint =~ s/\[dwidth\]//gsi; $qnaprint =~ s/\[dheight\]//gsi; $qnaprint =~ s/\[normal\]//gsi; $qnaprint =~ s/\[underline\]//gsi; #/qna question fetch my @breaked = split (/\n|\r/, $qnaprint); $_ =~ s/\n|\r// foreach @breaked; my $cnt1 = 1; my $cnt2 = 1; foreach my $line (@breaked) { if ($line =~ /(\[qp\])/) { $questionz{$qna_id}{questions}{$cnt1} = $'; $cnt1++; $cnt2 = 1; } elsif ($line =~ m/(\[q\])/gsi) { my $b = $line; while ($b =~ m/(\[q\])([^\[]*)/gsi) { $questionz{$qna_id}{answers}{$cnt1-1}{$cnt2} = $2; $cnt2++; } #~ $questionz{$qna_id}{answers}{$cnt1-1}{$cnt2} = $'; #~ $cnt2++; } } } #/questionare fetch END. my %globalcounts; my %globalbrandcounts; my %brandcounts; my %brandallinvoices; my %brandfillinvoices; my %answersperquestion; my %shopnames; my %waitrons; $temphtml .= "Covering $R::startdate 3:00:00 to $R::enddate 3:00:00
    "; if ($thisshop > 0) {$R::selshop=$thisshop; $R::brandsel = $abrevi} foreach my $brand (@databases_order) { my $dbhl; if ($thisshop == 0) { $dbhl = DBI->connect("DBI:mysql:server$association{$brand};host=127.0.0.1",'root','fbg4ips') or die $DBI::errstr; open DATA, "$folder/../intranet-server$association{$brand}/data/shopid.txt"; while () {my ($shopid, $shoptitle) = split (/\:/,$_); $shopnames{$brand}{$shopid}=$shoptitle} close DATA; } else { #/shop version $dbhl = $dbh; $shopnames{$brand}{$shop{id}} = $shop{name}; } next unless ($thisshop == 0 or ($thisshop > 0 and $brand eq $abrevi)); #/supermode headoffice or not next unless ($R::brandsel eq $brand or $R::brandsel eq "allbrands" or ($thisshop >0 and $brand eq $abrevi)); my $modifier; if ($R::selshop > 0) {$modifier = "and inv.shop_id=$R::selshop";} if ($R::waitronid > 0) {$modifier .= " and inv.waitron_id='$R::waitronid'";} if ($R::selshop*1 == 0) { } else { $results = $dbhl->prepare(" #/count all invoices select inv.shop_id shop_id, count(inv.id) counted from tillinvoices inv, tilltableops tabops, tilltables tabs where inv.stamp >= '$startdate 3:00:00' and inv.stamp <= '$enddate 3:00:00' and (inv.voided is null or inv.voided = 0) and inv.f_status < 100 and tabops.f_status < 100 and tabs.f_status < 100 and tabs.shop_id=inv.shop_id and tabops.shop_id=inv.shop_id $modifier and tabs.id = tabops.table_id and inv.tableops_id = tabops.id and tabs.type not in (2,3,4) group by inv.shop_id ;") or die $dbhl->errstr(); $results->execute() or die $results->errstr(); #/print " $brand
    "; while ($ref = $results->fetchrow_hashref()) { $brandallinvoices{$brand}{$ref->{shop_id}} = $ref->{counted}; $globalbrandcounts{$brand}{allinvoices} += $ref->{counted}; $globalbrandcounts{allbrands}{allinvoices} += $ref->{counted}; #/debug #/print "$brand -> $ref->{shop_id} -> $ref->{counted}
    "; #//debug } #/next unless ($R::selshop > 0 or $R::selshop == -1); $results = $dbhl->prepare(" #/count filled invoices select sf.shop_id, sf.form_id, count(distinct sf.till_invoice) counted from slipfeedback sf, tillinvoices inv where sf.f_status<100 and inv.f_status<100 and sf.shop_id=inv.shop_id $modifier and sf.till_invoice = inv.id and (inv.voided is null or inv.voided = 0) and inv.stamp >= '$startdate 3:00:00' and inv.stamp <= '$enddate 3:00:00' group by sf.shop_id; ;") or die $dbhl->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $brandfillinvoices{$brand}{$ref->{shop_id}}{$ref->{form_id}} += $ref->{counted}; $globalbrandcounts{$brand}{fillinvoices}{$ref->{form_id}} += $ref->{counted}; $globalbrandcounts{allbrands}{fillinvoices}{$ref->{form_id}} += $ref->{counted}; #/ print "$brand -> $ref->{shop_id} -> $ref->{counted}
    "; } $results = $dbhl->prepare(" #/count answers #/ shop_id->form_id->question_id->answer_id = count select sf.shop_id shop_id, sf.form_id form_id, sf.question_id quid, sf.answer_id anid, count(sf.answer_id) counter from slipfeedback sf, tillinvoices inv where sf.f_status < 100 and inv.f_status < 100 and (inv.voided is null or inv.voided = 0) and inv.stamp >= '$startdate 3:00:00' and inv.stamp <= '$enddate 3:00:00' and inv.id = sf.till_invoice and inv.shop_id=sf.shop_id $modifier group by sf.shop_id, sf.question_id, sf.answer_id order by sf.shop_id, quid; ;") or die $dbhl->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $brandcounts{$brand}{$ref->{shop_id}}{$ref->{form_id}}{$ref->{quid}}{$ref->{anid}} = $ref->{counter}; $answersperquestion{$brand}{$ref->{shop_id}}{$ref->{form_id}}{$ref->{quid}} += $ref->{counter}; $globalbrandcounts{$brand}{answercount}{$ref->{form_id}}{$ref->{quid}}{$ref->{anid}} += $ref->{counter}; $globalbrandcounts{allbrands}{answercount}{$ref->{form_id}}{$ref->{quid}}{$ref->{anid}} += $ref->{counter}; $globalbrandcounts{$brand}{answersperquestion}{$ref->{form_id}}{$ref->{quid}} += $ref->{counter}; $globalbrandcounts{allbrands}{answersperquestion}{$ref->{form_id}}{$ref->{quid}} += $ref->{counter}; } if ($R::waitrons == 1) { #/get waitrons with trade $results = $dbhl->prepare(" select w.id wid, w.name wname from waitron w, tillinvoices inv, tilltableops tabops, tilltables tabs where inv.shop_id='$R::selshop' and w.shop_id=inv.shop_id and tabs.shop_id=inv.shop_id and tabops.shop_id=inv.shop_id and inv.waitron_id=w.id and tabops.f_status < 100 and tabs.f_status < 100 and inv.f_status<100 and w.f_status<100 and tabs.id = tabops.table_id and inv.tableops_id = tabops.id and tabs.type not in (2,3,4) and (inv.voided is null or inv.voided = 0) and inv.stamp >= '$startdate 04:00:00' and inv.stamp <= '$enddate 04:00:00' group by inv.waitron_id; ;") or die $dbhl->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $waitrons{$ref->{wid}} = $ref->{wname}; } } } #/ shop criteria matched } #/ SHOP | TOTAL INV COUNT | FILLED INV COUNT | QUESTIONS $temphtml .= " Expand everything

    " if ($thisshop == 0); $temphtml .= ""; if ($R::brandsel eq "allbrands" and $R::selshop == -1) { $temphtml .= ""; $temphtml .= ""; } #/ Brand totals foreach my $brand (@databases_order) { next unless ($thisshop == 0 or ($thisshop >0 and $brand eq $abrevi)); #/supermode headoffice or not $temphtml .= ""; $temphtml .= "" if ($thisshop==0); $temphtml .= ""; if (($R::brandsel eq $brand or $R::brandsel eq "allbrands") and $R::selshop == -1) { $temphtml .= ""; $temphtml .= ""; } #/ Brand totals if ($R::brandsel eq $brand or $R::brandsel eq "allbrands") { foreach my $shopid (sort {$a <=> $b} keys %{$shopnames{$brand}} ) { #/$brandallinvoices{$brand} next if ($R::waitrons == 1 and $R::selshop != $shopid); $temphtml .= ""; $temphtml .= ""; next if (! $brandallinvoices{$brand}{$shopid}); if ( ($R::selshop == $shopid or $R::selshop < 0) and ($R::brandsel eq $brand or $R::brandsel eq "allbrands") ) { $temphtml .= ""; } } #/ selshop $temphtml .= ""; } } #/brandsel $temphtml .= "
    ALL BRANDS TOTALS
    "; foreach my $qnaid (sort keys %questionz) { next if (! $globalbrandcounts{allbrands}{fillinvoices}{$qnaid}); $temphtml .= " FORM: $qnaid (".(1*$globalbrandcounts{allbrands}{fillinvoices}{$qnaid})." of $globalbrandcounts{allbrands}{allinvoices} slips filled) ".pr($globalbrandcounts{allbrands}{fillinvoices}{$qnaid} / $globalbrandcounts{allbrands}{allinvoices} * 100)."%
    "; $temphtml .= "
      "; foreach my $question (sort keys %{$questionz{$qnaid}{questions}} ) { $temphtml .= ""; $temphtml .= ""; $temphtml .= "$questionz{$qnaid}{questions}{$question} "; $temphtml .= " (Answers: ".(1*$globalbrandcounts{allbrands}{answersperquestion}{$qnaid}{$question}).")"; $temphtml .= ""; foreach my $answer_id (sort keys %{$questionz{$qnaid}{answers}{$question}}) { $temphtml .= ""; } $temphtml .= "
      * $questionz{$qnaid}{answers}{$question}{$answer_id}: ".($globalbrandcounts{allbrands}{answercount}{$qnaid}{$question}{$answer_id}*1); $temphtml .= " (".pr($globalbrandcounts{allbrands}{answercount}{$qnaid}{$question}{$answer_id} / $globalbrandcounts{allbrands}{answersperquestion}{$qnaid}{$question}*100)."%)" if ($globalbrandcounts{allbrands}{answersperquestion}{$qnaid}{$question} > 0); $temphtml .= "
      "; } $temphtml .= "

    "; } $temphtml .= "

    $brands{$brand}"; $temphtml .= " | Expand all stores
    BRAND TOTALS
    "; foreach my $qnaid (sort keys %questionz) { next if (! $globalbrandcounts{$brand}{fillinvoices}{$qnaid}); $temphtml .= " FORM: $qnaid (".(1*$globalbrandcounts{$brand}{fillinvoices}{$qnaid})." of $globalbrandcounts{$brand}{allinvoices} slips filled) ".pr($globalbrandcounts{$brand}{fillinvoices}{$qnaid} / $globalbrandcounts{$brand}{allinvoices} * 100)."%
      "; foreach my $question (sort keys %{$questionz{$qnaid}{questions}} ) { $temphtml .= ""; $temphtml .= ""; $temphtml .= "$questionz{$qnaid}{questions}{$question} "; $temphtml .= " (Answers: ".(1*$globalbrandcounts{$brand}{answersperquestion}{$qnaid}{$question}).")"; $temphtml .= ""; foreach my $answer_id (sort keys %{$questionz{$qnaid}{answers}{$question}}) { $temphtml .= ""; } $temphtml .= "
      * $questionz{$qnaid}{answers}{$question}{$answer_id}: ".($globalbrandcounts{$brand}{answercount}{$qnaid}{$question}{$answer_id}*1); $temphtml .= " (".pr($globalbrandcounts{$brand}{answercount}{$qnaid}{$question}{$answer_id} / $globalbrandcounts{$brand}{answersperquestion}{$qnaid}{$question}*100)."%)" if ($globalbrandcounts{$brand}{answersperquestion}{$qnaid}{$question} > 0); $temphtml .= "
      "; } $temphtml .= "

    "; } $temphtml .= "
      $shopnames{$brand}{$shopid}".( ($brandallinvoices{$brand}{$shopid}*1 <= 0) and ($R::selshop*1 == -1) ? " - No bills printed / Not updating" : "" ).($R::waitronid > 0 and $shopid==$R::selshop ? "  REPORT FOR $R::wname" : "")."
     "; foreach my $qnaid (sort keys %questionz) { next if (! $brandfillinvoices{$brand}{$shopid}{$qnaid}); $temphtml .= "
    FORM: $qnaid (".(1*$brandfillinvoices{$brand}{$shopid}{$qnaid})." of $brandallinvoices{$brand}{$shopid} slips filled) "; $temphtml .= pr($brandfillinvoices{$brand}{$shopid}{$qnaid} / $brandallinvoices{$brand}{$shopid} * 100)."%" if ($brandallinvoices{$brand}{$shopid} > 0); $temphtml .= "
      "; foreach my $question (sort keys %{$questionz{$qnaid}{questions}} ) { $temphtml .= ""; $temphtml .= ""; $temphtml .= "$questionz{$qnaid}{questions}{$question} "; $temphtml .= " (Answers: ".(1*$answersperquestion{$brand}{$shopid}{$qnaid}{$question}).")"; $temphtml .= ""; foreach my $answer_id (sort keys %{$questionz{$qnaid}{answers}{$question}}) { $temphtml .= ""; } $temphtml .= "
      * $questionz{$qnaid}{answers}{$question}{$answer_id}: ".($brandcounts{$brand}{$shopid}{$qnaid}{$question}{$answer_id}*1); $temphtml .= " (".pr($brandcounts{$brand}{$shopid}{$qnaid}{$question}{$answer_id} / $answersperquestion{$brand}{$shopid}{$qnaid}{$question}*100)."%)" if ($answersperquestion{$brand}{$shopid}{$qnaid}{$question} > 0); $temphtml .= "
      "; } $temphtml .= "

    "; } $temphtml .= "
  • Show Users "; if ($R::waitrons == 1) { $temphtml .= "
      "; foreach my $wid (sort keys %waitrons) { $temphtml .= "
    • $waitrons{$wid}
      "; } $temphtml .= "
    "; } $temphtml .= "
  • "; #/ ------- } else { $template =~ s/\@title\@/Feedback Report/sgi; $temphtml = getform("period"); $temphtml .= "
    "; $temphtml .= "The default time for the selected period will be 3:00 am"; $temphtml .= ""; $temphtml .= ""; } } if ($R::subaction eq "daily_theory") { if ($R::command eq "Report" and $R::sdate and $R::edate) { $temphtml = "
    "; $template =~ s/\@title\@/THEORETICAL REPORT/sgi; $temphtml .= " Theoretical Stock Usage vs. Actual Stock Usage
    (Variance Report)
    Opening Stock Date: $R::sdate Closing Stock Date: $R::edate

    Date: $R::date | STOCK TYPE: $stocktypes{$database}{$R::stocktype}"; my %ssqldate = dateforsql($R::sdate); my %esqldate = dateforsql($R::edate); my $sdate = "$ssqldate{year}-$ssqldate{month}-$ssqldate{day}"; my $edate = "$esqldate{year}-$esqldate{month}-$esqldate{day}"; my %stockitems; my %skucodes; my %stockcategories; $results = $dbh->prepare(" SELECT si.id,sc.name cat,si.name name, sku FROM stockitems si LEFT JOIN stockcats sc ON sc.id = si.stockcats_id WHERE si.f_status<100 and si.shop_id=$shop{id} and sc.f_status<100 and sc.shop_id=$shop{id} and si.type='$R::stocktype';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockitems{$ref->{id}} = $ref->{name}; $skucodes{$ref->{id}} = $ref->{sku}; $stockcategories{$ref->{id}} = $ref->{cat}; } my %unitprices; my %unitpricesdate; $results = $dbh->prepare(" select DATE_FORMAT(max(pu.date), '%e/%m/%Y') dateformat, pu.stockitems_id sid, substring_index(group_concat(pu.price order by pu.date desc), ',', 1) price from purchases pu, stockitems si where pu.f_status < 100 and si.f_status < 100 and pu.date <= '$edate' and pu.date > DATE_SUB('$edate', INTERVAL 100 day) and si.type='$R::stocktype' and pu.stockitems_id = si.id and si.stockitem != 2 and pu.stockitems_id>0 group by pu.stockitems_id order by max(pu.date);") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $unitprices{$ref->{sid}} = $ref->{price}; $unitpricesdate{$ref->{sid}} = $ref->{dateformat}; } #sql helper my $plutypes; #if ($R::stocktype == 1) { # $plutypes = "1,3"; #} else { # $plutypes = "2"; #} $plutypes = $R::stocktype; #GRAND RETREIVAL #retreive ingredient details my %idetails; $results = $dbh->prepare("select id,name,stockitems_id,units from ritems;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ $idetails{$ref->{id}}{stockitems_id} = $ref->{stockitems_id}; $idetails{$ref->{id}}{units} = $ref->{units}; } my %latestyields; $results = $dbh->prepare(" select id ritem_id, yield from ritems;" ) or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $idetails{$ref->{ritem_id}}{yield} = $ref->{yield}; } #determine RAW usage + RAW prep my %openingstock; my %closingstock; my %closingpreps; #morning column $results = $dbh->prepare("select sum(stockissue.qty) qty, stockissue.stockitems_id from stockissue,stockitems where stockitems.type = '$R::stocktype' and stockissue.stockitems_id = stockitems.id and stockissue.date='$sdate' and stockissue.f_status<100 and stockissue.direction=1 group by stockissue.stockitems_id; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $openingstock{$ref->{stockitems_id}} = $ref->{qty}; } #evening column $results = $dbh->prepare("select sum(stockissue.qty) qty, stockissue.stockitems_id from stockissue,stockitems where stockitems.type = '$R::stocktype' and stockissue.stockitems_id = stockitems.id and stockissue.date='$edate' and stockissue.f_status<100 and stockissue.direction=2 group by stockissue.stockitems_id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $closingstock{$ref->{stockitems_id}} = $ref->{qty}; } if ($R::prep == 1) { #all prep $results = $dbh->prepare("select sum(qty) qty, ingredient_id from stockprep where date >= '$sdate' and date <= '$edate' and ingredient_id > 0 and ingredient_id is not null and shop_id=$shop{id} and f_status<100 group by ingredient_id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $closingpreps{ $idetails{$ref->{ingredient_id}}{stockitems_id} } += $ref->{qty}* ((100+(100-$idetails{$ref->{ingredient_id}}{yield}))/100)* #yield towards stockitem ${$unitalias{ $idetails{$ref->{ingredient_id}}{units} } }[1];; } #recipes prep $results = $dbh->prepare(" select sum(sp.qty) qty, sp.recipe_id recipe_id, sp.recipe_units recipe_units, ry.yield yield from stockprep sp, recipe_yields ry where sp.recipe_units = ry.yield_unit and sp.recipe_id=ry.recipe_id and sp.date >='$sdate' and sp.date <='$edate' and sp.recipe_id > 0 and sp.recipe_id is not null and sp.shop_id=$shop{id} and sp.f_status<100 group by sp.recipe_id,sp.recipe_units; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ my %usage = &recipeingredients($ref->{recipe_id}, $ref->{yield}, {dbh => $dbh} ); foreach my $ingred (keys %usage) { $closingpreps{$idetails{$ingred}{stockitems_id}} += $ref->{qty}*$usage{$ingred}* ((100+(100-$idetails{$ingred}{yield}))/100)* #yield towards stockitem ${$unitalias{ $idetails{$ingred}{units} } }[1];; } } } #RETREIVE PURCHASES FOR THE PERIOD my %purchases; if ($copycstock) { $results = $dbh->prepare(" select pu.stockitems_id stockitems_id, sum(pu.qty) sqty, sum(pu.price) price from purchases pu, stockitems si where pu.f_status < 100 and si.f_status < 100 and pu.date >= '$sdate' and pu.date <= '$edate' and (pu.cnote != 1 or pu.cnote is NULL or pu.cnote = 0) and si.type = '$R::stocktype' and pu.stockitems_id = si.id and si.stockitem != 2 and pu.stockitems_id>0 group by pu.stockitems_id ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ $purchases{$ref->{stockitems_id}} += $ref->{sqty}; } $results = $dbh->prepare(" select pu.stockitems_id stockitems_id, sum(pu.qty) sqty, sum(pu.price) price from purchases pu, stockitems si where pu.f_status < 100 and si.f_status < 100 and pu.date >= '$sdate' and pu.date <= '$edate' and pu.cnote = 1 and si.type = '$R::stocktype' and pu.stockitems_id = si.id and si.stockitem != 2 and pu.stockitems_id>0 group by pu.stockitems_id ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ $purchases{$ref->{stockitems_id}} -= $ref->{sqty}; } } # continue with sales to RAW conversion my %stockuse; my %ingredientuse; my %pluuse; my %returns; my %returns_stockuse; my %onetoone; #TO RETREIVE TOTAL PLU QTYs (based on QTY or YIELD column); $results = $dbh->prepare(" select menu.id pluid, inv.isrefund, menu.stockid stockid, inv.voided voided, sum(qty) totalqty from tillordersdetails ttod, tillorders tto, menu, tillinvoices inv, tilltableops tabops, tilltables where ttod.f_status < 101 and tto.f_status <101 and ttod.stamp >= '$sdate 06:00:00' and ttod.stamp <= DATE_ADD('$edate 06:00:00',INTERVAL 1 DAY) #and menu.type=1 and tabops.id = tto.tableops_id and tilltables.id = tabops.table_id and ttod.orders_id = tto.id and tto.confirm_status=3 and menu.type in ($plutypes) and ttod.menusource = 1 and menu.id = ttod.plu and inv.id = ttod.invoice and (inv.voided is NULL or inv.voided = 2 or inv.voided = 0) group by menu.id, inv.voided, inv.isrefund;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ if ( $ref->{isrefund} == 1 ) { $pluuse{$ref->{pluid}} += $ref->{totalqty}; } else { $pluuse{$ref->{pluid}} += $ref->{totalqty} if ($ref->{voided} != 2); $returns{$ref->{pluid}} += $ref->{totalqty} if ($ref->{voided} == 2); } $onetoone{$ref->{pluid}} = $ref->{stockid}; } # loop the PLUs in the following: foreach my $plu (keys %pluuse) { $results = $dbh->prepare(" SELECT rn.name name, rn.id id, mr.qty qty, ry.yield totaly from recipe_names rn, menu_recipes mr, recipe_yields ry where ry.recipe_id = rn.id and ry.yield_unit = mr.recipe_units and mr.menu_id=$plu and rn.id=mr.recipe_id ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ my %usage = &recipeingredients($ref->{id},$ref->{totaly}/$ref->{qty}, {dbh => $dbh} ); foreach my $ingred (keys %usage) { # THE LiNK $stockuse{$idetails{$ingred}{stockitems_id}} += $pluuse{$plu}*$usage{$ingred}* #usage in the PLU ((100+(100-$idetails{$ingred}{yield}))/100)* #yield towards stockitem ${$unitalias{ $idetails{$ingred}{units} } }[1]; } } #one on one link $stockuse{$onetoone{$plu}} += $pluuse{$plu} if {$onetoone{$plu} > 0}; } #foreach PLU # loop the PLUs in the following: foreach my $plu (keys %returns) { $results = $dbh->prepare(" SELECT rn.name name, rn.id id, mr.qty qty, ry.yield totaly from recipe_names rn, menu_recipes mr, recipe_yields ry where ry.recipe_id = rn.id and ry.yield_unit = mr.recipe_units and mr.menu_id=$plu and rn.id=mr.recipe_id ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ my %usage = &recipeingredients($ref->{id},$ref->{totaly}/$ref->{qty}, {dbh => $dbh} ); foreach my $ingred (keys %usage) { # THE LiNK $returns_stockuse{$idetails{$ingred}{stockitems_id}} += $returns{$plu}*$usage{$ingred}* #usage in the PLU ((100+(100-$idetails{$ingred}{yield}))/100)* #yield towards stockitem ${$unitalias{ $idetails{$ingred}{units} } }[1] ; } } #one on one link $returns_stockuse{$onetoone{$plu}} += $returns{$plu} if {$onetoone{$plu} > 0}; } #foreach PLU $temphtml .= "

    "; # DRAW THE TABLE $temphtml .= ""; $temphtml .= " "; $temphtml .= "" if ($R::prep == 1); $temphtml .= " "; my %combo; $combo{$_} = 1 foreach (keys %openingstock); $combo{$_} = 1 foreach (keys %purchases); #create combined keys array for openingstock and purchases hash tables my $total_variance_value; foreach my $id ( sort {$skucodes{$a} cmp $skucodes{$b}} sort {$stockcategories{$a} cmp $stockcategories{$b}} sort {$stockitems{$a} cmp $stockitems{$b}} keys %combo) { my $totalreturn = $closingstock{$id}+$closingpreps{$id}; my $actualusage = ($openingstock{$id}+$purchases{$id}) - $totalreturn; my $difference = $stockuse{$id} - $actualusage; my $variance = "0"; if ($actualusage) { $variance = 0 - (1 - $stockuse{$id} / $actualusage); $variance *= 100; } if ($R::report_type < 3) { if ($R::report_type == 1) { if ($difference <= 0) { next; } } elsif ($R::report_type == 2) { if ($difference >= 0) { next; } } } $temphtml .= " "; $temphtml .= "" if ($R::prep == 1); $temphtml .= " "; $total_variance_value += $unitprices{$id} * $difference; } $temphtml .= ""; $temphtml .= "
    SKU CODE CATEGORY STOCK ITEM LAST UNIT PRICE OPENING
    STOCK
    PURCHASES TOTAL OPENING CLOSING
    STOCK
    PREPARED
    STOCK
    TOTAL
    AVAILABILITY
    ACTUAL
    USAGE
    GROSS SALES NET SALES GROSS DIFFERENCE
    $skucodes{$id} $stockcategories{$id} $stockitems{$id} $currency ".pr($unitprices{$id})." ".rn3($openingstock{$id})." ".rn3($purchases{$id})." ".rn3($purchases{$id} + $openingstock{$id})." ".rn3($closingstock{$id})." ".rn3($closingpreps{$id})." ".rn3($totalreturn)." ".( $actualusage < 0 ? " $icons{w} " : "" )."".rn3($actualusage )." ".rn3($stockuse{$id})." ".rn3($stockuse{$id} - $returns_stockuse{$id})." ".rn3($difference)." $currency ".pr($unitprices{$id} * $difference)."
    Total variance value: $currency ".pr($total_variance_value)."
    "; $temphtml .= "
    "; } else { $template =~ s/\@title\@/THEORETICAL REPORT/sgi; $temphtml = ""; #/calendar JS $temphtml .= qq~ ~; $temphtml .= "
    "; $temphtml .= " Select Opening Stock date: $icons{cal} Select Closing Stock date: $icons{cal} "; $temphtml .= "
    Select Stock Type:
    "; $temphtml .= "
    Select report type: "; $temphtml .= "
    Show Prep. Stock
    "; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } } #daily teoritical stock if ($R::subaction eq "plu_staffmeals") { if ($R::command eq "Report") { $temphtml = "
    "; $template =~ s/\@title\@/PLU STAFF PROMO REPORT/sgi; my ($startdate, $enddate, $starttime, $endtime); my (%sqldate,%sqldate2); %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate2 = dateforsql($R::enddate); $enddate = $sqldate2{year}."-".$sqldate2{month}."-".$sqldate2{day}; $results = $dbh->prepare(" select tods.name name, inv.id invoice, tods.qty qty, round(tods.price,2) avg_unitprice, tods.qty*tods.price total, waitron.name waitron, supervisor.name supervisor, tods.stamp stamp from tillordersdetails tods, tillorders tod, tilltableops tabops, tilltables tabs, tillinvoices inv, waitron, supervisor where waitron.f_status<100 and supervisor.f_status<100 and waitron.id = tods.waitron_id and supervisor.id = inv.supervised_by and inv.id = tods.invoice and tods.shop_id=$shop{id} and supervisor.shop_id=$shop{id} and waitron.shop_id=$shop{id} and tod.shop_id=tods.shop_id and tabops.shop_id=tods.shop_id and tabs.shop_id=tods.shop_id and tabs.type=4 #/staff meals and tod.tableops_id = tabops.id and tods.orders_id=tod.id and tabops.table_id=tabs.id and tods.plutype=1 and tods.stamp >= '$startdate 3:00:00' and tods.stamp <= '$enddate 3:00:00' order by tods.stamp desc; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $temphtml .= "$startdate - $enddate"; my $total = 0; $temphtml .= $table{start}; $temphtml .= "
    STAMP / InvoiceUserSuperuserItemQty Unit Price total
    $ref->{stamp} Invoice {invoice}','','status=yes,scrollbars=yes,width=700,height=400');\">$ref->{invoice}$ref->{waitron}$ref->{supervisor}$ref->{name} $ref->{qty} $ref->{avg_unitprice} $ref->{total}
    Total $total
    "; $temphtml .= ""; $temphtml .= "" if $R::typecolumn; $temphtml .= ""; $temphtml .= "" if $R::grossuprice; $temphtml .= "" if $R::discount; $temphtml .= "" if $R::nettotal; if ($R::gpreport) { $temphtml .= " "; } $temphtml .= ""; my $totaltotals; if (1) { foreach my $mcatid (reverse sort {$mcattotals{$a} <=> $mcattotals{$b}} keys %mcatnames) { my $linetotals; $temphtml .= ""; foreach my $pluname (reverse sort {$cat_plus{pluprices}{$mcatid}{$a}*$cat_plus{allpluqty}{$mcatid}{$a} <=> $cat_plus{pluprices}{$mcatid}{$b}*$cat_plus{allpluqty}{$mcatid}{$b}} keys %{$mcatplus{$mcatid}} ) { #%{$plus{plunames}} $plustotal += $cat_plus{plutotal}{$mcatid}{$pluname}; #~ print "$pluname # $cat_plus{allpluqty}{$mcatid}{$pluname} x $cat_plus{pluprices}{$mcatid}{$pluname}|
    "; #~ my $up = 0; #~ $up = $cat_plus{plutotal}{$mcatid}{$pluname} / $cat_plus{pluqty}{$mcatid}{$pluname} if ($cat_plus{pluqty}{$mcatid}{$pluname} != 0); #~ my $ttt; #~ foreach my $unitprice ( keys %{ $cat_plus{plunames}{$mcatid}{$pluname} }) { #~ foreach my $discount ( keys %{ $cat_plus{plunames}{$mcatid}{$pluname}{$unitprice} } ) { #~ $ttt->{$unitprice} += $cat_plus{pluqty}{$mcatid}{$pluname}{$unitprice}{$discount} * ($unitprice - $discount); #~ } #~ } foreach my $unitprice (keys %{ $cat_plus{plunames}{$mcatid}{$pluname} }) { #~ sort {$ttt->{$a} <=> $ttt->{$b}} foreach my $discount (keys %{ $cat_plus{plunames}{$mcatid}{$pluname}{$unitprice} } ) { my $qty = $cat_plus{pluqty}{$mcatid}{$pluname}{$unitprice}{$discount}; #logit("= $discount,$qty,$mcatid,$pluname,$unitprice\n"); ###2020-11-18 Incl VAT # if ($plutax{$pluname} > 0) { # $unitprice = $unitprice * ((100 + $cvat)/100); # } my $netlinetotal = $qty * ($unitprice - $discount); #net my $grosslinetotal = $qty * $unitprice; ##$grosslinetotal = $grosslinetotal * ((100 + $cvat)/100); if ($R::search) { #search totals foreach my $words (@searchedwords) { #~ print "WORDS: |$words| $netlinetotal
    "; if ($pluname =~ /$words/i) { $wordsturnover{$words}{net} += $netlinetotal; $wordsturnover{$words}{discounts} += $discount * $qty; $wordsturnover{$words}{gross} += $grosslinetotal; } } } $temphtml .= ""; $temphtml .= "" if $R::typecolumn; $temphtml .= ""; $temphtml .= "" if $R::grossuprice; $temphtml .= "" if $R::discount; $temphtml .= "" if $R::nettotal; if ($R::gpreport) { #directly linked to stock item: my $total_excl; if ($plutax{$pluname} > 0) { $total_excl = $netlinetotal / ( (100 + $cvat)/100 ); } else { $total_excl = $netlinetotal; } my $buyingprice = $cat_plucost{$mcatid}{$pluname}; #2020-11-18 let's include VAT #$buyingprice = $buyingprice * ((100 + $cvat)/100); my $cost_percent = (($buyingprice * $qty) / $total_excl) * 100 if $total_excl != 0; my $gp_percent = ($total_excl - $buyingprice*$qty) / $total_excl * 100 if $total_excl != 0; #if ($total_excl < $buyingprice && $gp_percent > 0) {#2020-03-08 # $gp_percent *= -1; #} $linetotals->{buyingprice} += $buyingprice * $qty; $linetotals->{total_excl} += $total_excl; $totaltotals->{buyingprice} += $buyingprice * $qty; $totaltotals->{total_excl} += $total_excl; $temphtml .= " "; #$buyingprice * ((100 + $cvat)/100) } $temphtml .= ""; $linetotals->{qty} += $qty; $linetotals->{discount} += $discount * $qty; $linetotals->{net} += $netlinetotal; $linetotals->{gross} += $grosslinetotal; $totaltotals->{qty} += $qty; $totaltotals->{discount} += $discount * $qty; $totaltotals->{net} += $netlinetotal; $totaltotals->{gross} += $grosslinetotal; } } } $temphtml .= ""; $temphtml .= "" if $R::typecolumn; $temphtml .= ""; $temphtml .="" if $R::grossuprice; $temphtml .="" if $R::discount; $temphtml .="" if $R::nettotal; if ($R::gpreport) { my $gp_total = ($linetotals->{total_excl} - $linetotals->{buyingprice}) / $linetotals->{total_excl} * 100 if ($linetotals->{total_excl} != 0); if ($linetotals->{total_excl} < $linetotals->{buyingprice} && $gp_total > 0) { $gp_total *= -1; } $temphtml .= " "; } $temphtml .=""; } } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "" if $R::typecolumn; $temphtml .= ""; $temphtml .= "" if $R::grossuprice; $temphtml .= "" if $R::discount; $temphtml .= "" if $R::nettotal; if ($R::gpreport) { my $gp_total = ($totaltotals->{total_excl} - $totaltotals->{buyingprice}) / $totaltotals->{total_excl} * 100 if ($totaltotals->{total_excl}); $temphtml .= " "; } $temphtml .= ""; foreach my $words (@searchedwords) { if ($wordsturnover{$words}{gross}) { $temphtml .= ""; } } } elsif ($menu_db) { $template =~ s/\@title\@/PLU SALES REPORT/sgi; #calendar JS $temphtml .= qq~ ~; $temphtml .= "
    SKU/PLU CodeDescriptionTypeQTYSelling Price (Incl)DiscountNet Sales (Incl)
    After Discount
    Total Sales
    - Net (Excl)
    Unit Cost (Excl) Total Cost (Excl) Gross ProfitTotal Sales (Incl)
    $mcatnames{$mcatid}
    $cat_plucodes{$mcatid}{$pluname}$pluname$stocktypes{$database}{$cat_plutypes{$mcatid}{$pluname}} $qty ".pr($unitprice)."".pr($discount * $qty)."".pr($netlinetotal)."".pr($total_excl)." ".pr($buyingprice)." ".pr($buyingprice * $qty )." ".pr($gp_percent)." %".(pr($grosslinetotal))."
    Totals   $linetotals->{qty}  ".pr($linetotals->{discount})."".pr($linetotals->{net})."".pr($linetotals->{total_excl})." ".pr($linetotals->{buyingprice})." ".pr($gp_total)." %".pr($linetotals->{gross})."
    GRAND TOTAL
    Totals   $totaltotals->{qty}  ".pr($totaltotals->{discount})."".pr($totaltotals->{net})."".pr($totaltotals->{total_excl})." ".pr($totaltotals->{buyingprice})." ".pr($gp_total)." %".pr($totaltotals->{gross})."
    SEARCHED KEYWORD: \"$words\" Gross: ".pr($wordsturnover{$words}{gross})." Discounts: ".pr($wordsturnover{$words}{discounts})." Net: ".pr($wordsturnover{$words}{net})."
    "; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } #else - choise $temphtml .= ""; $temphtml .= ""; # $temphtml .= "Subquery database selection: $menu_db"; $temphtml .= ""; } #/ plu sales if ($R::subaction eq "timecontrol") { $temphtml = "
    "; if ($R::command eq "Report" and $R::startdate and $R::enddate) { my (%staff, %allstaff, %staffdetails); #/ prepare waitrons my $subresults = $dbh->prepare("SELECT * FROM employees WHERE f_status<100 and shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $allstaff{$subref->{id}} = $subref->{name}; $staffdetails{passid}{$subref->{id}} = $subref->{passid}; $staffdetails{address}{$subref->{id}} = $subref->{address}; $staffdetails{phone}{$subref->{id}} = $subref->{phone}; $staff{$subref->{id}} = $subref->{name} if ($subref->{active} == 1); } my %sqldate = dateforsql($R::startdate); my $startdate = "$sqldate{year}-$sqldate{month}-$sqldate{day}"; my $starttime = "$R::shh:$R::smm:$R::sss"; %sqldate = dateforsql($R::enddate); my $enddate = "$sqldate{year}-$sqldate{month}-$sqldate{day}"; my $endtime = "$R::ehh:$R::emm:$R::ess"; $template =~ s/\@title\@/Clock System/sgi; my %tailing_mode = ('start'=>$R::start_tail,'end'=>$R::end_tail); #/whether we should use the full slice or intersection with our start/end time my %ignore_tails = ('start'=>$R::ignore_start_tail,'end'=>$R::ignore_end_tail); #/whether we should ignore intersected periods (normaly only the start one, because it belongs to a previous day) my $startstamp = "$startdate $starttime"; my $endstamp = "$enddate $endtime"; my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); $temphtml .= "Requested report period: from $R::startdate $starttime to $R::enddate $endtime

    "; $temphtml .= "
  • First cropped session was ignored!
    " if($ignore_tails{start}); $temphtml .= "
  • Last cropped session was ignored!
    " if($ignore_tails{end}); $temphtml .= "
  • Using full first cropped session!
    " if($tailing_mode{start}); $temphtml .= "
  • Using full last cropped session!
    " if($tailing_mode{end}); $temphtml .= "


    "; foreach my $employee (@R::employee_id) { $temphtml .= "
  • Filter SKU / PLU Code
    "; $temphtml .= " (eg \"AST*\" will match all SKU codes starting with AST"; $temphtml .= "
    Select PLU type / name(s)
    "; $temphtml .= "PLU types: "; $temphtml .= "
    OR
    SEARCH FOR ITEM NAME(S):
    Eg. Mineral water + Tonic Water
    (leave blank if you want list of PLUs from certain type - the list above)"; $temphtml .= "
    Select Table Range
    "; $temphtml .= " Query only tables
    from "; my @tablenumbers; my %tabledescriptions; my $subresults = $dbh->prepare(" SELECT number,description,type FROM tilltables WHERE active=1 and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { push @tablenumbers, $subref->{number}; $tabledescriptions{$subref->{number}} = " Type: ".$tilltabletype{$subref->{type}}; $tabledescriptions{$subref->{number}} .= " | ".$subref->{description} if ($subref->{description}); } $temphtml .= ""; $temphtml .= " to "; $temphtml .= ""; $temphtml .= "
    Select User
    "; my (%waitrons, %allwaitrons); # prepare waitrons $subresults = $dbh->prepare("SELECT id, name,active FROM waitron WHERE f_status<100 and shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $allwaitrons{$subref->{id}} = $subref->{name}; $waitrons{$subref->{id}} = $subref->{name} if ($subref->{active} == 1); } $temphtml .= "Users: "; $temphtml .= "
    Select Client Filter
    "; my %allclients; # prepare waitrons $subresults = $dbh->prepare("SELECT id, substr(name,1,20) name,clientgroup,code FROM $sharedclients.tillclients WHERE f_status<100 and shop_id=$sharedclients_shopid ;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $allclients{$subref->{id}} = "CODE: $subref->{code} CLIENT: $subref->{clientgroup} -> $subref->{name}"; } $temphtml .= "Clients (Optional):

    Client/Company Filter (Optional):

    Client Folder Filter (Optional):

    Client Code (Optional):

    Use \"%\" as a wildcard. Example: \"micro%\" will find anything that starts with \"micro\". "; $temphtml .= "
    Select Menu Category
    "; $temphtml .= " Query all categories
    "; $temphtml .= ""; #$temphtml .= "
    Query Local Menu PLUs
    "; $temphtml .= "
    Select Part of Day
    Time of Day Start (HH:MM:SS) : : 00 Time of Day End (HH:MM:SS) : : 00
    Additional Report Options
    GP Report Discount Gross U.Price Nett Total Stock Type
    Select Period
    Start date: $icons{cal}
    Start time (HH:MM:SS) : : 00
    End date: $icons{cal}
    END time (HH:MM:SS) : : 00
    Recommended way of use:
    01/03/2004 04:00:00 - 02/03/2004 04:00:00
    (will capture all the trade for 01/03/2004)

    Note: time varies between 00:00:00 to 24:00:00
    "; my $employee_id = $employee; $results = $dbh->prepare(" select id, operation, date(stamp) date, time(stamp) time,stamp from employeesaccess where employee_id = $employee_id and shop_id = $shop{id} and stamp >= '$startstamp' and stamp <= '$endstamp' order by stamp asc ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); my @slice; my %times; while ($ref = $results->fetchrow_hashref()) { push @slice, $ref->{id}; $times{dt}{$ref->{id}} = $ref->{date}; $times{tm}{$ref->{id}} = $ref->{time}; $times{op}{$ref->{id}} = $ref->{operation}; } #/prepare full pears of operations my @peers = (); my %intersections; if ($times{op}{$slice[0]} == 2) { #/ this is the case where we intersect at the begin #/determine closing stamp that follows opening stamp $results = $dbh->prepare(" select date(stamp) date, time(stamp) time,stamp from employeesaccess where employee_id = $employee_id and shop_id = $shop{id} and stamp < '".$times{dt}{$slice[0]}." ".$times{tm}{$slice[0]}."' #/end stamp limit 1 ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($tailing_mode{start}==1) { #/this is quite unusual to happen push @peers, [$ref->{date}, $ref->{time}]; #/instead , if mode = capture heads $intersections{start} = 0; } else { #/ intersection of the start #/ $temphtml .= "intersect - at start\n"; $intersections{start} = 1; push @peers, [$startdate, $starttime]; } } foreach my $id (@slice) { push @peers, [$times{dt}{$id},$times{tm}{$id}]; } if ($times{op}{$slice[$#slice]} == 1) { #/determine closing stamp that follows opening stamp $results = $dbh->prepare(" select date(stamp) date, time(stamp) time,stamp from employeesaccess where employee_id = $employee_id and shop_id = $shop{id} and stamp > '".$times{dt}{$slice[$#slice]}." ".$times{tm}{$slice[$#slice]}."' #/end stamp limit 1 ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($tailing_mode{end} == 1) { #/this is more likely to happen if ($ref->{date} ne "" and $ref->{time} ne "") { push @peers, [$ref->{date}, $ref->{time}]; #/instead, if mode = capture tails $intersections{end} = 0; } else { #/time = NOW! my ( $Day, $Month, $Year, $Hour,$Minute,$Second ); $Day = $tm->mday; $Month = ($tm->mon+1); $Year = ($tm->year + 1900); $Hour = $tm->hour; $Minute = $tm->min; $Second = $tm->sec; push @peers, ["$Year-$Month-$Day", "$Hour:$Minute:$Second"]; #/$temphtml .= "$Second, $Minute, $Hour, $Day, $Month, $Year, $WeekDay, $DayOfYear, $IsDST"; $intersections{end} = 2; } } else { #/intersection #/$temphtml .= "intersect - at end\n"; push @peers, [$enddate, $endtime]; $intersections{end} = 1; } } if ($ignore_tails{start} and $intersections{start}) { shift @peers; shift @peers; } if ($ignore_tails{end} and $intersections{end}) { pop @peers; pop @peers; } #/peers complete, convert to epoch seconds my @epochseconds; my @nonroundedepochseconds; my @epochtitles; my @roundepochtitles; my %prevrecord; my $transactions = 0; my $startsession = 1; foreach my $peer (@peers) { my ($hr, $min, $sec, $day, $month, $year); ($year,$month,$day) = split("-",@{$peer}[0]); ($hr,$min,$sec) = split(":",@{$peer}[1]); #/$sec my $epoch = timelocal(0, $min, $hr, $day, $month-1, $year); push @nonroundedepochseconds, $epoch; #/rounding start #/if ($transactions > 0) { #/ more than one session if ($startsession == 1) { #/rounding start session if ($min > 0 and $min < 15) { $epoch += (15 - $min)*60; } elsif ($min > 15 and $min < 30) { $epoch += (30 - $min)*60; } elsif ($min > 30 and $min < 45) { $epoch += (45 - $min)*60; } elsif ($min > 45 and $min < 60) { $epoch += (60 - $min)*60; } $startsession = -1; } else { #/rounding end session if ($min > 0 and $min < 15) { $epoch -= $min*60; } elsif ($min > 15 and $min < 30) { $epoch -= ($min*60 - 15*60) } elsif ($min > 30 and $min < 45) { $epoch -= ($min*60 - 30*60) } elsif ($min > 45 and $min < 60) { $epoch -= ($min*60 - 45*60) } if($prevrecord{epoch} > $epoch) {$epoch = $prevrecord{epoch}} $startsession = 1; } push @epochtitles, "$day $months[$month-1] $year @{$peer}[1]"; #/epoch to time; my $tmt = localtime($epoch); my $datetime = sprintf("%02d-%02d-%04d %02d:%02d:%02d",$tmt->mday,$tmt->mon,($tmt->year + 1900), $tmt->hour, $tmt->min, $tmt->sec); push @roundepochtitles, $datetime; $prevrecord{epoch} = $epoch; #/$epoch=0; #/rounding end push @epochseconds, $epoch; } my @epochperiods; #/ peers of session times. ei one record represent the time for one session my $totalepoch; #/my $i; $temphtml .= "Report for $allstaff{$employee_id}
    Employee ID: $staffdetails{passid}{$employee}, Address: $staffdetails{address}{$employee}, Phone: $staffdetails{phone}{$employee}
    "; $temphtml .= "
  • Cropped start session!
    " if($intersections{start}); $temphtml .= "
  • Cropped end session!
    " if($intersections{end}); $temphtml .= "

    "; if (! $R::brief) { $temphtml .= ""; } my $logintime; for (my $i=1;$i<=$#epochseconds;$i+=2) { #/ 0,1;2,3;4,5 #/push @epochperiods, [$epochseconds[$i-1],$epochseconds[$i]]; if (! $R::brief) { $temphtml .= "" if ( substr($epochtitles[$i-1],0,2) ne substr($epochtitles[$i-3],0,2) ); $temphtml .= ""; } $totalepoch += $epochseconds[$i] - $epochseconds[$i-1]; $logintime = $nonroundedepochseconds[$i-1]; } $temphtml .= "
    Session StartSession EndDuration
    Date: ".(substr($epochtitles[$i-1],0,11))."
    $roundepochtitles[$i-1] $roundepochtitles[$i] ".( ($intersections{end} == 2 and $i == $#epochseconds) ? " (now!) " : "")." ".stringtime($epochseconds[$i] - $epochseconds[$i-1])."

    " if (! $R::brief) ; $temphtml .= "Total duration time: ".stringtime($totalepoch).( $intersections{end} == 2 ? " (Still working!) " : "")."\n"; if ($intersections{end} == 2) { $temphtml .= "


    Forced Clock-out Actions: "; $temphtml .= "
    Close Session with custom time (click to specify)
    "; } #/$temphtml .= $#epochperiods; $temphtml .= "


  • "; } } elsif ($R::command eq "forceout") { #/epoch to time; my $tmt = localtime($R::logintime); my $lastdatetime = sprintf("%02d-%02d-%04d %02d:%02d:%02d",$tmt->mday,$tmt->mon,($tmt->year + 1900), $tmt->hour, $tmt->min, $tmt->sec); my (%staff, %allstaff,%staffdetails); #/ prepare waitrons my $subresults = $dbh->prepare("SELECT * FROM employees WHERE f_status<100 and shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $allstaff{$subref->{id}} = $subref->{name}; $staffdetails{passid}{$subref->{id}} = $subref->{passid}; $staffdetails{address}{$subref->{id}} = $subref->{address}; $staffdetails{phone}{$subref->{id}} = $subref->{phone}; $staff{$subref->{id}} = $subref->{name} if ($subref->{active} == 1); } $template =~ s/\@title\@/Forced Clock-out/sgi; $temphtml .= "Forced clock-out
    "; if ($R::subcommand eq "") { $temphtml .= "Employee name: $allstaff{$R::employee_id}
    Employee ID: $staffdetails{passid}{$R::employee_id}, Address: $staffdetails{address}{$R::employee_id}, Phone: $staffdetails{phone}{$R::employee_id}
    Current session started: $lastdatetime (not rounded)"; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "

    Please specify date for the clock-out:"; $temphtml .= qq~ ~; $temphtml .= " $icons{cal}"; $temphtml .= "

    Please specify time for the clock-out: (HH:MM:SS)
    "; $temphtml .= " "; $temphtml .= ""; } elsif ($R::subcommand eq "submit") { my %sqldate = dateforsql($R::date); my $lastepoch = $R::logintime; my $newepoch = timelocal($R::ess, $R::emm, $R::ehh, $sqldate{day}, $sqldate{month}, $sqldate{year}); my $newduration = $newepoch - $lastepoch; my $maxduration = 10*(60*60); #/10 hours #/epoch to time; my $tmt = localtime($newepoch); my $newdatetime = sprintf("%02d-%02d-%04d %02d:%02d:%02d",$tmt->mday,$tmt->mon,($tmt->year + 1900), $tmt->hour, $tmt->min, $tmt->sec); if ($newduration < $maxduration and $newduration > 0) { #/check whether $R:datetime is > $logintime $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    Forced Clock-out acknowledge form
    Session start: $lastdatetime
    Session end: $newdatetime
    Session duration: ".stringtime($newduration)."
    Employee $allstaff{$R::employee_id}
    Employee ID: $staffdetails{passid}{$R::employee_id}, Address: $staffdetails{address}{$R::employee_id}, Phone: $staffdetails{phone}{$R::employee_id}

    Employee Signature: ____________________________

    Manager Name: ____________________________


    Manager Signature: ____________________________


    "; $temphtml .= " "; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } elsif ($newduration < 0) { #/negative duration $temphtml .= "The clock-out time is less than the clock-in time.
    "; $temphtml .= ""; } else { #/over duration $temphtml .= "The duration of this session exceeded 10 hours limit.
    "; $temphtml .= "The duration you've specified is ".stringtime($newduration)."
    "; $temphtml .= ""; } } elsif ($R::subcommand eq "Confirm_signing_of_this_form") { #/verify whether this session is still open $subresults = $dbh->prepare("select operation from employeesaccess where shop_id=$shop{id} and employee_id=$R::employee_id order by id desc limit 1;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); if ($subref->{operation} == 1) { $subresults = $dbh->prepare("insert into employeesaccess (shop_id,employee_id,stamp,operation) values ($shop{id},$R::employee_id,'$R::logouttime',2);") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $temphtml .= "The form has been successfuly accepted and the clock-out action has been stored."; } else { $temphtml .= " An error occured: Session already closed or invalid session selected. "; } } #/end subcommand } else { my (%staff, %allstaff); #/ prepare waitrons my $subresults = $dbh->prepare("SELECT id, name,active FROM employees WHERE f_status<100 and shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $allstaff{$subref->{id}} = $subref->{name}; $staff{$subref->{id}} = $subref->{name} if ($subref->{active} == 1); } $temphtml .= "
    "; $temphtml .= "Please select staff member:

    "; $temphtml .= "
    "; my $formhtml; $template =~ s/\@title\@/Timer report/sgi; $formhtml = getform("period", undef); $temphtml .= $formhtml; $temphtml .= "

    edit and report off days
    Select start time: (HH:MM:SS)

    Select end time: (HH:MM:SS)
    Remove cropped first session?
    Remove cropped last session?

    Show full cropped first session?
    Show full cropped last session?

    Brief report "; $temphtml .= "
    Click here for explanation on the options

    "; $temphtml .= ""; } #/else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } #/timecontrol if ($R::subaction eq "sysinfo"){ $template =~ s/\@title\@/System Information/sgi; $temphtml = "
    "; if ($R::command eq "details") { $temphtml .= "Intranet System Update details for $R::day/$R::month/$R::year, $shop{name}

    "; $temphtml .= $table{start}; $temphtml .= "EventDate and time"; $results = $dbh->prepare("select status, date_format(stamp, '%e %M %Y, %W %T') datetime from updatelog where shop_id=$shop{id} and DAYOFMONTH(stamp)=$R::day and month(stamp) =$R::month and year(stamp) =$R::year order by stamp desc;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $temphtml .= "$ref->{status}$ref->{datetime}"; } $temphtml .= $table{end}; $temphtml .= "

    "; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= "*** WELCOME TO FBG INTRANET SYSTEM INFORMATION ***"; $temphtml .= "
    [UPDATES REPORT] for $shop{name}
    "; $temphtml .= $table{start}; $temphtml .= "Date"; $results = $dbh->prepare("select distinct DAYOFMONTH(stamp) day, month(stamp) month, year(stamp) year, DATE_FORMAT(stamp, '%e %M %Y, %W') date from updatelog where shop_id=$shop{id} order by stamp desc;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $temphtml .= "$ref->{date}{day}&month=$ref->{month}&year=$ref->{year}\">more..."; } $temphtml .= $table{end}; } $temphtml .= "
    "; } #/sysinfo - system status if ($R::subaction eq "unitprice"){ $temphtml = "
    "; if ($R::command eq "Report" and @R::stockitem) { my ($startdate, $enddate); my %sqldate; my $datequery; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; if ($R::startdate and $R::enddate) { $datequery="and pu.date>='$startdate' and pu.date<='$enddate'" } else { $datequery=""; } $template =~ s/\@title\@/Unit Price Report/sgi; $temphtml .= "Unit price summary for $shop{name}
    for the period: $R::startdate - $R::enddate


    "; my %stockdetails; $results = $dbh->prepare(" SELECT si.id,concat(sc.name,' - ',si.name) name, bin, units FROM stockitems si LEFT JOIN stockcats sc ON sc.id = si.stockcats_id WHERE si.f_status<100 and si.shop_id=$shop{id} and sc.f_status<100 and sc.shop_id=$shop{id} and si.type=$R::rtype; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockdetails{name}{$ref->{id}} = $ref->{name}; $stockdetails{bin}{$ref->{id}} = $ref->{bin}; $stockdetails{units}{$ref->{id}} = $ref->{units}; } #/report table $temphtml .= $table{start}; if (! $R::groupitems) { my $grosstotal = 0; $temphtml .= " Date Supplier Item Invoice QTY Unit Price Total "; my $sortcriteria = "order by su.name asc,pu.date desc"; if ($R::sortitems) { $sortcriteria = "order by si.name asc,pu.date desc"; } $results = $dbh->prepare(" select pu.price price, DATE_FORMAT(pu.date, '%e %M %Y') date, su.name supplier, pu.cnote, pu.stockitems_id stockitems_id, pu.qty, pu.invoice from purchases pu, suppliers su, stockitems si where si.id = pu.stockitems_id and pu.supplier_id=su.id $datequery and pu.f_status < 100 and su.f_status < 100 and pu.shop_id=$shop{id} and su.shop_id=pu.shop_id and pu.stockitems_id in (".join(",",@R::stockitem).") and su.name like ? $sortcriteria;") or die $dbh->errstr(); $results->execute("%"."$R::suppsearch"."%") or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($ref->{cnote} > 0) { $ref->{qty} = $ref->{qty} * -1; } my $linetotal = $ref->{qty} * $ref->{price}; $grosstotal += $linetotal; $temphtml .= " $ref->{date} $ref->{supplier} $stockdetails{name}{$ref->{stockitems_id}}, $units{$stockdetails{units}{$ref->{stockitems_id}}} $ref->{invoice} $ref->{qty} $currency ".pr($ref->{price})." $currency ".pr($linetotal)." "; } $temphtml .= "Totals:"; $temphtml .= " - - - - - - $currency ".pr($grosstotal)." "; } else { $temphtml .= " Item QTY Avg. Unit Price Total "; my $grosstotal; $results = $dbh->prepare(" select si.name, pu.stockitems_id, ROUND(SUM(pu.qty * pu.price) / SUM(pu.qty) , 2) avgprice , SUM(pu.qty) qty, ROUND(SUM(pu.qty * pu.price),2) total from purchases pu, suppliers su, stockitems si where si.id = pu.stockitems_id and pu.supplier_id=su.id $datequery and pu.f_status < 100 and pu.cnote != 1 and pu.stockitems_id in (".join(",",@R::stockitem).") and su.name like ? group by si.id order by si.name asc") or die $dbh->errstr(); $results->execute("%"."$R::suppsearch"."%") or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $grosstotal += $ref->{total}; $temphtml .= " $stockdetails{name}{$ref->{stockitems_id}}, $units{$stockdetails{units}{$ref->{stockitems_id}}} $ref->{qty} $currency ".pr($ref->{avgprice})." $currency ".pr($ref->{total})." "; } $temphtml .= " Total - - $currency ".pr($grosstotal)." "; } $temphtml .= $table{end}; } else { my $formhtml; $template =~ s/\@title\@/Unit Price Report/sgi; $temphtml .= &ajaxfunctions; $temphtml .= "Please select the following, and press Report.

    "; $temphtml .= ""; $onload = " submitsrch(); "; $temphtml .= "
    "; #/just border $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    STOCK TYPE:
    Stock Category Filter:
    Stock Item Name Filter:
    LOADING STOCK ITEMS... "; $temphtml .= "
    Supplier Name Filter: "; $temphtml .= "
    "; $temphtml .= "

    "; $temphtml .= " Sort by Item Description (or by Supplier, Date if not checked)

    "; $temphtml .= " Group by item and display average unit price

    "; $formhtml = getform("period", undef); $temphtml .= $formhtml; } #/else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } #/unitprice if ($R::subaction eq "commission") { $temphtml = "
    "; if ($R::command eq "Report") { my $waitrons; my ($startdate, $enddate); my %sqldate; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; $waitrons = join (",",@R::waitron); $template =~ s/\@title\@/Service Fees Report/sgi; $temphtml .= "Service Fees for $shop{name}
    for the period: $R::startdate - $R::enddate


    "; #/report table $temphtml .= $table{start}; $temphtml .= " Name Date S.fee Status"; #/ #/SERVICE FEES $results = $dbh->prepare("select w.name name, DATE_FORMAT(dc.date, '%e %M %Y') date, dci.s_fee s_fee, w.active active from waitron w, dcash dc, dcashitems dci where w.shop_id=$shop{id} and w.f_status<100 and dc.shop_id=$shop{id} and dc.f_status<100 and dci.shop_id=$shop{id} and dci.f_status<100 and dci.dcash_id=dc.id and dci.waitron_id = w.id and dci.s_fee>0 and dc.date>='$startdate' and dc.date<='$enddate' and w.id in ($waitrons) order by w.name,dc.date;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $temphtml .= " $ref->{name} $ref->{date} $ref->{s_fee} $wstatus{$ref->{active}}"; } #//sfees while $temphtml .= $table{end}; $temphtml .= "
    "; } else { my (%waitrons, %allwaitrons); #/ prepare waitrons my $subresults = $dbh->prepare("SELECT id, name,active FROM waitron WHERE f_status<100 and shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $allwaitrons{$subref->{id}} = $subref->{name}; $waitrons{$subref->{id}} = $subref->{name} if ($subref->{active} == 1); } $temphtml .= "
    "; $temphtml .= "Please select waitron(s):



    "; $temphtml .= "
    "; my $formhtml; $template =~ s/\@title\@/Service Fees Report/sgi; $formhtml = getform("period", undef); $temphtml .= $formhtml; $temphtml .= "
    "; } #/else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } #/commission - sfees if ($R::subaction eq "pettycash") { my ($grandtotal); $temphtml = "
    "; if ($R::command eq "Report") { my $rstocktype; my %invoicestotal; my ($startdate, $enddate); my %sqldate; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; $template =~ s/\@title\@/Petty Cash Report/sgi; $temphtml .= "Petty cash summary for $shop{name}
    for the period: $R::startdate - $R::enddate


    "; #/report table $temphtml .= $table{start}; $temphtml .= " Supplier/Name Invoice Item/Description Amount"; my (@pdates,%fdates, %pettycashpercash); #/fetch cashup dates $results = $dbh->prepare("SELECT distinct date, DATE_FORMAT(date, '%e %M %Y') mydate, pettycash from dcash where date>='$startdate' and date<='$enddate' and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { push @pdates, $ref->{date}; $fdates{$ref->{date}} = $ref->{mydate}; $pettycashpercash{$ref->{date}} = $ref->{pettycash}; } my (%waitrons, %allwaitrons); #/ prepare waitrons my $subresults = $dbh->prepare("SELECT id, name,active FROM waitron WHERE f_status<100 and shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $allwaitrons{$subref->{id}} = $subref->{name}; $waitrons{$subref->{id}} = $subref->{name} if ($subref->{active} == 1); } foreach my $cashdate (@pdates) { my $daytotal; $temphtml .= "Pettycash for $fdates{$cashdate}
    Pettycash as per cashup: $currency ".pr($pettycashpercash{$cashdate})." "; #/ #/PURCHASES $results = $dbh->prepare("SELECT org_price,stockitems_id,othertype, description, wholesaler_id, supplier_id, invoice from purchases where date ='$cashdate' and type=3 and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { my ($suptable,$supid,$suptype, $useshop); if (! $ref->{supplier_id}) {$suptable = 'wholesalers'; $supid=$ref->{wholesaler_id};$suptype=1; } else {$suptable = 'suppliers';$useshop="and shop_id=$shop{id}";$supid=$ref->{supplier_id};$suptype=2;} #/fetch supplier/wholesaler $subresults = $dbh->prepare(" SELECT name FROM $suptable WHERE id=$supid $useshop and f_status<100;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $temphtml .= " $subref->{name}"; my $stockname; if ($ref->{stockitems_id}) { $subresults = $dbh->prepare(" SELECT name FROM stockitems WHERE id=$ref->{stockitems_id} and shop_id=$shop{id} and f_status<100;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $stockname = $subref->{name} ; } else { $stockname=$ref->{description}; } $temphtml .= "$ref->{invoice}"; $temphtml .= "$stockname"; $temphtml .= " $currency $ref->{org_price}"; $temphtml .= ""; $daytotal += $ref->{org_price}; } #//purchases while #/LOANS $results = $dbh->prepare("SELECT * from loans where date ='$cashdate' and shop_id=$shop{id} and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $temphtml .= ""; my $name; if ($ref->{loantype} == 1) { $name = $allwaitrons{$ref->{waitron_id}}; $name .= "*" if (! exists $waitrons{$ref->{waitron_id}}); $name .= " (waitron)"; } else {$name=$ref->{wageperson}." (other) [$wagetypes{$ref->{wagetype}}]"} $temphtml .= "$name$ref->{description}$currency $ref->{amount}"; $temphtml .= ""; $daytotal += $ref->{amount}; } #/loans while #/CREDITORS $results = $dbh->prepare("SELECT * from creditors where date ='$cashdate' and shop_id=$shop{id} and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $temphtml .= ""; my ($suptable,$supid,$suptype, $useshop); if (! $ref->{supplier_id}) {$suptable = 'wholesalers'; $supid=$ref->{wholesaler_id};$suptype=1; } else {$suptable = 'suppliers';$useshop="and shop_id=$shop{id}";$supid=$ref->{supplier_id};$suptype=2;} #/fetch supplier/wholesaler $subresults = $dbh->prepare(" SELECT name FROM $suptable WHERE id=$supid $useshop and f_status<100;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $temphtml .= "$subref->{name} [credited]"; $temphtml .= "$ref->{description}$currency $ref->{amount}"; $temphtml .= ""; $daytotal += $ref->{amount}; } #/loans while $temphtml .= "Total as per pettycash : $currency ".pr($daytotal).""; $grandtotal += $daytotal; } #/ foreach cash day $temphtml .= "Total pettycash for the period: $currency ".pr($grandtotal).""; $temphtml .= $table{end}; $temphtml .= "
    "; } else { my $formhtml; $template =~ s/\@title\@/Petty Cash Report/sgi; $formhtml = getform("period", undef); $temphtml .= $formhtml; } #/else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } #/petty if ($R::subaction eq "plu_voids") { my ($grandtotal); $temphtml = "
    "; if ($R::command eq "Report" and $R::type and $R::startdate and $R::enddate) { my %voidtypes = (1=>'Voids',2=>'Returns'); my %totals; my ($startdate, $enddate); my %sqldate; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; $template =~ s/\@title\@/Voids Report/sgi; $temphtml .= "$voidtypes{$R::type} summary for $shop{name}
    for the period: $R::startdate - $R::enddate


    "; #/report table $temphtml .= $table{start}; $temphtml .= " Invoice Date & time Void Reason User Supervisor Amount"; my (@pdates,%fdates, %pettycashpercash); #/fetch cashup dates $results = $dbh->prepare(" select inv.id invoice, date_format(inv.stamp, '%e %M %Y, %W %T') timestamp, inv.void_reason void_reason, wa.name waitron, su.name supervisor, round(sum(tods.qty*tods.price),2) total from tillinvoices inv, waitron wa, supervisor su, tillordersdetails tods where inv.shop_id=$shop{id} and wa.shop_id=$shop{id} and su.shop_id=$shop{id} and tods.shop_id=$shop{id} and inv.f_status < 100 and tods.f_status < 100 and wa.f_status<100 and su.f_status<100 and inv.stamp>='$startdate' and inv.stamp<='$enddate' and inv.supervised_by = su.id and inv.waitron_id=wa.id and tods.invoice=inv.id and inv.voided = $R::type group by inv.id order by inv.id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $totals{1} = 0; while ($ref = $results->fetchrow_hashref()) { $temphtml .= "
    {invoice}','','status=yes,scrollbars=yes,width=700,height=400');\">$ref->{invoice} $ref->{timestamp} $ref->{void_reason} $ref->{waitron} $ref->{supervisor} ".pr($ref->{total}).""; $totals{1} += $ref->{total}; } $temphtml .= " Total $voidtypes{$R::type} for the period ".pr($totals{1}).""; $temphtml .= $table{end}; $temphtml .= "
    "; } else { my $formhtml; $template =~ s/\@title\@/Petty Cash Report/sgi; $formhtml = getform("period", undef); $temphtml .= "Voids Returns "; $temphtml .= $formhtml; } #/else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } if ($R::subaction eq "cost") { $temphtml = "
    "; if ($R::command eq "Itemized Report") { my $reportdate = $q->param("date"); $template =~ s/\@title\@/Total Cost Report: $stocktypes{$database}{$R::rtype}/sgi; #/determine data from previous stock take - one before the selection my %current; my %previous; my %between; my $filter_sql; if ($R::filter) { $filter_sql = "and si.name like \"%$R::filter%\""; } #/get all stock in memory: name, bin, units my %stockdetails; $results = $dbh->prepare(" SELECT si.id,concat(sc.name,' - ',si.name) name, bin, units FROM stockitems si LEFT JOIN stockcats sc ON sc.id = si.stockcats_id WHERE si.f_status<100 and si.shop_id=$shop{id} and sc.f_status<100 and sc.shop_id=$shop{id} and si.type=$R::rtype; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $stockdetails{name}{$ref->{id}} = $ref->{name}; $stockdetails{bin}{$ref->{id}} = $ref->{bin}; $stockdetails{units}{$ref->{id}} = $ref->{units}; } $results = $dbh->prepare(" select cs.last_pid, DATE_FORMAT(cs.date, '%e %M %Y %T') mydate, cs.date, date(cs.date) date_only, cs.date>='2005-06-20' realistic, sum(cs.value) value, sum(cs.pvalue) pvalue from cstock cs, stockitems si where cs.stocktype=$R::rtype and cs.date<='$reportdate' and cs.shop_id=$shop{id} and cs.f_status<100 and si.shop_id=$shop{id} and si.f_status<100 and cs.stockitems_id=si.id $filter_sql group by date ORDER BY date desc limit 2;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #/this closing stock - The selected from drop down $ref = $results->fetchrow_hashref(); $current{display_date} = $ref->{mydate}; $current{date} = $ref->{date}; $current{date_only} = $ref->{date_only}; $current{last_pid} = $ref->{last_pid}; $current{value} = $ref->{value}; $current{credit_notes} = $ref->{pvalue}; $current{realistic} = $ref->{realistic}; #/previous date closing stock - second result $ref = $results->fetchrow_hashref(); $previous{display_date} = $ref->{mydate}; $previous{date} = $ref->{date}; $previous{date_only} = $ref->{date_only}; $previous{last_pid} = $ref->{last_pid}; $previous{value} = $ref->{value}; $previous{credit_notes} = $ref->{pvalue}; $temphtml .= "DATE OF SELECTED CLOSING STOCK: $current{display_date}
    "; $temphtml .= "DATE OF PREVIOUS CLOSING STOCK: $previous{display_date}
    "; #/retreive individual values - previous stock $results = $dbh->prepare(" select cs.stockitems_id, cs.value, cs.pvalue, cs.qty,cs.debited_pid,cs.credit_left from cstock cs, stockitems si where cs.stocktype=$R::rtype and cs.date='$previous{date}' and cs.shop_id=$shop{id} and cs.f_status<100 and si.shop_id=$shop{id} and si.f_status<100 $filter_sql and cs.stockitems_id=si.id; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $previous{i_debited_pid}{$ref->{stockitems_id}} = $ref->{debited_pid}; $previous{i_credit_left}{$ref->{stockitems_id}} = $ref->{credit_left}; $previous{i_value}{$ref->{stockitems_id}} = $ref->{value}; $previous{i_qty}{$ref->{stockitems_id}} = $ref->{qty}; $previous{i_credit_notes}{$ref->{stockitems_id}} = $ref->{pvalue}; } #/retreive individual values - this stock $results = $dbh->prepare(" select cs.stockitems_id, cs.value, cs.pvalue, cs.qty,cs.debited_pid,cs.credit_left from cstock cs, stockitems si where cs.stocktype=$R::rtype and cs.date='$current{date}' and cs.shop_id=$shop{id} and cs.f_status<100 and si.shop_id=$shop{id} and si.f_status<100 $filter_sql and cs.stockitems_id=si.id; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $current{i_debited_pid}{$ref->{stockitems_id}} = $ref->{debited_pid}; $current{i_credit_left}{$ref->{stockitems_id}} = $ref->{credit_left}; $current{i_value}{$ref->{stockitems_id}} = $ref->{value}; $current{i_qty}{$ref->{stockitems_id}} = $ref->{qty}; $current{i_credit_notes}{$ref->{stockitems_id}} = $ref->{pvalue}; } #/purchases in between $results = $dbh->prepare(" SELECT sum(pu.qty*pu.price) value, si.id stockitems_id, sum(pu.qty) qty from purchases pu, stockitems si where pu.id>'$previous{last_pid}' and pu.id<='$current{last_pid}' and si.stockitem <> 2 and si.type = '$R::rtype' and (pu.cnote != 1 or pu.cnote is null or pu.cnote = 0) and si.id=pu.stockitems_id and pu.shop_id=$shop{id} and pu.f_status<100 and si.shop_id=pu.shop_id and si.f_status<100 $filter_sql group by si.id; "); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $between{i_purchases}{$ref->{stockitems_id}} = $ref->{value}; $between{i_purchases_qty}{$ref->{stockitems_id}} = $ref->{qty}; $between{purchases} += $ref->{value}; } #/credit notes in between $results = $dbh->prepare(" SELECT sum(pu.qty*pu.price) value, si.id stockitems_id, sum(pu.qty) qty from purchases pu, stockitems si where pu.id>'$previous{last_pid}' and pu.id<='$current{last_pid}' and si.stockitem <> 2 and si.type = '$R::rtype' and pu.cnote = 1 and si.id=pu.stockitems_id and pu.shop_id=$shop{id} and pu.f_status<100 and si.shop_id=pu.shop_id and si.f_status<100 $filter_sql group by si.id; "); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $between{i_creditnotes}{$ref->{stockitems_id}} = $ref->{value}; $between{i_creditnotes_qty}{$ref->{stockitems_id}} = $ref->{qty}; $between{i_creditnotes}{$ref->{stockitems_id}} = $current{i_credit_notes}{$ref->{stockitems_id}} if ($current{i_credit_notes}{$ref->{stockitems_id}}); $between{creditnotes} += $between{i_creditnotes}{$ref->{stockitems_id}}; $between{creditnotes_entered} += $ref->{value}; } #/ TURNOVER #/ TURNOVER #$stocktypes{$database}{$R::rtype} #and dc.date >= '$previous{date}' #and dc.date < '$current{date}' #/ Sunday #GROSS AND DEDUCTABLES NET $results = $dbh->prepare(" select sum(dci.s_fee) sfee_total, sum(dcinv.dcinv_turnover_total - dcinv.vat_total) turnover_total from dcash, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 where dcash.date >= '$previous{date_only}' and dcash.date < '$current{date_only}' #/ tuesday ??????? and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 # group by dci.id # order by dci.id ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $total_turnover = $ref->{turnover_total}; $results = $dbh->prepare(" select sum(dci.s_fee) sfee_total from dcash, dcashitems dci where dcash.date >= '$previous{date_only}' and dcash.date < '$current{date_only}' #/ tuesday ??????? and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $total_service_fees = $ref->{sfee_total}; #COSTCENTER TURNOVER $subresults = $dbh->prepare(" select sum(dctov.turnover_total) costcenter_turnover, sum(dctov.vat_total) costcenter_vat, sum(dctov.returns_total) costcenter_returns, sum(dctov.staffpromo_total) costcenter_staffpromo, sum(dctov.discounts_total) costcenter_discounts from dcash, dcashitems dci, dcashinvoices dcinv, dcashturnover dctov where dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcinv.shop_id=dcash.shop_id and dctov.shop_id=dcash.shop_id and dcash.f_status<100 and dci.f_status<100 and dcinv.f_status<100 and dctov.f_status<100 and dcash.date >= '$previous{date_only}' and dcash.date < '$current{date_only}' #/ tuesday ??????? and dctov.costcenter_id=$R::rtype and dcash.id = dci.dcash_id and dci.id = dcinv.dcashitems_id and dcinv.id = dctov.dcashinvoices_id"); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $costcenter_vat = $subref->{costcenter_vat}; my $costcenter_net = $subref->{costcenter_turnover}; my $costcenter_returns = $subref->{costcenter_returns}; my $costcenter_staffpromo = $subref->{costcenter_staffpromo}; my $costcenter_discounts = $subref->{costcenter_discounts}; #factors my $costcenter_factor = $costcenter_net/$total_turnover if ($total_turnover); my $costcenter_sfee = $costcenter_factor*$total_service_fees; my %calc1; $calc1{turnover} = $costcenter_net; $between{turnover} = $calc1{turnover}; $calc1{noni_turnover} = $costcenter_net - $costcenter_sfee - $costcenter_returns - $costcenter_staffpromo - $costcenter_discounts; my $maxusage; #/itemized calculation my @compiled_ids; @compiled_ids = keys %{$current{i_value}}; foreach my $id ( @compiled_ids ) { $between{i_available}{$id} = $previous{i_value}{$id} + ($between{i_purchases}{$id}-$between{i_creditnotes}{$id}); $between{i_available_qty}{$id} = $previous{i_qty}{$id} + ($between{i_purchases_qty}{$id}-$between{i_creditnotes_qty}{$id}); $between{i_usage}{$id} = $between{i_available}{$id} - $current{i_value}{$id}; $between{i_usage_qty}{$id} = $between{i_available_qty}{$id} - $current{i_qty}{$id}; $between{total_usage} += $between{i_usage}{$id}; $maxusage = $between{i_usage}{$id} if ($maxusage < $between{i_usage}{$id}); } $temphtml .= $table{startp}; $temphtml .= ""; $temphtml .= "Previous Stock" if ($R::sel_co1); $temphtml .= "Purchases" if ($R::sel_co2); $temphtml .= "Credit Notes" if ($R::sel_co3); $temphtml .= "Total Availability" if ($R::sel_co4); $temphtml .= "Stock on Hand" if ($R::sel_co5); $temphtml .= "Usage" if ($R::sel_co6); $temphtml .= " Cost" if ($R::sel_co7); $temphtml .= ""; my @colorz = blender("#FFFFFF","#0000FF",255); my @sortedids; @sortedids = sort {$between{i_usage}{$b} <=> $between{i_usage}{$a}} @compiled_ids; my $incrementalusage; my $lastincrementalusage; my $cnt; foreach my $id ( @sortedids ) { $cnt++; $incrementalusage += $between{i_usage}{$id}; $temphtml .= "$stockdetails{name}{$id}, $units{$stockdetails{units}{$id}}"; $temphtml .= " (
    param("date")."&rtype=$R::rtype &sel_co1=$R::sel_co1 &sel_co2=$R::sel_co2 &sel_co3=$R::sel_co3 &sel_co4=$R::sel_co4 &sel_co5=$R::sel_co5 &sel_co6=$R::sel_co6 &sel_co7=$R::sel_co7 &purdetails=$id#kotva\">purchases details)" if ($current{realistic} and $previewpurchases); if ($R::purdetails == $id and rn3($between{i_usage_qty}{$id}) > 0 ) { #/$temphtml .= "
    #/
    stockitems_id = $id [".join("+",keys %{$purchases_for_use{$id}})."]
    #/debited start pid $fifodetails{$id}{debited_pid} creditleft $fifodetails{$id}{credit_left} #/
    #/debited end pid $fiforesultz{$id}{debited_pid} creditleft $fiforesultz{$id}{credits_left}"; my %purdetails; my %bottomline; $results = $dbh->prepare(" select * from purchases where shop_id=$shop{id} and f_status<100 and (cnote = 0 or cnote is null or cnote != 1) and stockitems_id='$id' and id >= '$previous{i_debited_pid}{$id}' and id <= '$current{i_debited_pid}{$id}';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($previous{i_debited_pid}{$id} != $current{i_debited_pid}{$id}) { if ($ref->{id} == $previous{i_debited_pid}{$id}) { $purdetails{$ref->{id}}{qty} = $previous{i_credit_left}{$id}; } elsif ($ref->{id} == $current{i_debited_pid}{$id}) { $purdetails{$ref->{id}}{qty} = $ref->{qty} - $current{i_credit_left}{$id}; } else { $purdetails{$ref->{id}}{qty} = $ref->{qty}; } } else { $purdetails{$ref->{id}}{qty} = $previous{i_credit_left}{$id} - $current{i_credit_left}{$id}; } $purdetails{$ref->{id}}{invoice} = $ref->{invoice}; $purdetails{$ref->{id}}{date} = $ref->{date}; $purdetails{$ref->{id}}{price} = $ref->{price}; } #/$temphtml .= "
    ID $id -> Last PID = $current{last_pid}
    #/debpid $previous{i_debited_pid}{$id} cred $previous{i_credit_left}{$id}
    #/debpid $current{i_debited_pid}{$id} cred $current{i_credit_left}{$id}"; my %fifo_credit_notes; if ($between{i_creditnotes_qty}{$R::purdetails} > 0) { #/$temphtml.= "
    CSTOCK STORED CNOTES VALUE: $current{i_credit_notes}{$R::purdetails}
    "; my $tocredit = $between{i_creditnotes_qty}{$R::purdetails}; my @deletepids; foreach my $pid (sort {$a<=>$b} keys %purdetails) { if (rn3($tocredit) > $purdetails{$pid}{qty}) { $tocredit -= $purdetails{$pid}{qty}; $fifo_credit_notes{$R::purdetails} += $purdetails{$pid}{qty}*$purdetails{$pid}{price}; delete $purdetails{$pid}; } else { $purdetails{$pid}{qty} -= $tocredit; $fifo_credit_notes{$R::purdetails} += $tocredit*$purdetails{$pid}{price}; $tocredit = 0; } } } $temphtml .= ""; $temphtml .= "

    Calculated FIFO cnotes value = $currency $fifo_credit_notes{$R::purdetails}
    "; $temphtml .= ""; foreach my $pid (sort {$a<=>$b} keys %purdetails) { $bottomline{usage_value} += $purdetails{$pid}{qty}*$purdetails{$pid}{price}; $bottomline{qty} += $purdetails{$pid}{qty}; $temphtml .= " $previous{last_pid} ? "class=ccel" : "")."> "; } $temphtml .= ""; $temphtml .= "
    Invoice Date Unit Price Usage Usage Value
    $purdetails{$pid}{invoice} $purdetails{$pid}{date} $currency ".pr($purdetails{$pid}{price})." ".rn3($purdetails{$pid}{qty})." $units{$stockdetails{units}{$R::purdetails}} $currency ".pr($purdetails{$pid}{qty}*$purdetails{$pid}{price})."
    Total avg. $currency "; $temphtml .= pr($bottomline{usage_value}/$bottomline{qty}) if ($bottomline{qty}>0); $temphtml .=" ".rn3($bottomline{qty})." $units{$stockdetails{units}{$R::purdetails}} $currency ".pr($bottomline{usage_value})."
    "; } #/ if invoice details when usage elsif ($R::purdetails == $id and rn3($between{i_usage_qty}{$id}) <= 0) { $temphtml .= "

    NO USAGE TO SHOW..."; } $temphtml .= ""; $temphtml .= ""; #/ if ($R::sel_co1) $temphtml .= "
    Previous Stock
    QTY: $previous{i_qty}{$id} $units{$stockdetails{units}{$id}}
    VALUE: $currency ".pr($previous{i_value}{$id})."" if ($R::sel_co1); $temphtml .= "
    Purchases
    QTY: $between{i_purchases_qty}{$id} $units{$stockdetails{units}{$id}}
    VALUE: $currency ".pr($between{i_purchases}{$id})."" if ($R::sel_co2);; $temphtml .= "
    Credit Notes
    QTY: $between{i_creditnotes_qty}{$id} $units{$stockdetails{units}{$id}}
    VALUE: $currency ".pr($between{i_creditnotes}{$id})."" if ($R::sel_co3); $temphtml .= "
    Total Availability
    QTY: $between{i_available_qty}{$id} $units{$stockdetails{units}{$id}}
    VALUE: $currency ".pr($between{i_available}{$id})."" if ($R::sel_co4); $temphtml .= "
    Stock on Hand
    QTY: $current{i_qty}{$id} $units{$stockdetails{units}{$id}}
    VALUE: $currency ".pr($current{i_value}{$id})."" if ($R::sel_co5); $temphtml .= "
    Usage
    QTY: ".rn3($between{i_usage_qty}{$id})." $units{$stockdetails{units}{$id}}
    VALUE: $currency ".pr($between{i_usage}{$id})."" if ($R::sel_co6); if ($R::sel_co7) { $temphtml .= " "; $temphtml .= "
    Overall "; if ($between{turnover}) {$temphtml .= (pr($incrementalusage/$between{turnover}*100));} $temphtml .= " %
    This item "; $temphtml .= (pr($between{i_usage}{$id}/$between{turnover}*100)) if ($between{turnover}); $temphtml .= " %"; } } $temphtml .= $table{end}; #/totals - bottom $between{available} = $previous{value} + ($between{purchases}-$between{creditnotes}); $between{usage} = $between{available} - $current{value}; $temphtml .= "

    "; $temphtml .= "" if ($R::filter); $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; if ($between{turnover}>0) { $between{cost} = $between{usage} / $between{turnover} * 100; $temphtml .= ""; } else { $temphtml .= ""; } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; if ($calc1{noni_turnover}>0) { $calc1{noni_cost} = $between{usage} / $calc1{noni_turnover} * 100; $temphtml .= ""; } else { $temphtml .= ""; } $temphtml .= "
    Filter \"$R::filter\"
    Opening Stock $currency ".pr($previous{value})."

    Purchases since
    last closing stock
    $currency ".pr($between{purchases})."
    Credit notes since
    last closing stock
    $currency ".pr($between{creditnotes})."
    Total Availability
    $currency ".pr($between{available} )."
    Stock on Hand $currency ".pr($current{value})."

    Usage $currency ".pr($between{usage})."
    Turnover $currency ".pr($between{turnover})."
    COST ".pr($between{cost})." %
    COST Error!!!

    Non-Income Turnover $currency ".pr($calc1{turnover} - $calc1{noni_turnover})."
    Returns $currency ".pr($costcenter_returns)."
    Discounts $currency ".pr($costcenter_discounts)."
    Staff Promo $currency ".pr($costcenter_staffpromo)."
    Service Fees $currency ".pr($costcenter_sfee)."
    NET Turnover $currency ".pr($calc1{noni_turnover})."
    NET COST TO COMPANY ".pr($calc1{noni_cost})." %
    COST TO COMPANY Error!!!
    "; } elsif ($R::command eq "Totals Report") { my $reportdate = $q->param("date"); $template =~ s/\@title\@/Total Cost Report: $stocktypes{$database}{$R::rtype}/sgi; #/determine data from previous stock take - one before the selection my %current; my %previous; my %between; $results = $dbh->prepare(" select last_pid, DATE_FORMAT(date, '%e %M %Y %T') mydate, date, date(date) date_only, sum(value) value, sum(pvalue) pvalue from cstock where stocktype=$R::rtype and date<='$reportdate' and shop_id=$shop{id} and f_status<100 group by date ORDER BY date desc limit 2;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #/this closing stock - The selected from drop down $ref = $results->fetchrow_hashref(); $current{display_date} = $ref->{mydate}; $current{date} = $ref->{date}; $current{date_only} = $ref->{date_only}; $current{last_pid} = $ref->{last_pid}; $current{value} = $ref->{value}; $current{credit_notes} = $ref->{pvalue}; #/previous date closing stock - second result $ref = $results->fetchrow_hashref(); $previous{display_date} = $ref->{mydate}; $previous{date} = $ref->{date}; $previous{date_only} = $ref->{date_only}; $previous{last_pid} = $ref->{last_pid}; $previous{value} = $ref->{value}; $previous{credit_notes} = $ref->{pvalue}; $temphtml .= "DATE OF SELECTED CLOSING STOCK: $current{display_date}
    "; $temphtml .= "DATE OF PREVIOUS CLOSING STOCK: $previous{display_date}
    "; #/purchases in between $results = $dbh->prepare(" SELECT sum(pu.qty*pu.price) value from purchases pu, stockitems si where pu.id>'$previous{last_pid}' and pu.id<='$current{last_pid}' and si.stockitem <> 2 and si.type = '$R::rtype' and (pu.cnote != 1 or pu.cnote is null or pu.cnote = 0) and si.id=pu.stockitems_id and pu.shop_id=$shop{id} and pu.f_status<100 and si.shop_id=pu.shop_id and si.f_status<100; "); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $between{purchases} = $ref->{value}; #/credit notes in between $results = $dbh->prepare(" SELECT sum(pu.qty*pu.price) value from purchases pu, stockitems si where pu.id>'$previous{last_pid}' and pu.id<='$current{last_pid}' and si.stockitem <> 2 and si.type = '$R::rtype' and pu.cnote = 1 and si.id=pu.stockitems_id and pu.shop_id=$shop{id} and pu.f_status<100 and si.shop_id=pu.shop_id and si.f_status<100; "); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $between{creditnotes} = $ref->{value}; $between{creditnotes_entered} = $ref->{value}; #/ignored if there is pvalues stored $between{creditnotes} = $current{credit_notes} if ($current{credit_notes} > 0); #/ TURNOVER #$stocktypes{$database}{$R::rtype} #and dc.date >= '$previous{date}' #and dc.date < '$current{date}' #/ Sunday #GROSS AND DEDUCTABLES NET $results = $dbh->prepare(" select sum(dci.s_fee) sfee_total, sum(dcinv.dcinv_turnover_total - dcinv.vat_total) turnover_total from dcash, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 where dcash.date >= '$previous{date_only}' and dcash.date < '$current{date_only}' #/ tuesday ??????? and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 # group by dci.id # order by dci.id ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $total_turnover = $ref->{turnover_total}; $results = $dbh->prepare(" select sum(dci.s_fee) sfee_total from dcash, dcashitems dci where dcash.date >= '$previous{date_only}' and dcash.date < '$current{date_only}' #/ tuesday ??????? and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $total_service_fees = $ref->{sfee_total}; #COSTCENTER TURNOVER $subresults = $dbh->prepare(" select sum(dctov.turnover_total) costcenter_turnover, sum(dctov.vat_total) costcenter_vat, sum(dctov.returns_total) costcenter_returns, sum(dctov.staffpromo_total) costcenter_staffpromo, sum(dctov.discounts_total) costcenter_discounts from dcash, dcashitems dci, dcashinvoices dcinv, dcashturnover dctov where dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcinv.shop_id=dcash.shop_id and dctov.shop_id=dcash.shop_id and dcash.f_status<100 and dci.f_status<100 and dcinv.f_status<100 and dctov.f_status<100 and dcash.date >= '$previous{date_only}' and dcash.date < '$current{date_only}' #/ tuesday ??????? and dctov.costcenter_id=$R::rtype and dcash.id = dci.dcash_id and dci.id = dcinv.dcashitems_id and dcinv.id = dctov.dcashinvoices_id"); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $costcenter_vat = $subref->{costcenter_vat}; my $costcenter_net = $subref->{costcenter_turnover}; my $costcenter_returns = $subref->{costcenter_returns}; my $costcenter_staffpromo = $subref->{costcenter_staffpromo}; my $costcenter_discounts = $subref->{costcenter_discounts}; #factors my $costcenter_factor = $costcenter_net/$total_turnover if ($total_turnover); my $costcenter_sfee = $costcenter_factor*$total_service_fees; my %calc1; $calc1{turnover} = $costcenter_net; $between{turnover} = $calc1{turnover}; $calc1{noni_turnover} = $costcenter_net - $costcenter_sfee - $costcenter_returns - $costcenter_staffpromo - $costcenter_discounts; $between{available} = $previous{value} + ($between{purchases}-$between{creditnotes}); $between{usage} = $between{available} - $current{value}; $temphtml .= "

    "; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; if ($between{turnover}>0) { $between{cost} = $between{usage} / $between{turnover} * 100; $temphtml .= ""; } else { $temphtml .= ""; } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; if ($calc1{noni_turnover}>0) { $calc1{noni_cost} = $between{usage} / $calc1{noni_turnover} * 100; $temphtml .= ""; } else { $temphtml .= ""; } $temphtml .= "
    Opening Stock $currency ".pr($previous{value})."

    Purchases since
    last closing stock
    $currency ".pr($between{purchases})."
    Credit notes since
    last closing stock
    $currency ".pr($between{creditnotes})."
    Total Availability
    $currency ".pr($between{available} )."
    Stock on Hand $currency ".pr($current{value})."

    Usage $currency ".pr($between{usage})."
    Turnover $currency ".pr($between{turnover})."
    COST ".pr($between{cost})." %
    COST Error!!!

    Non-Income Turnover $currency ".pr($calc1{turnover} - $calc1{noni_turnover})."
    Returns $currency ".pr($costcenter_returns)."
    Discounts $currency ".pr($costcenter_discounts)."
    Staff Promo $currency ".pr($costcenter_staffpromo)."
    Service Fees $currency ".pr($costcenter_sfee)."
    NET Turnover $currency ".pr($calc1{noni_turnover})."
    NET COST TO COMPANY ".pr($calc1{noni_cost})." %
    COST TO COMPANY Error!!!
    "; } else { $temphtml .= &ajaxfunctions; #rtype; $template =~ s/\@title\@/Cost Report/sgi; $temphtml .= " $table{start} Select type of report: STOCK TYPE: DATES "; $temphtml .= "
    Itemized Report, specify desired columns
    Filter:
    "; $temphtml .= "
    "; $temphtml .= $table{end}; } #/else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } #/costreport if ($R::subaction eq "topwaitron") { $temphtml = "
    "; if ($R::command eq "Report") { my ($startdate, $enddate); my %sqldate; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; $template =~ s/\@title\@/Top User Report/sgi; $temphtml .= "
    "; $temphtml .= "Top User for $shop{name}
    for the period: $R::startdate - $R::enddate

    "; $results = $dbh->prepare(" select waitron.name name, sum( (dcinv.dcinv_turnover_total - dcinv.vat_total) - (dcinv.staffpromo_total - dcinv.staffpromo_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.discount_total - dcinv.discount_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.returns_total - dcinv.returns_total/dcinv.dcinv_turnover_total*dcinv.vat_total) ) - dci.s_fee AS netto, sum( (dcinv.dcinv_turnover_total - dcinv.vat_total) - (dcinv.staffpromo_total - dcinv.staffpromo_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.discount_total - dcinv.discount_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.returns_total - dcinv.returns_total/dcinv.dcinv_turnover_total*dcinv.vat_total) ) / sum(dcinv.covers) AS avg, sum(dcinv.covers) avgcvr from waitron, dcash, dcashitems dci, dcashinvoices dcinv where dci.waitron_id=waitron.id and dcash.date >= '$startdate' and dcash.date <= '$enddate' and dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 and dcinv.covers > 0 and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and waitron.shop_id = dcash.shop_id and waitron.f_status<100 and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 group by waitron.id order by avg desc; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $temphtml .= $table{startp}; $temphtml .= " Place Name Turnover Covers Avg. Headspend "; my $place; while ($ref = $results->fetchrow_hashref()) { $place ++; $temphtml .= " $place $ref->{name} ".pr($ref->{netto})." $ref->{avgcvr} ".pr($ref->{avg}).""; } $temphtml .= $table{end}; $temphtml .= "

    "; } else { my $formhtml; $template =~ s/\@title\@/Top User Report/sgi; $formhtml = getform("period", undef); $temphtml .= $formhtml; } #/else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } #/ top waiter if ($R::subaction eq "invoices") { $temphtml = "
    "; if ($R::command eq "Report") { my $rstocktype; my %invoicestotal; my ($startdate, $enddate); my %sqldate; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; if ($R::rtype<=2) { $template =~ s/\@title\@/Invoice Report: $stocktypes{$database}{$R::rtype}/sgi; $rstocktype = "and si.type=$R::rtype"; } else { $template =~ s/\@title\@/Invoice Report: Food & liqour/sgi; $rstocktype = "and si.type<=2"; } $temphtml .= "Invoice summary for $shop{name}
    for the period: $R::startdate - $R::enddate


    "; #report table $temphtml .= $table{start}; #break $temphtml .= "Suppliers"; $results = $dbh->prepare("SELECT * from suppliers where f_status<100 and shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); my %supplier_totals; my $prevsupplier; my $icount; while ($ref = $results->fetchrow_hashref()) { my $thtml; if ($prevsupplier > 0 and $prevsupplier != $ref->{id} and $icount) { $temphtml .= " SUPPLIER TOTAL"; $temphtml .= " $currency".pr($supplier_totals{novat}).""; $temphtml .= " $currency".pr($supplier_totals{vat}).""; $temphtml .= ""; $temphtml .= "$currency".pr($supplier_totals{discount}).""; $temphtml .= " $currency".pr($supplier_totals{invoice}).""; $temphtml .= ""; %supplier_totals = (); $prevsupplier = $ref->{id}; } $icount = 0; $thtml .= "$ref->{name}"; $thtml .= "InvoiceDateTotal (excl. TAX)Total (incl. TAX)c.noteDiscountInvoice Total"; $subresults = $dbh->prepare("SELECT DISTINCT invoice, cnote, DATE_FORMAT(date, '%e %M %Y') date from purchases where date>='$startdate' and date<='$enddate' and supplier_id='$ref->{id}' and f_status<100 and shop_id=$shop{id} ORDER BY invoice;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while($subref = $subresults->fetchrow_hashref()) { $icount++; my $itotal; my $vat; my $discount; my $discountvat; #getting vat $subresults1 = $dbh->prepare("SELECT sum((price*(100/(100-discount)))*qty*($cvat/100)) vat from purchases where vat=1 and invoice='$subref->{invoice}' and date>='$startdate' and date<='$enddate' and supplier_id='$ref->{id}' and cnote=$subref->{cnote} and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); $vat = $subref1->{vat}; #getting discount vat total $subresults1 = $dbh->prepare("SELECT sum( (price*(100/(100-discount))*(discount/100))*qty*($cvat/100) ) vat from purchases where vat=1 and invoice='$subref->{invoice}' and date>='$startdate' and date<='$enddate' and supplier_id='$ref->{id}' and cnote=$subref->{cnote} and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); $discountvat = $subref1->{vat}; #getting discount total $subresults1 = $dbh->prepare("SELECT sum(((price*(100/(100-discount)))*discount/100)*qty) discount from purchases where invoice='$subref->{invoice}' and date>='$startdate' and date<='$enddate' and supplier_id='$ref->{id}' and cnote=$subref->{cnote} and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); $discount = $subref1->{discount}; #getting nonvat total $subresults1 = $dbh->prepare("SELECT sum((price*(100/(100-discount)))*qty) price from purchases where invoice='$subref->{invoice}' and date>='$startdate' and date<='$enddate' and supplier_id='$ref->{id}' and cnote=$subref->{cnote} and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); if (! $subref->{cnote}) { $invoicestotal{novat} += $subref1->{price}; $invoicestotal{vat} += $subref1->{price}+$vat; $invoicestotal{discount} += $discount+$discountvat; $invoicestotal{invoice} += ($subref1->{price}+$vat)-($discount+$discountvat); $supplier_totals{novat} += $subref1->{price}; $supplier_totals{vat} += $subref1->{price}+$vat; $supplier_totals{discount} += $discount+$discountvat; $supplier_totals{invoice} += ($subref1->{price}+$vat)-($discount+$discountvat); } else { $invoicestotal{novat} -= $subref1->{price}; $invoicestotal{vat} -= $subref1->{price}+$vat; $invoicestotal{discount} -= $discount+$discountvat; $invoicestotal{invoice} -= ($subref1->{price}+$vat)-($discount+$discountvat); $supplier_totals{novat} -= $subref1->{price}; $supplier_totals{vat} -= $subref1->{price}+$vat; $supplier_totals{discount} -= $discount+$discountvat; $supplier_totals{invoice} -= ($subref1->{price}+$vat)-($discount+$discountvat); } $thtml .= "     {name}&startdate=$startdate&enddate=$enddate&invoice=$subref->{invoice}&supplier=$ref->{id}&wholesaler=','','status=yes,scrollbars=yes,width=700,height=400');\">$subref->{invoice}"; $thtml .= " $subref->{date}"; $thtml .= " $currency".pr($subref1->{price}).""; $thtml .= " $currency".pr($subref1->{price}+$vat).""; $thtml .= "$cnote{$subref->{cnote}}"; $thtml .= " $currency".pr($discount+$discountvat).""; $thtml .= " $currency".pr(($subref1->{price}+$vat)-($discount+$discountvat)).""; $thtml .= ""; } $temphtml .= $thtml if ($icount); $prevsupplier = $ref->{id}; } #~ $temphtml .= " SUPPLIER TOTAL"; #~ $temphtml .= " $currency".pr($supplier_totals{novat}).""; #~ $temphtml .= " $currency".pr($supplier_totals{vat}).""; #~ $temphtml .= ""; #~ $temphtml .= "$currency".pr($supplier_totals{discount}).""; #~ $temphtml .= " $currency".pr($supplier_totals{invoice}).""; #~ $temphtml .= ""; $temphtml .= "
    "; $temphtml .= "GRAND TOTAL"; $temphtml .= " $currency".pr($invoicestotal{novat}).""; $temphtml .= " $currency".pr($invoicestotal{vat}).""; $temphtml .= ""; $temphtml .= "$currency".pr($invoicestotal{discount}).""; $temphtml .= " $currency".pr($invoicestotal{invoice}).""; $temphtml .= ""; $temphtml .= $table{end}; $temphtml .= "
    "; } else { my $formhtml; $template =~ s/\@title\@/Invoices Report/sgi; $formhtml = getform("period", undef); $temphtml .= $formhtml; } #else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } #/ inv.report if ($R::subaction eq "promos") { $temphtml = "
    "; if ($R::command eq "Report" and $R::startdate and $R::enddate) { $template =~ s/\@title\@/Promotions Report/sgi; my ($startdate, $enddate); my %sqldate; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; $temphtml .= "Promotions summary for $shop{name}
    for the period: $R::startdate - $R::enddate


    "; my %client_names; $results = $dbh->prepare("SELECT name,id from $sharedclients.tillclients where f_status < 100 and shop_id=$sharedclients_shopid; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $client_names{$ref->{id}} = $ref->{name}; } my $condition; if ($R::clientgroup or (scalar @R::client)) { my @match; my $clientcond; if (scalar @R::client) {$clientcond = " and id in(".join(",",@R::client).")"} $temphtml .= "Clients matching your search: "; $results = $dbh->prepare("select id,name from $sharedclients.tillclients where clientgroup like ? $clientcond") or die $dbh->errstr(); my $likeCondition = $R::clientgroup ne "" ? $R::clientgroup : ""; $results->execute($likeCondition) or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { push @match,$ref->{id}; $temphtml .= "$ref->{name};"; #$clientnames{$ref->{id}} = $ref->{name}; #TODO - later display matches } if (scalar @match) { $condition .= " and dci.tillclients_id in (".join(",",@match).")"; } else { $condition .= " and dci.tillclients_id in (-1)"; $temphtml .= "No Clients found."; } } #/report table $temphtml .= $table{startp}; $temphtml .= "DateClientInvoiceDescriptionPromotionsAuthorized by"; $R::searchstring =~ s/\*/%/sgi; if (! $R::searchstring) {$R::searchstring = "%"} $results = $dbh->prepare(" SELECT tillclients_id,DATE_FORMAT(dc.date, '%e %M %Y') date, pd.doc name, pd.promo promo, pd.authorized authorized, pd.invoice invoice from dcash dc,pdrcash pd left join dcashinvoices dci ON dci.tillinvoices_id = pd.invoice and dci.f_status < 100 where dc.f_status<100 and pd.f_status<100 and dc.shop_id=$shop{id} and pd.shop_id=$shop{id} and dc.date >= '$startdate' and dc.date <= '$enddate' and pd.promo>0 $condition and pd.dcash_id=dc.id and pd.doc like ? ORDER BY dc.date,pd.doc;") or die $dbh->errstr(); $results->execute($R::searchstring) or die $results->errstr(); my $dtotal; while ($ref = $results->fetchrow_hashref()) { $dtotal += $ref->{promo}; $temphtml .= "$ref->{date} $client_names{$ref->{tillclients_id}} {invoice}','','status=yes,scrollbars=yes,width=700,height=400');\">$ref->{invoice}$ref->{name} $currency".pr($ref->{promo})."$ref->{authorized}"; } $temphtml .= "Total: $currency".pr($dtotal)."-"; $temphtml .= $table{end}; $temphtml .= "
    "; } else { my %allclients; # prepare waitrons my $subresults = $dbh->prepare("SELECT id, name,clientgroup FROM $sharedclients.tillclients WHERE f_status<100 and shop_id=$sharedclients_shopid ;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $allclients{$subref->{id}} = "GROUP: $subref->{clientgroup} -> $subref->{name}"; } $temphtml .= "Clients (Optional):

    Group Filter (Optional):

    "; my $formhtml; $template =~ s/\@title\@/Promotions Report/sgi; $formhtml = getform("period", undef); $temphtml .= "
    Cashup Description Search:

    Note: \"*est\" will find everything that ends with \"est\",
    alternatively \"te*\" will find everything that starts with \"te\",
    both can be used at the same time
    "; $temphtml .= $formhtml; } #/else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; }#/promos if ($R::subaction eq "debtors") { $temphtml = "
    "; if ($R::command eq "Report" and $R::startdate and $R::enddate) { $template =~ s/\@title\@/Debtors Report/sgi; my ($startdate, $enddate); my %sqldate; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; $temphtml .= "Debtors summary for $shop{name}
    for the period: $R::startdate - $R::enddate


    "; my %client_names; $results = $dbh->prepare("SELECT name,id from $sharedclients.tillclients where f_status < 100 and shop_id=$sharedclients_shopid; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $client_names{$ref->{id}} = $ref->{name}; } my $condition; if ($R::clientgroup or (scalar @R::client)) { my @match; my $clientcond; if (scalar @R::client) {$clientcond = " and id in(".join(",",@R::client).")"} $temphtml .= "Clients matching your search: "; $results = $dbh->prepare("select id,name from $sharedclients.tillclients where clientgroup like ? $clientcond") or die $dbh->errstr(); $results->execute("%"."$R::clientgroup"."%") or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { push @match,$ref->{id}; $temphtml .= "$ref->{name};"; #$clientnames{$ref->{id}} = $ref->{name}; #TODO - later display matches } if (scalar @match) { $condition .= " and dci.tillclients_id in (".join(",",@match).")"; } else { $condition .= " and dci.tillclients_id in (-1)"; $temphtml .= "No Clients found."; } } #/report table $temphtml .= $table{startp}; $temphtml .= "DateClientInvoiceNotesDebtorsAuthorized by"; $R::searchstring =~ s/\*/%/sgi; if (! $R::searchstring) {$R::searchstring = "%"} $results = $dbh->prepare(" SELECT DATE_FORMAT(dc.date, '%e %M %Y') date, pd.doc name, pd.debtors debtors, pd.authorized authorized, pd.invoice invoice, dci.tillclients_id from dcash dc, pdrcash pd, dcashinvoices dci where dc.f_status<100 and pd.f_status<100 and dci.f_status<100 and dci.tillinvoices_id = pd.invoice and dc.date >= '$startdate' and dc.date <= '$enddate' and pd.debtors>0 and pd.dcash_id=dc.id $condition and pd.doc like ? group by pd.invoice ORDER BY dci.tillclients_id,pd.invoice;") or die $dbh->errstr(); $results->execute($R::searchstring) or die $results->errstr(); my $dtotal; while ($ref = $results->fetchrow_hashref()) { $dtotal += $ref->{debtors}; $temphtml .= "$ref->{date} $client_names{$ref->{tillclients_id}} {invoice}','','status=yes,scrollbars=yes,width=700,height=400');\">$ref->{invoice} $ref->{name} $currency".pr($ref->{debtors})."$ref->{authorized}"; } $temphtml .= "Total: $currency".pr($dtotal)."-"; $temphtml .= $table{end}; $temphtml .= "
    "; } else { my $formhtml; $template =~ s/\@title\@/Debtors Report/sgi; my %allclients; # prepare waitrons my $subresults = $dbh->prepare("SELECT id, name,clientgroup FROM $sharedclients.tillclients WHERE f_status<100 and shop_id=$sharedclients_shopid ;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { $allclients{$subref->{id}} = "GROUP: $subref->{clientgroup} -> $subref->{name}"; } $temphtml .= "Clients (Optional):

    Group Filter (Optional):
    "; $formhtml = getform("period", undef); $temphtml .= "
    Notes Search:

    Note: \"*est\" will find everything that ends with \"est\",
    alternatively \"te*\" will find everything that starts with \"te\",
    both can be used at the same time
    "; $temphtml .= $formhtml; } #/else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } #/debtors if ($R::subaction eq "globalcashup") { #/ my %association = ( "fbg" => "", "amici" => "-amici", "rjs" => "-rjs" ); my %brands = ( "fbg" => "The Famous Butchers Grill", "amici" => "Amici Restaurants", "rjs" => "RJ's Steakhouse" ); my $prefix = ""; #/ "qg" + "server"; my %turnover; $temphtml = "
    "; if ($R::command eq "Report" and $R::startdate and $R::enddate) { my ($startdate, $enddate); my %sqldate; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; $template =~ s/\@title\@/Turnover Report/sgi; $temphtml .= "Turnover summary for the period:
    $R::startdate - $R::enddate


    "; foreach my $brand (keys %association) { my $dbhl = DBI->connect("DBI:mysql:server$association{$brand};host=127.0.0.1",'root','fbg4ips') or die $DBI::errstr; my %shopnames; open DATA, "$folder/../intranet-server$association{$brand}/data/shopid.txt"; while () {my ($shopid, $shoptitle) = split (/\:/,$_); $shopnames{$shopid}=$shoptitle} close DATA; foreach my $theshopid (sort keys %shopnames) { $results = $dbhl->prepare(" select count(di.waitron_id) waitrons, sum(di.cvr) cvr, sum(di.food) food, sum(di.bev) bev, sum(di.retail) retail, sum(di.bar) bar, sum(di.transfer) transfer, sum(di.s_fee_retained) s_fee_retained, sum(di.s_fee) s_fee, sum(di.staff_meals) staff_meals, sum(di.pro) pro, sum(di.retrns) retrns, sum(di.accounts) accounts, sum(di.pettycash) pettycash, sum(di.cred_c) cred_c, sum(di.cheq) cheq, sum(di.food + di.bev + di.retail + di.bar + di.transfer) grossto, sum(di.food + di.bev + di.retail + di.bar + di.transfer) - sum(di.s_fee) - ((sum(di.food + di.bev + di.retail + di.bar + di.transfer) - sum(di.s_fee))/(100 + $cvat)*$cvat) - sum(di.staff_meals) - sum(di.pro) - sum(di.retrns) nettoexc, (sum(di.food + di.bev + di.retail + di.bar + di.transfer) - sum(di.s_fee))/(100 + $cvat)*$cvat vat, (sum(di.food + di.bev + di.retail + di.bar + di.transfer) - sum(di.s_fee)) - sum(di.staff_meals + di.pro + di.retrns + di.accounts + di.cred_c + di.cheq) cash, (sum(di.food + di.bev + di.retail + di.bar + di.transfer) - sum(di.s_fee)) - sum(di.staff_meals + di.pro + di.retrns + di.accounts + di.cred_c + di.cheq) + sum(di.s_fee_retained) grosscash from dcashitems di, dcash dc where dc.f_status < 100 and di.f_status < 100 and dc.shop_id = '$theshopid' and di.shop_id = '$theshopid' and dc.date >= '$startdate' and dc.date <= '$enddate' and di.dcash_id=dc.id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $results->finish(); next if (! $ref->{cvr}); my $ahs; $ahs = $ref->{nettoexc} / $ref->{cvr} if ($ref->{cvr}); $turnover{$brand}{name} = $brands{brand}; $turnover{$brand}{shop}{$theshopid}{name} = $shopnames{$theshopid}; $turnover{$brand}{shop}{$theshopid}{cvr} = $ref->{cvr}; $turnover{$brand}{shop}{$theshopid}{ahs} = $ahs; $turnover{$brand}{shop}{$theshopid}{grossto} = $ref->{grossto}; $turnover{$brand}{shop}{$theshopid}{netto} = $ref->{nettoexc}; $turnover{$brand}{totalcvr} += $ref->{cvr}; $turnover{$brand}{totalgross} += $ref->{grossto}; $turnover{$brand}{totalnet} += $ref->{nettoexc}; $turnover{$brand}{totalahs} += $ahs; } #/$dbhl->disconnect; $turnover{$brand}{totalahs} /= scalar keys %{$turnover{$brand}{shop}}; } $temphtml .= "
    "; $temphtml .= ""; foreach my $brand (keys %association) { $temphtml .= ""; foreach my $theshop (reverse sort {$turnover{$brand}{shop}{$a}{netto} <=> $turnover{$brand}{shop}{$b}{netto}} keys %{$turnover{$brand}{shop}}) { next if (! $turnover{$brand}{shop}{$theshop}{cvr}); $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } $temphtml .= "
    BranchCoversNET A.H.S.GROSS T/ONET T/O
    $brands{$brand}
    $turnover{$brand}{shop}{$theshop}{name}$turnover{$brand}{shop}{$theshop}{cvr}".pr($turnover{$brand}{shop}{$theshop}{ahs})."".pr($turnover{$brand}{shop}{$theshop}{grossto})."".pr($turnover{$brand}{shop}{$theshop}{netto})."
    Total$turnover{$brand}{totalcvr}".pr($turnover{$brand}{totalahs})."".pr($turnover{$brand}{totalgross})."".pr($turnover{$brand}{totalnet})."
    "; } else { my $formhtml; $template =~ s/\@title\@/Turnover Report/sgi; $formhtml = getform("period", undef); $temphtml .= $formhtml; } #/else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; }#/// global report if ($R::subaction eq "andrew") { #/ my $sqlmonth; my $sqlyear; if ($R::sqlyear) { $sqlyear= $R::sqlyear } else {$sqlyear= $today{year}} if ($R::sqlmonth) {$sqlmonth = $R::sqlmonth} else {$sqlmonth=$today{month}} my %association = ( "fbg" => "", "amici" => "-amici", "ups" => "-ups", "rjs" => "-rjs" ); my %shopstype; $shopstype{fbg}{1}=1; $shopstype{fbg}{2}=1; $shopstype{fbg}{3}=1; $shopstype{fbg}{4}=1; $shopstype{fbg}{5}=2; $shopstype{fbg}{6}=1; $shopstype{fbg}{7}=2; $shopstype{fbg}{8}=1; $shopstype{fbg}{9}=1; $shopstype{amici}{1}=1; $shopstype{rjs}{9}=1; $shopstype{ups}{1}=1; my %brands = ( "fbg" => "The Famous Butchers Grill", "amici" => "Amici Restaurants", "rjs" => "RJ's Steakhouse", "ups" => "Upstairs Asian Fusion" ); my $prefix = ""; #/ "qg" + "server"; my %turnover; $temphtml = "
    "; #/$temphtml .= "Selected year: $sqlyear"; $temphtml .= ""; $results = $dbh->prepare("select distinct YEAR(date) year from dcash where f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { my $mycolor; if ($ref->{year} == $sqlyear) {$mycolor="cyan"} else {$mycolor="white"} $temphtml .= ""; } $temphtml .= "
    {year}\">$ref->{year}
    "; $temphtml .= ""; foreach (sort {$a <=> $b} keys %months) { my $mycolor; if ($_ == $sqlmonth) {$mycolor="cyan"} else {$mycolor="white"} $temphtml .= ""; } $temphtml .= "
    $months{$_}
    "; $temphtml .= "
    "; $template =~ s/\@title\@/Turnover Report/sgi; #/$temphtml .= "Turnover summary for the month:
    ".$months{$sqlmonth}."


    "; foreach my $brand (keys %association) { my $dbhl = DBI->connect("DBI:mysql:server$association{$brand};host=127.0.0.1",'root','fbg4ips') or die $DBI::errstr; my %shopnames; open DATA, "$folder/../intranet-server$association{$brand}/data/shopid.txt"; while () {my ($shopid, $shoptitle) = split (/\:/,$_); $shopnames{$shopid}=$shoptitle} close DATA; foreach my $theshopid (sort keys %shopnames) { $results = $dbhl->prepare(" select count(di.waitron_id) waitrons, sum(di.cvr) cvr, sum(di.food) food, sum(di.bev) bev, sum(di.retail) retail, sum(di.bar) bar, sum(di.transfer) transfer, sum(di.s_fee_retained) s_fee_retained, sum(di.s_fee) s_fee, sum(di.staff_meals) staff_meals, sum(di.pro) pro, sum(di.retrns) retrns, sum(di.accounts) accounts, sum(di.pettycash) pettycash, sum(di.cred_c) cred_c, sum(di.cheq) cheq, sum(di.food + di.bev + di.retail + di.bar + di.transfer) grossto, sum(di.food + di.bev + di.retail + di.bar + di.transfer) - sum(di.s_fee) - ((sum(di.food + di.bev + di.retail + di.bar + di.transfer) - sum(di.s_fee))/(100 + $cvat)*$cvat) - sum(di.staff_meals) - sum(di.pro) - sum(di.retrns) nettoexc, (sum(di.food + di.bev + di.retail + di.bar + di.transfer) - sum(di.s_fee))/(100 + $cvat)*$cvat vat, (sum(di.food + di.bev + di.retail + di.bar + di.transfer) - sum(di.s_fee)) - sum(di.staff_meals + di.pro + di.retrns + di.accounts + di.cred_c + di.cheq) cash, (sum(di.food + di.bev + di.retail + di.bar + di.transfer) - sum(di.s_fee)) - sum(di.staff_meals + di.pro + di.retrns + di.accounts + di.cred_c + di.cheq) + sum(di.s_fee_retained) grosscash from dcashitems di, dcash dc where dc.f_status < 100 and di.f_status < 100 and dc.shop_id = '$theshopid' and di.shop_id = '$theshopid' and month(dc.date) = '$sqlmonth' and year(dc.date) = '$sqlyear' and di.dcash_id=dc.id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $results->finish(); next if (! $ref->{cvr}); my $ahs; $ahs = $ref->{nettoexc} / $ref->{cvr} if ($ref->{cvr}); $turnover{$brand}{name} = $brands{brand}; $turnover{$brand}{shop}{$theshopid}{name} = $shopnames{$theshopid}; $turnover{$brand}{shop}{$theshopid}{cvr} = $ref->{cvr}; $turnover{$brand}{shop}{$theshopid}{ahs} = $ahs; $turnover{$brand}{shop}{$theshopid}{grossto} = $ref->{grossto}; $turnover{$brand}{shop}{$theshopid}{netto} = $ref->{nettoexc}; $turnover{$brand}{totalcvr} += $ref->{cvr}; $turnover{$brand}{totalgross} += $ref->{grossto}; $turnover{$brand}{totalnet} += $ref->{nettoexc}; $turnover{$brand}{totalahs} += $ahs; } #/$dbhl->disconnect; $turnover{$brand}{totalahs} /= scalar keys %{$turnover{$brand}{shop}} if (scalar keys %{$turnover{$brand}{shop}}); } $temphtml .= ""; if ($turnover{fbg}{totalgross} + $turnover{amici}{totalgross} + $turnover{rjs}{totalgross}) { $temphtml .= "
    "; $temphtml .= ""; foreach my $brand (keys %association) { $temphtml .= ""; my @shopys; foreach my $theshop (reverse sort {$turnover{$brand}{shop}{$a}{netto} <=> $turnover{$brand}{shop}{$b}{netto}} keys %{$turnover{$brand}{shop}} ) { next if (! $turnover{$brand}{shop}{$theshop}{cvr}); my $mycolor; if ($shopstype{$brand}{$theshop} == 1) {$mycolor="white"} else {$mycolor="orange"} $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; } $temphtml .= "
    BranchCoversNET A.H.S.GROSS T/ONET T/O
    $brands{$brand}
    $turnover{$brand}{shop}{$theshop}{name} (details)".commify($turnover{$brand}{shop}{$theshop}{cvr})."".pr($turnover{$brand}{shop}{$theshop}{ahs})."".pr($turnover{$brand}{shop}{$theshop}{grossto})."".pr($turnover{$brand}{shop}{$theshop}{netto})."
    Total".commify($turnover{$brand}{totalcvr})."".pr($turnover{$brand}{totalahs})."".pr($turnover{$brand}{totalgross})."".pr($turnover{$brand}{totalnet})."
    "; } else { $temphtml .= "NO DATA YET."; } #/if $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } #// global report if ($R::subaction eq "cashup") { $temphtml = "
    "; if (($R::command eq "Daily Report" and $R::startdate and $R::enddate) or ($R::command eq "Report" and $R::sqlmonth and $R::sqlyear and $R::sqlshop)) { my $datequery; $template =~ s/\@title\@/Cashup Report/sgi; my ($startdate, $enddate); my %sqldate; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; my %calc; my %total_calc; #GRAND RETREIVAL #SFEES PER DCASH id ----------------------------------------------------------- $results = $dbh->prepare(" select dcash.id dcashid, sum(dci.s_fee) s_fee, sum(dci.s_fee_retained) s_fee_retained from dcashitems dci,dcash where dcash.date >= '$startdate' and dcash.date <= '$enddate' and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id = dci.dcash_id and dcash.f_status < 100 and dci.f_status < 100 group by dcash.id; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $calc{$ref->{dcashid}}{s_fee} = $ref->{s_fee}; $total_calc{s_fee} += $calc{$ref->{dcashid}}{s_fee}; $calc{$ref->{dcashid}}{s_fee_retained} = $ref->{s_fee_retained}; $total_calc{s_fee_retained} += $calc{$ref->{dcashid}}{s_fee_retained}; } #TURNOVER ----------------------------------------------------------------------- my $turnOver_SQL = qq|select dcash.pettycash pettycash, dcash.id dcashid, DATE_FORMAT(dcash.date, '%e %M %Y') dcashdate, dcash.date dcashdate, sum(dcinv.dcinv_turnover_total) grossto, sum(dcinv.covers) covers_total, sum(dcinv.staffpromo_total) staff_promo, sum(dcinv.returns_total) returns_total, sum(dcinv.discount_total) promo_total, sum(dcinv.eft_total) eft_total, sum(dcinv.creditcards_total) creditcard_total, sum(dcinv.accounts_total) accounts_total, sum(dcinv.cheque_total) cheque_total, sum(dcinv.vat_total) vat_total, sum( (dcinv.dcinv_turnover_total - dcinv.vat_total) - (dcinv.staffpromo_total - dcinv.staffpromo_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.discount_total - dcinv.discount_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.returns_total - dcinv.returns_total/dcinv.dcinv_turnover_total*dcinv.vat_total) ) #- sum(dci.s_fee) AS nettoexc_componenet, sum( ( (dcinv.dcinv_turnover_total - dcinv.vat_total) - (dcinv.staffpromo_total - dcinv.staffpromo_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.discount_total - dcinv.discount_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.returns_total - dcinv.returns_total/dcinv.dcinv_turnover_total*dcinv.vat_total) ) ) / sum(dcinv.covers) AS avgnet, sum( dcinv.dcinv_turnover_total - dcinv.staffpromo_total - dcinv.discount_total - dcinv.returns_total - dcinv.eft_total - dcinv.creditcards_total - dcinv.accounts_total - dcinv.cheque_total ) #- dci.s_fee AS cash_component, sum( dcinv.dcinv_turnover_total - dcinv.staffpromo_total - dcinv.discount_total - dcinv.returns_total - dcinv.eft_total - dcinv.creditcards_total - dcinv.accounts_total - dcinv.cheque_total ) #- dci.s_fee + dci.s_fee_retained AS grosscash_component from dcash, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 where dcash.date >= '$startdate' and dcash.date <= '$enddate' and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 group by dcash.id;|; #open FILE,">C:/wwwroot/extranet/logfile.txt"; #print FILE $turnOver_SQL; #close FILE; $results = $dbh->prepare(" select dcash.pettycash pettycash, dcash.id dcashid, DATE_FORMAT(dcash.date, '%e %M %Y') dcashdate, dcash.date dcashdate, sum(dcinv.dcinv_turnover_total) grossto, sum(dcinv.covers) covers_total, sum(dcinv.staffpromo_total) staff_promo, sum(dcinv.returns_total) returns_total, sum(dcinv.discount_total) promo_total, sum(dcinv.eft_total) eft_total, sum(dcinv.creditcards_total) creditcard_total, sum(dcinv.accounts_total) accounts_total, sum(dcinv.cheque_total) cheque_total, sum(dcinv.vat_total) vat_total, #2023-02-24 Steven synced with cashup formula #sum( # (dcinv.dcinv_turnover_total - dcinv.vat_total) - # (dcinv.staffpromo_total - dcinv.staffpromo_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - # (dcinv.discount_total - dcinv.discount_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - # (dcinv.returns_total - dcinv.returns_total/dcinv.dcinv_turnover_total*dcinv.vat_total) #) #- sum(dci.s_fee) sum( (dcinv.dcinv_turnover_total - dcinv.staffpromo_total - dcinv.discount_total - dcinv.returns_total- dcinv.vat_total ) ) AS nettoexc_componenet, sum( ( (dcinv.dcinv_turnover_total - dcinv.vat_total) - (dcinv.staffpromo_total - dcinv.staffpromo_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.discount_total - dcinv.discount_total/dcinv.dcinv_turnover_total*dcinv.vat_total) - (dcinv.returns_total - dcinv.returns_total/dcinv.dcinv_turnover_total*dcinv.vat_total) ) ) / sum(dcinv.covers) AS avgnet, sum( dcinv.dcinv_turnover_total - dcinv.staffpromo_total - dcinv.discount_total - dcinv.returns_total - dcinv.eft_total - dcinv.creditcards_total - dcinv.accounts_total - dcinv.cheque_total ) #- dci.s_fee AS cash_component, sum( dcinv.dcinv_turnover_total - dcinv.staffpromo_total - dcinv.discount_total - dcinv.returns_total - dcinv.eft_total - dcinv.creditcards_total - dcinv.accounts_total - dcinv.cheque_total ) #- dci.s_fee + dci.s_fee_retained AS grosscash_component from dcash, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 where dcash.date >= '$startdate' and dcash.date <= '$enddate' and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 group by dcash.id; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $calc{$ref->{dcashid}}{dcashdate} = $ref->{dcashdate}; $calc{$ref->{dcashid}}{covers_total} = $ref->{covers_total}; $total_calc{covers_total} += $calc{$ref->{dcashid}}{covers_total}; #$calc{$dcashid}{deposits} $subresults = $dbh->prepare(" SELECT SUM(credit - debit) balance FROM accounts WHERE transaction_type='Cash' AND DATE = ?;") or die $dbh->errstr(); $subresults->execute($ref->{dcashdate}) or die $subresults->errstr(); $ref1 = $subresults->fetchrow_hashref(); $calc{$ref->{dcashid}}{deposits} = $ref1->{balance}; $total_calc{deposits} += $ref1->{balance}; $calc{$ref->{dcashid}}{grossto} = $ref->{grossto}; $total_calc{grossto} += $calc{$ref->{dcashid}}{grossto}; $calc{$ref->{dcashid}}{staff_promo} = $ref->{staff_promo}; $total_calc{staff_promo} += $calc{$ref->{dcashid}}{staff_promo}; $calc{$ref->{dcashid}}{returns_total} = $ref->{returns_total}; $total_calc{returns_total} += $calc{$ref->{dcashid}}{returns_total}; $calc{$ref->{dcashid}}{promo_total} = $ref->{promo_total}; $total_calc{promo_total} += $calc{$ref->{dcashid}}{promo_total}; $calc{$ref->{dcashid}}{eft_total} = $ref->{eft_total}; $total_calc{eft_total} += $calc{$ref->{dcashid}}{eft_total}; $calc{$ref->{dcashid}}{creditcard_total} = $ref->{creditcard_total}; $total_calc{creditcard_total} += $calc{$ref->{dcashid}}{creditcard_total}; $calc{$ref->{dcashid}}{accounts_total} = $ref->{accounts_total}; $total_calc{accounts_total} += $calc{$ref->{dcashid}}{accounts_total}; $calc{$ref->{dcashid}}{cheque_total} = $ref->{cheque_total}; $total_calc{cheque_total} += $calc{$ref->{dcashid}}{cheque_total}; my $taxRes = $dbh->prepare("SELECT percent FROM tax WHERE std=1;") or die $dbh->errstr(); $taxRes->execute(); my $taxRef = $taxRes->fetchrow_hashref(); #$calc{$ref->{dcashid}}{vat_total} = ($ref->{grossto} - $ref->{staff_promo} - $ref->{promo_total} - $ref->{returns_total}) * ($taxRef->{percent}/(100+$taxRef->{percent})); $calc{$ref->{dcashid}}{vat_total} = $ref->{vat_total}; $total_calc{vat_total} += $calc{$ref->{dcashid}}{vat_total}; $calc{$ref->{dcashid}}{nettoexc} = $ref->{nettoexc_componenet} - $calc{$ref->{dcashid}}{s_fee}; $total_calc{nettoexc} += $calc{$ref->{dcashid}}{nettoexc}; $calc{$ref->{dcashid}}{avgnet} = $ref->{avgnet}; #use formula below = Tnet+Ts_fee / Tcovers if Tcovers $calc{$ref->{dcashid}}{cash} = $ref->{cash_component} - $calc{$ref->{dcashid}}{s_fee}; $total_calc{cash} += $calc{$ref->{dcashid}}{cash}; $calc{$ref->{dcashid}}{grosscash} = $ref->{grosscash_component} - $calc{$ref->{dcashid}}{s_fee} + $calc{$ref->{dcashid}}{s_fee_retained}; $total_calc{grosscash} += $calc{$ref->{dcashid}}{grosscash}; $calc{$ref->{dcashid}}{pettycash} = $ref->{pettycash}; $total_calc{pettycash} += $calc{$ref->{dcashid}}{pettycash}; $calc{$ref->{dcashid}}{totalbanked} = $calc{$ref->{dcashid}}{grosscash} + $calc{$ref->{dcashid}}{cheque_total} - $calc{$ref->{dcashid}}{pettycash}; $calc{$ref->{dcashid}}{totalbanked} = $calc{$ref->{dcashid}}{totalbanked} + $calc{$ref->{dcashid}}{deposits}; $total_calc{totalbanked} += $calc{$ref->{dcashid}}{totalbanked}; } # while turnover #AHS totals $total_calc{avgnet} = ($total_calc{nettoexc} + $total_calc{s_fee}) / $total_calc{covers_total} if ($total_calc{covers_total}>0); #### EXTRA OPTIONS ############################# ACCOUNTS if (scalar @R::on_accounts){ my @groups = @R::on_accounts; $_ = "'".$_."'" foreach (@groups); $results = $dbh->prepare(" select dcash.id dcashid, tic.clientgroup clientgroup, sum(dcinv.accounts_total) accounts_total from dcash, $sharedclients.tillclients tic, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 where dcash.date >= '$startdate' and dcash.date <= '$enddate' and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and tic.shop_id=$sharedclients_shopid and dcash.id=dci.dcash_id and dcinv.tillclients_id=tic.id and tic.clientgroup in (".join(",",@groups).") and dcash.f_status<100 and dci.f_status<100 and tic.f_status<100 group by dcash.id, tic.clientgroup; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $calc{$ref->{dcashid}}{on_account}{$ref->{clientgroup}} = $ref->{accounts_total}; $total_calc{on_account}{$ref->{clientgroup}} += $ref->{accounts_total}; } } #### EXTRA OPTIONS ############################# COST OF SALES - STEVEN20190523 if (scalar @R::on_costofsales){ my $SQL = "select dcash.id dcashid, dctov.costcenter_id costcenter_id, sum(dctov.turnover_total+dctov.vat_total) turnover_total, sum(dctov.discounts_total + dctov.vat_total*dctov.discounts_total/dctov.turnover_total), SUM(dcinv.returns_total) returns_total from dcash, dcashturnover dctov, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 where dcash.date >= '$startdate' and dcash.date <= '$enddate' and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dctov.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcinv.id=dctov.dcashinvoices_id and dcash.f_status<100 and dctov.f_status<100 and dci.f_status<100 and dctov.costcenter_id in (".join(",",@R::on_costofsales).") group by dcash.id, dctov.costcenter_id"; #logit($SQL ."\n"); #STEVEN 2019-06-11 SUM(dcinv.returns_total) returns_total $results = $dbh->prepare($SQL) or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { #ORIGINAL #$calc{$ref->{dcashid}}{on_costofsales}{$ref->{costcenter_id}} = $ref->{turnover_total}; #$total_calc{on_costofsales}{$ref->{costcenter_id}} += $ref->{turnover_total}; $calc{$ref->{dcashid}}{on_costofsales}{$ref->{costcenter_id}} = $ref->{turnover_total} - $ref->{returns_total} ; $total_calc{on_costofsales}{$ref->{costcenter_id}} += $ref->{turnover_total} - $ref->{returns_total}; } } #20190523 START INCOME,Section,other SALES... my (@on_costofsales,@on_costofsales_t); $results = $dbh->selectall_arrayref("SELECT * FROM stocktypes WHERE f_status < 100 AND shop_id=?",{ Slice=>{} }, $shop{id}); foreach(@$results){ if($_->{name} =~/OTHER\s+INCOME/i || $_->{name} =~/OTHER\s+SALES/i || $_->{name}=~/Section/i){ my $_id = $_->{id}; foreach my $id(@R::on_costofsales){ if($_id == $id){ push @on_costofsales_t,$id; } } } } my $SQL_2 = "select dcash.id dcashid,dcinv.tillinvoices_id, dcinv.returns_total returns_total from dcash, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id = dci.shop_id and dcinv.f_status<100 where dcash.date >= '$startdate' and dcash.date <= '$enddate' and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100"; # logit($SQL_2."\n"); $results = $dbh->prepare($SQL_2) or die $dbh->errstr(); $results->execute() or die $results->errstr(); my $dcashid={}; while ($ref = $results->fetchrow_hashref()) { push @{$dcashid->{$ref->{dcashid}}},$ref->{tillinvoices_id} if $ref->{tillinvoices_id}; } foreach my $did(keys %{$dcashid}){ my $invs = join(",",@{$dcashid->{$did}}); #logit($invs); if(length($invs) > 1 && scalar(@on_costofsales_t) > 0){ foreach my $cost_center_id(@on_costofsales_t){ #RESET $calc{$did}{on_costofsales}{$cost_center_id} = 0; #$total_calc{on_costofsales}{$cost_center_id} = 0; my $SQL = "SELECT *,year(stamp) year FROM `tillordersdetails` WHERE invoice in($invs) AND plu in (SELECT id FROM menu WHERE `type` IN (".$cost_center_id."))"; #logit($SQL); $results = $dbh->prepare($SQL); $results->execute() or die $results->errstr(); while (my $ref2 = $results->fetchrow_hashref()) { $calc{$did}{on_costofsales}{$cost_center_id} += $ref2->{qty} * $ref2->{price} -$ref2->{discount}; #$total_calc{on_costofsales}{$cost_center_id} += $ref2->{qty} * $ref2->{price} -$ref2->{discount}; } #$calc{$did}{on_costofsales}{$cost_center_id} = $calc{$did}{on_costofsales}{$cost_center_id} - $ref2->{returns_total}; #$total_calc{on_costofsales}{$cost_center_id} = $total_calc{on_costofsales}{$cost_center_id} - $ref2->{returns_total}; } } } #20190523 END special sales. #### EXTRA OPTIONS ############################# TIME for my $timenr (1..3) { if ( $q->param("time".$timenr) ne "" and $q->param("time".$timenr."hs") ne "" and $q->param("time".$timenr."he") ne "" and $q->param("time".$timenr."name") ne "" ) { my $starth = $q->param("time".$timenr."hs"); my $endh = $q->param("time".$timenr."he"); my $condition; if ($endh < $starth) { $condition .= " and (dcinv.time >= '$starth:00:00' or dcinv.time <= '$endh:00:00') "; } else { $condition .= " and (dcinv.time >= '$starth:00:00' and dcinv.time <= '$endh:00:00') "; } #the query $results = $dbh->prepare(" select dcash.id dcashid, sum(dcinv.dcinv_turnover_total) turnover_total from dcash, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 and (dcinv.returns_total = 0 or dcinv.returns_total is null) where dcash.date >= '$startdate' and dcash.date <= '$enddate' $condition and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 group by dcash.id;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $calc{$ref->{dcashid}}{timeperiod}{$timenr} = $ref->{turnover_total}; $total_calc{timeperiod}{$timenr} += $ref->{turnover_total}; } } # if time provided } #foreach 3 times #### EXTRA OPTIONS ############################# TABLE TYPE if (scalar @R::on_tabletype){ $results = $dbh->prepare(" select dcash.id dcashid, tt.type ttype, sum(dcinv.dcinv_turnover_total) turnover_total from dcash, tilltables tt, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 where dcash.date >= '$startdate' and dcash.date <= '$enddate' and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and tt.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcinv.tilltables_id=tt.id and tt.type in (".join(",",@R::on_tabletype).") and dcash.f_status<100 and dci.f_status<100 and tt.f_status<100 group by dcash.id, tt.id; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $calc{$ref->{dcashid}}{on_tabletype}{$ref->{ttype}} = $ref->{turnover_total}; $total_calc{on_tabletype}{$ref->{ttype}} += $ref->{turnover_total}; } } $results = $dbh->prepare("SELECT * FROM suppliers WHERE me = 1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $temphtml .= "
    Company Name: $ref->{name}
    "; #/report table $temphtml .= $table{startp}; #table header ---------------------------------------------------------------- $temphtml .= ""; $temphtml .= "Date"; $temphtml .= "Covers" if ($R::col_covers); $temphtml .= "AHS.Net" if ($R::col_ahs); $temphtml .= "GROSS T/O"; $temphtml .= "Commission Retained" if ($R::col_sfee_ret); $temphtml .= "Commission" if ($R::col_sfee); $temphtml .= "NET T/O Excl" if ($R::col_netto); $temphtml .= "TAX"; $temphtml .= "Staff Promotions" if ($R::col_staffpromo); $temphtml .= "Discounts" if ($R::col_discount); $temphtml .= "Returns" if ($R::col_returns); $temphtml .= "Accounts" if ($R::col_accounts); $temphtml .= "EFT" if ($R::col_eft); $temphtml .= "Credit Cards" if ($R::col_creditcard); $temphtml .= "Mobile/Cheque" if ($R::col_cheque);##STEVEN need to cahnge to mobile payment : Cheques -> MOBILE Payment $temphtml .= "Cash" if ($R::col_cash); $temphtml .= "Gross Cash" if ($R::col_grosscash); $temphtml .= "PETTY CASH" if ($R::col_pettycash); $temphtml .= "CASH DEP/WITHDRW" if ($R::col_deposits); $temphtml .= "TOTAL BANKED" if ($R::col_banked); if (scalar @R::on_accounts){ $temphtml .= "$_" foreach (@R::on_accounts); } #cos if (scalar @R::on_costofsales){ $temphtml .= "$menutypes{$database}{$_}" foreach (@R::on_costofsales); } #time for my $timenr (1..3) { if ( $q->param("time".$timenr) ne "" and $q->param("time".$timenr."hs") ne "" and $q->param("time".$timenr."he") ne "" and $q->param("time".$timenr."name") ne "" ) { $temphtml .= "".$q->param("time".$timenr."name")."" } } #ttype if (scalar @R::on_tabletype){ $temphtml .= "$tilltabletype{$_}" foreach (@R::on_tabletype); } $temphtml .= ""; #table data -------------------------------------------------------------------- foreach my $dcashid (sort {$a <=> $b} keys %calc) { $temphtml .= ""; $temphtml .= "$calc{$dcashid}{dcashdate}"; $temphtml .= "$calc{$dcashid}{covers_total}" if ($R::col_covers); $temphtml .= "".pr($calc{$dcashid}{avgnet})."" if ($R::col_ahs); $temphtml .= "".pr($calc{$dcashid}{grossto}).""; $temphtml .= "".pr($calc{$dcashid}{s_fee_retained})."" if ($R::col_sfee_ret); $temphtml .= "".pr($calc{$dcashid}{s_fee})."" if ($R::col_sfee); $temphtml .= "".pr($calc{$dcashid}{nettoexc})."" if ($R::col_netto); $temphtml .= "".pr($calc{$dcashid}{vat_total}).""; $temphtml .= "".pr($calc{$dcashid}{staff_promo})."" if ($R::col_staffpromo); $temphtml .= "".pr($calc{$dcashid}{promo_total})."" if ($R::col_discount); $temphtml .= "".pr($calc{$dcashid}{returns_total})."" if ($R::col_returns); $temphtml .= "".pr($calc{$dcashid}{accounts_total})."" if ($R::col_accounts); $temphtml .= "".pr($calc{$dcashid}{eft_total})."" if ($R::col_eft); $temphtml .= "".pr($calc{$dcashid}{creditcard_total})."" if ($R::col_creditcard); $temphtml .= "".pr($calc{$dcashid}{cheque_total})."" if ($R::col_cheque); $temphtml .= "".pr($calc{$dcashid}{cash})."" if ($R::col_cash); $temphtml .= "".pr($calc{$dcashid}{grosscash})."" if ($R::col_grosscash); $temphtml .= "".pr($calc{$dcashid}{pettycash})."" if ($R::col_pettycash); $temphtml .= "".pr($calc{$dcashid}{deposits})."" if ($R::col_deposits); $temphtml .= "".pr($calc{$dcashid}{totalbanked})."" if ($R::col_banked); if (scalar @R::on_accounts){ $temphtml .= "".pr($calc{$dcashid}{on_account}{$_})."" foreach (@R::on_accounts); } if (scalar @R::on_costofsales){ $temphtml .= "".pr($calc{$dcashid}{on_costofsales}{$_})."" foreach (@R::on_costofsales); } #time for my $timenr (1..3) { if ( $q->param("time".$timenr) ne "" and $q->param("time".$timenr."hs") ne "" and $q->param("time".$timenr."he") ne "" and $q->param("time".$timenr."name") ne "" ) { $temphtml .= "".pr($calc{$dcashid}{timeperiod}{$timenr})."" } } if (scalar @R::on_tabletype){ $temphtml .= "".pr($calc{$dcashid}{on_tabletype}{$_})."" foreach (@R::on_tabletype); } $temphtml .= ""; } #foreach line #TOTALS ---------------------- $temphtml .= ""; $temphtml .= "".(scalar keys %calc).""; $temphtml .= "$total_calc{covers_total}" if ($R::col_covers); $temphtml .= "".pr($total_calc{avgnet})."" if ($R::col_ahs); $temphtml .= "".pr($total_calc{grossto}).""; $temphtml .= "".pr($total_calc{s_fee_retained})."" if ($R::col_sfee_ret); $temphtml .= "".pr($total_calc{s_fee})."" if ($R::col_sfee); $temphtml .= "".pr($total_calc{nettoexc})."" if ($R::col_netto); $temphtml .= "".pr($total_calc{vat_total}).""; $temphtml .= "".pr($total_calc{staff_promo})."" if ($R::col_staffpromo); $temphtml .= "".pr($total_calc{promo_total})."" if ($R::col_discount); $temphtml .= "".pr($total_calc{returns_total})."" if ($R::col_returns); $temphtml .= "".pr($total_calc{accounts_total})."" if ($R::col_accounts); $temphtml .= "".pr($total_calc{eft_total})."" if ($R::col_eft); $temphtml .= "".pr($total_calc{creditcard_total})."" if ($R::col_creditcard); $temphtml .= "".pr($total_calc{cheque_total})."" if ($R::col_cheque); $temphtml .= "".pr($total_calc{cash})."" if ($R::col_cash); $temphtml .= "".pr($total_calc{grosscash})."" if ($R::col_grosscash); $temphtml .= "".pr($total_calc{pettycash})."" if ($R::col_pettycash); $temphtml .= "".pr($total_calc{deposits})."" if ($R::col_deposits); $temphtml .= "".pr($total_calc{totalbanked})."" if ($R::col_banked); if (scalar @R::on_accounts){ $temphtml .= "".pr($total_calc{on_account}{$_})."" foreach (@R::on_accounts); } if (scalar @R::on_costofsales){ $temphtml .= "".pr($total_calc{on_costofsales}{$_})."" foreach (@R::on_costofsales); } #time for my $timenr (1..3) { if ( $q->param("time".$timenr) ne "" and $q->param("time".$timenr."hs") ne "" and $q->param("time".$timenr."he") ne "" and $q->param("time".$timenr."name") ne "" ) { $temphtml .= "".pr($total_calc{timeperiod}{$timenr})."" } } if (scalar @R::on_tabletype){ $temphtml .= "".pr($total_calc{on_tabletype}{$_})."" foreach (@R::on_tabletype); } $temphtml .= ""; $temphtml .= $table{end}; $temphtml .= "
    "; } else { my $formhtml; $template =~ s/\@title\@/Turnover Report/sgi; $formhtml = getform("dcashnew", undef); my $listhtml; #select forms #on account $listhtml = ""; $formhtml =~ s/\@on_accounts\@/$listhtml/gsi; #on COST OF SALES CAT $listhtml = ""; $formhtml =~ s/\@on_costsales\@/$listhtml/gsi; #on TABLE TYPE $listhtml = ""; $formhtml =~ s/\@on_tabletype\@/$listhtml/gsi; $temphtml .= $formhtml; } #/else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } #/cashup if ($R::subaction eq "wages") { $temphtml = "
    "; if ($R::command eq "Report" and $R::startdate and $R::enddate) { my ($startdate, $enddate); my %sqldate; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; $template =~ s/\@title\@/Wages Report/sgi; $temphtml .= "Period selected: $R::startdate - $R::enddate

    "; $temphtml .= $table{startp}; $temphtml .= "NameAmountDescription"; foreach (sort keys %wagetypes) { $temphtml .= "$wagetypes{$_}"; $results = $dbh->prepare("select * from loans where loantype=2 and wagetype='$_' and date >= '$startdate' and date <= '$enddate' and shop_id=$shop{id} and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $temphtml .= "$ref->{wageperson}$currency$ref->{amount}$ref->{description}"; } } $temphtml .= $table{end}; $temphtml .= "
    "; } else { my $formhtml; $template =~ s/\@title\@/Wages Report/sgi; $formhtml = getform("period", undef); $temphtml .= $formhtml; } #/else - choise $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } #/ inv.report if ($R::subaction eq "sfees") { my $formhtml; my $listhtml; $template =~ s/\@title\@/Retained Service Fees Report/sgi; $temphtml = "
    "; if ($R::command eq "Report") { my %waitronnames; my ($startdate, $enddate); my %sqldate; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; $temphtml .= "Period selected: $R::startdate - $R::enddate

    "; #/prepare waitrons $results = $dbh->prepare("SELECT DISTINCT w.id id, w.name name FROM waitron w WHERE w.shop_id=$shop{id} and w.f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) {$waitronnames{$ref->{id}}=$ref->{name}} my @waitrons; my %retained; my %loans; my %sfeepaid; my %paidtotal; my %owed; my $totalowed; if ($R::type == 2) { $results = $dbh->prepare("SELECT DISTINCT w.id id FROM waitron w, dcashitems d, dcash dc WHERE w.shop_id=$shop{id} and w.f_status<100 and d.shop_id=$shop{id} and d.f_status<100 and dc.shop_id=$shop{id} and dc.f_status<100 and d.dcash_id=dc.id and dc.date >= '$startdate' and dc.date <= '$enddate' and w.id=d.waitron_id and d.s_fee_retained > 0 ORDER BY w.name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) {push @waitrons,$ref->{id}} } else { @waitrons = ($R::waitron) } foreach my $waitron (@waitrons) { $results = $dbh->prepare("SELECT sum(s_fee_retained) retained FROM dcashitems d, dcash dc WHERE d.waitron_id=$waitron and d.shop_id=$shop{id} and d.f_status<100 and d.dcash_id = dc.id and dc.date >= '$startdate' and dc.date <= '$enddate' and dc.shop_id=$shop{id} and dc.f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $retained{$waitron}=$ref->{retained}; } foreach my $waitron (@waitrons) { $results = $dbh->prepare("SELECT sum(amount) loan FROM loans WHERE waitron_id=$waitron and date >= '$startdate' and date <= '$enddate' and shop_id=$shop{id} and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $results->finish(); $loans{$waitron}=$ref->{loan}; } foreach my $waitron (@waitrons) { $results = $dbh->prepare("SELECT sum(amount) sfeepaid FROM sfeepaid WHERE waitron_id=$waitron and date >= '$startdate' and date <= '$enddate' and shop_id=$shop{id} and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $results->finish(); $sfeepaid{$waitron}=$ref->{sfeepaid}; } #/calculation foreach (@waitrons) { $paidtotal{$_} = $loans{$_} + $sfeepaid{$_}; $owed{$_} = $retained{$_} - $paidtotal{$_}; $totalowed += $owed{$_}; } $temphtml .= $table{startp}; $temphtml .= "UserMoney Owed "; foreach my $waitron (@waitrons) { $temphtml .= "$waitronnames{$waitron} $currency".pr($owed{$waitron})." payment"; } $temphtml .= "Total $currency".pr($totalowed)." "; $temphtml .= $table{end}; $temphtml .= "
    "; } elsif ($R::command eq "Select" and $R::startdate and $R::enddate) { #/print the second form my ($startdate, $enddate); my %sqldate; %sqldate = dateforsql($R::startdate); $startdate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; %sqldate = dateforsql($R::enddate); $enddate = $sqldate{year}."-".$sqldate{month}."-".$sqldate{day}; $formhtml = getform("sfees",undef); $listhtml = ""; $formhtml =~ s/\@waitrons\@/$listhtml/sgi; $temphtml .= $formhtml; $temphtml .= ""; $temphtml .= ""; } else { $formhtml = getform("period-select",undef); $temphtml .= $formhtml; $temphtml .= "
    "; } $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; } #/ sfee.report $template =~ s/\@content\@/$temphtml/sgi; } #/ END REPORTS ACTION elsif ($socketflag == 1 and $R::action eq "offdays") { my $temphtml; $template =~ s/\@title\@/Off Days Editor/sgi; #my %dnames = (0 => "Su", 1 => "Mo", 2 => "Tu", 3 => "We", 4 => "Th", 5 => "Fr", 6 => "Sa"); my %mnames = (0 => "January", 1 => "February", 2 => "March", 3 => "April", 4 => "May", 5 => "June", 6 => "July", 7 => "August", 8 => "September", 9 => "October", 10 => "November", 11 => "December"); my %dayflags = ( 1 => "off", 2 => "swn", 3 => "snn", 4 => "abs", 5 => "cpl", 6 => "anl" ); my %daycounter; my %daytypes = ( "off" => "Day Off", "swn" => "Sick with Note", "snn" => "Sick without Note", "abs" => "Absent", "cpl" => "Compationate Leave", "anl" => "Anual Leave" ); my %employees; $results = $dbh->prepare("select id,name from employees where f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $employees{$ref->{id}} = $ref->{name}; } my $year = (localtime(time))[5] + 1900; $year = $R::year if ($R::year); $temphtml .= qq~ ~; $temphtml .= "
    Selected year: "; $temphtml .= "Selected employee: "; $temphtml .= " "; $temphtml .= " Mode: ".(($R::mode eq "" or $R::mode eq "view") ? "*** " : "")."View Mode | ".($R::mode eq "edit" ? "*** " : "")."Edit Mode"; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; if ($R::employee_id) { #/## UPDATE FROM BROWSER if ($R::date and $R::flag > 0) { $results = $dbh->prepare("select count(id) count from offdays where employee_id=$R::employee_id and date = '$R::date' and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $exist = $ref->{count}; if ($exist) { $results = $dbh->prepare("update offdays set f_status=1, flag=$R::flag where employee_id=$R::employee_id and date = '$R::date' and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } else { $results = $dbh->prepare(" insert into offdays (date,employee_id,flag,shop_id) values ('$R::date',$R::employee_id, $R::flag, $shop{id});") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } } elsif ($R::date and $R::flag < 0) { $results = $dbh->prepare("update offdays set f_status=101 where employee_id=$R::employee_id and date = '$R::date' and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } #/## // UPDATE my %offdays; my %workdays; my %publicholidays; my %workedpublicholidays; $results = $dbh->prepare("select description,month(date)-1 month ,day(date) day from publicholidays where year(date)=$year;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $publicholidays{$ref->{month}}{$ref->{day}} = $ref->{description}; } $results = $dbh->prepare("select month(date)-1 month ,day(date) day, flag flag from offdays where shop_id=$shop{id} and employee_id=$R::employee_id and f_status<100 and year(date)=$year order by date;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $offdays{$ref->{month}}{$ref->{day}} = $ref->{flag}; #/count'em $daycounter{offdays}{flag}{ $dayflags{$ref->{flag}} }++; $daycounter{offdays}{all}++; } $results = $dbh->prepare(" select count(id) sessions, month(stamp)-1 month, day(stamp) day from employeesaccess where year(stamp)='$year' and employee_id = $R::employee_id and shop_id = $shop{id} and operation = 1 group by day,month; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $workdays{$ref->{month}}{$ref->{day}} = $ref->{sessions}; $daycounter{workdays}{all} ++ ; #/if (! $offdays{$ref->{month}}{$ref->{day}}); $workedpublicholidays{all} ++ if ( ! $offdays{$ref->{month}}{$ref->{day}} and $publicholidays{$ref->{month}}{$ref->{day}} ); } #/CALENDAR if (! $R::report) { $temphtml .= ""; for my $month (0..11) { next if ($month != 0 and ! $R::premonth and $R::mode eq "edit"); next if ($month != $R::premonth and $R::premonth and $R::mode eq "edit"); $R::premonth = 0 if ($month == 0 and ! $R::premonth and $R::mode eq "edit"); if ($month % 4 == 0 and $month > 0) {$temphtml .= ""} $temphtml .= ""; } $shiftday = dayofweek(lastday($month+1,$year),$month,$year); $temphtml .= ""x(7-1-$shiftday); $temphtml .="
    "; #/ Month Cell $temphtml .= ""; $temphtml .= "
    $mnames{$month}"; if ($R::mode eq "edit") { $temphtml .= " Previous "; $temphtml .= " Next "; $temphtml .= " | Report "; } elsif ($R::mode eq "view" or $R::mode eq "") { $temphtml .= " Edit "; $temphtml .= " | Report "; } $temphtml .= "
    "; $temphtml .= ""; #/week days table $temphtml .= "" foreach (sort {$a<=>$b} keys %dnames); #/day titles $temphtml .= ""; $temphtml .= ""; my $shiftday = dayofweek(1,$month,$year) - 1; $temphtml .= ""x$shiftday; for my $day (1..(lastday($month+1,$year))) { if (($day+$shiftday) % 7 == 1) {$temphtml .= ""} $temphtml .= "
    $dnames{$_}
    $day
    " : "$day
    "); $temphtml .= "" if ($offdays{$month}{$day}); } elsif ($R::mode eq "edit") { #/$temphtml .= "" if ($offdays{$month}{$day}); $temphtml .= (exists $publicholidays{$month}{$day}? "
    $day
    " : "$day
    "); #/$temphtml .= "$day
    "; $temphtml .= ""; $temphtml .= ""; for (1..6) {$temphtml .= "" if ($_ % 4 == 0); $temphtml .= " $dayflags{$_} " ; } $temphtml .= "
    C
    L
    R
    "; #/$temphtml .= ""; } $temphtml .= "
    "; #/month table } $temphtml .= ""; $temphtml .= ""; #/main table #/Legend year totals $temphtml .= ""; $temphtml .= "" foreach (sort keys %daytypes); $temphtml .= "
    Legent / Totals
    - $daytypes{$_}
    $daycounter{offdays}{flag}{$_} days
    "; $temphtml .= "
    "; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    Total Days Off $daycounter{offdays}{all} Total Days Working $daycounter{workdays}{all} Total Public Holidays Working $workedpublicholidays{all}
    "; $temphtml .= "
    "; $temphtml .= "
    "; } else {#/ Reportmonth my %offdays; my %workdays; #/ my %daycounter; my %workedpublicholidays; $results = $dbh->prepare(" select day(date) day, flag, employee_id from offdays where month(date)=$R::reportmonth + 1 and shop_id=$shop{id} and f_status<100; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $offdays{employee_daily}{$ref->{employee_id}}{$ref->{day}} = $ref->{flag}; $offdays{total_per_flag}{$ref->{employee_id}}{$ref->{flag}} ++; } $results = $dbh->prepare(" select employee_id,count(id) sessions, month(stamp)-1 month, day(stamp) day from employeesaccess where year(stamp)='$year' and month(stamp)=$R::reportmonth + 1 and shop_id = $shop{id} and operation = 1 group by employee_id,day; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref() ) { $workdays{$ref->{employee_id}}{$ref->{day}} = $ref->{sessions}; $workedpublicholidays{$ref->{employee_id}}{all}++ if ( ! $offdays{employee_daily}{ $ref->{employee_id} }{ $ref->{day} } and $publicholidays{$R::reportmonth}{$ref->{day}} ); } $temphtml .= "
    Report for $mnames{$R::reportmonth}, $R::year
    "; $temphtml .= "" foreach (sort keys %dayflags); $temphtml .= ""; $temphtml .= ""; #/grouping qry foreach my $id (sort {$a<=>$b} keys %employees) { $temphtml .=""; #/count'em $temphtml .= "" foreach (sort keys %dayflags); $temphtml .= ""; $temphtml .= ""; } #/foreach employee $temphtml .= "
    Employee Name$daytypes{$dayflags{$_}}Public holidays
    $employees{$id}".($offdays{total_per_flag}{$id}{$_}*1)."".($workedpublicholidays{$id}{all}*1)."
    "; $temphtml .= "Legend:
    "; $temphtml .= "$_ = $daytypes{$_}; " foreach (sort keys %daytypes); } #///CALENDAR }#/if employee provided $template =~ s/\@content\@/$temphtml/sgi; } elsif ($socketflag == 1 and $R::action eq "Budget Factors") {##Budget Factors## my $temphtml; my %replacer; $template =~ s/\@title\@//sgi; $temphtml = "
    "; if ($R::command eq "Update") { $mess = "Record for $shop{name}, $R::byear updated"; my @columns; $results = $dbh->prepare("SHOW COLUMNS FROM bucalendar;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while (my @vu = $results->fetchrow_array()) {push @columns, $vu[0] if ($vu[0] ne "id" and $vu[0] ne "shop_id" and $vu[0] ne "f_status" and $vu[0] ne "last_update")}; my ($sqlvals,@prepared); # cache for placeholder values #calculate section full turnover my $section_turnover = $R::sect_seats*($R::sect_capacity_usage/100)*$R::sect_covers_seat*$R::sect_spend_per_head*($R::sect_avg_seat_util/100); #calculate turnover for full seating $R::tover=$R::seats*$R::spend_per_head; $R::hotover=$R::rooms*$R::person_per_room*$R::ahs_hotel*($R::abu/100); foreach my $day (sort {$a<=>$b} keys %dnames) { $R::hoteloccup += eval("\$R::wah_".$dnames{$day}); } $R::hoteloccup = pr($R::hoteloccup/7);# 7 days a week - get average percent # Calculate the days in each month using module calendarz my %daysmonth; for($bstartmonth..12) {#3..12 my @arrche = calendarz::dayscounter($_, $R::byear); $daysmonth{$_-1} = \@arrche; } for(1..$bstartmonth-1) {#1..2 my @arrche = calendarz::dayscounter($_, $R::byear+1); $daysmonth{$_-1} = \@arrche; } # calculate the budget root values per month my %rootvalues; #{root_id}{year}{month} = value # CALCULATION OF THE FAMOUS SALES (WAR,TM from bucalendar) ID: 1 foreach (sort {$a<=>$b} keys %mnames) { my $monthto; foreach my $day (sort {$a<=>$b} keys %dnames) { $monthto += $R::tover * (eval("\$R::war_".$dnames{$day}) / 100) * # corrected turnover for this day (${$daysmonth{$_}}[$day]); # how many of this day in this month ? } #ideal month turnover total in $monthto $monthto *= (eval("\$R::tm_".$mnames{$_}) / 100); #adjusted monthly turnover for this month $monthto *= ($R::avg_heads_day/100) if ($R::avg_heads_day > 0); #adjust as per average heads per day #eval("\$R::tmv_".$mnames{$_}."=".$monthto); $rootvalues{1}{$R::byear}{$_} = $monthto; $rootvalues{5}{$R::byear}{$_} = $monthto*$R::proret_rest/100; } # CALCULATION OF THE RESTAURANT STAFF MEALS ID: 2 foreach (sort {$a<=>$b} keys %mnames) { my $monthsm; foreach my $day (sort {$a<=>$b} keys %dnames) { $monthsm += $R::staff_ml_rest * # corrected turnover for this day (${$daysmonth{$_}}[$day]) * 2; # how many of this day in this month ? } $rootvalues{2}{$R::byear}{$_} = $monthsm; } # CALCULATION OF THE RESTAURANT MANAGEMENT MEALS ID: 3 foreach (sort {$a<=>$b} keys %mnames) { my $monthsm; foreach my $day (sort {$a<=>$b} keys %dnames) { $monthsm += $R::man_ml_rest * # corrected turnover for this day (${$daysmonth{$_}}[$day]) * 2; # how many of this day in this month ? } $rootvalues{3}{$R::byear}{$_} = $monthsm; } # CALCULATION OF THE RESTAURANT STAFF TRANSPORT ID: 4 foreach (sort {$a<=>$b} keys %mnames) { my $monthsm; foreach my $day (sort {$a<=>$b} keys %dnames) { $monthsm += $R::staff_tr_rest * # corrected turnover for this day (${$daysmonth{$_}}[$day]) * 2; # how many of this day in this month ? } $rootvalues{4}{$R::byear}{$_} = $monthsm; } # CALCULATION OF THE HOTEL SALES ID: 6 foreach (sort {$a<=>$b} keys %mnames) { my $monthto=0; foreach my $day (sort {$a<=>$b} keys %dnames) { $monthto += $R::hotover * (eval("\$R::wah_".$dnames{$day}) / 100) * # corrected turnover for this day (${$daysmonth{$_}}[$day]); # how many of this day in this month ? } #ideal month turnover total in $monthto $monthto *= (eval("\$R::tm_".$mnames{$_}) / 100); #adjusted monthly turnover for this month $rootvalues{6}{$R::byear}{$_} = $monthto; } # CALCULATION OF THE HOTEL STAFF TRANSPORT ID: 7 foreach (sort {$a<=>$b} keys %mnames) { my $monthst; foreach my $day (sort {$a<=>$b} keys %dnames) { $monthst += $R::staff_tr_hotel * # corrected turnover for this day (${$daysmonth{$_}}[$day]) * 2; # how many of this day in this month ? } $rootvalues{7}{$R::byear}{$_} = $monthst; } # ROOT - OTHER INCOME (8) foreach (sort {$a<=>$b} keys %mnames) { $rootvalues{8}{$R::byear}{$_} = eval("\$R::oi_month$_"); } # CALCULATION OF SECTION SALES ID: 9 foreach (sort {$a<=>$b} keys %mnames) { my $monthto=0; foreach my $day (sort {$a<=>$b} keys %dnames) { $monthto += $section_turnover * (eval("\$R::sect_war_".$dnames{$day}) / 100) * # corrected turnover for this day (${$daysmonth{$_}}[$day]); # how many of this day in this month ? } #ideal month turnover total in $monthto $monthto *= (eval("\$R::tm_".$mnames{$_}) / 100); #adjusted monthly turnover for this month $rootvalues{9}{$R::byear}{$_} = $monthto; } #CREATE/UPDATE ROOT BUDGET CACHE VALUES #CHECK FOR EXISTING RECORDS my %rootcounts; $results = $dbh->prepare("select count(id) counter,calc_id,month from burootcache where byear=$R::byear and shop_id=$shop{id} group by calc_id,month;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $rootcounts{$ref->{calc_id}}{$ref->{month}} = $ref->{counter}; } #update BUROOTCACHE! foreach my $rootid (sort keys %rootvalues) { foreach my $month (sort {$a<=>$b} keys %mnames) { if ($rootcounts{$rootid}{$month} > 0) { $results = $dbh->do("UPDATE burootcache set value = '$rootvalues{$rootid}{$R::byear}{$month}' where shop_id=$shop{id} and byear=$R::byear and month=$month and calc_id=$rootid;") or die $dbh->errstr(); } else { $results = $dbh->do("INSERT into burootcache (shop_id,byear,month,calc_id,value) values ('$shop{id}','$R::byear','$month','$rootid','$rootvalues{$rootid}{$R::byear}{$month}');") or die $dbh->errstr(); } } } # #prepare SQL update $R::* -> SQL # @prepared=@columns; $_ = "$_='".eval("\$R::$_")."'" foreach (@prepared); $sqlvals = join (",", @prepared); $sqlvals .= ",f_status=1"; #update $results = $dbh->prepare("UPDATE bucalendar SET $sqlvals where shop_id=$shop{id} and byear=$R::byear;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); #STEVEN 2019-5-16 #we have 3 special fields: other_income_name,venue_name,sect_name . #let's check cost center to see if they are there . if NO. add , otherwise try to match and update . my $cost_hash = {}; $cost_hash->{other_income_name} = 'Other Income (' . $R::other_income_name .")"; $cost_hash->{venue_name} = 'Other Sales (' . $R::venue_name .")";#'Hotel Sales (' . $R::venue_name .")"; $cost_hash->{sect_name} = 'Section Sales (' . $R::sect_name .")"; my ($f_other_income,$f_venue,$f_sect); $results = $dbh->selectall_arrayref("SELECT * FROM stocktypes WHERE f_status < 100 AND shop_id=?",{ Slice=>{} },$shop{id}); foreach(@$results){ my $val = $_->{name}; #my $_val = $_->{name}; #$_val =~s/(\s+|\(|\))//g; #foreach my $key(keys %{$cost_hash}){ # my $val = $cost_hash->{$key}; # $val =~s/(\s+|\(|\))//g; $f_other_income = 1 if $val =~/OTHER\s+INCOME\s+\(/i;# && $val eq $_val; $f_venue = 1 if $val =~/OTHER\s+SALES\s+\(/i;# && $val eq $_val; $f_sect = 1 if $val =~/Section\s+Sales\s+\(/i;# && $val eq $_val; #} } if (!$f_other_income){ $dbh->do("insert into stocktypes set name=?,description=?,account_type=?,shop_id=?",undef, $cost_hash->{other_income_name},'',1,$shop{id}) ; }else{ #UPDATE $dbh->do("UPDATE stocktypes set name=? WHERE name LIKE '%Other income%' AND account_type=? and shop_id=?",undef, $cost_hash->{other_income_name} ,1,$shop{id}) ; } if(!$f_venue){ $dbh->do("insert into stocktypes set name=?,description=?,account_type=?,shop_id=?",undef, $cost_hash->{venue_name},'',1,$shop{id}) ; } else{ #UPDATE $dbh->do("UPDATE stocktypes set name=? WHERE name LIKE '%Other Sales%' AND account_type=? and shop_id=?",undef, $cost_hash->{venue_name}, 1,$shop{id}) ; } if(!$f_sect){ $dbh->do("insert into stocktypes set name=?,description=?,account_type=?,shop_id=?",undef, $cost_hash->{sect_name},'',1,$shop{id}); } else{ #UPDATE $dbh->do("UPDATE stocktypes set name=? WHERE name LIKE '%Section Sales%' AND account_type=? and shop_id=?",undef, $cost_hash->{sect_name}, 1,$shop{id}) ; } #2019-5-16 STEVEN END } #update command if ($R::command eq "Create") { $results = $dbh->prepare(" INSERT INTO bucalendar (byear,shop_id) values ($R::byear,$shop{id});") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } #create command #check for record $results = $dbh->prepare(" SELECT id FROM bucalendar WHERE byear=$R::byear and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{id}<=0) { #create if no record $temphtml .= "
    THERE IS NO BUDGET FOR $R::byear ?
    "; } else { #there is record go to update form $results = $dbh->prepare(" SELECT * FROM bucalendar WHERE byear=$R::byear and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $results->finish(); my %bucalendardata = %{$ref}; my %rootvalues; $results = $dbh->prepare(" SELECT * FROM burootcache WHERE byear=$R::byear and f_status<100 and shop_id=$shop{id} and calc_id=8;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $bucalendardata{"oi_month".$ref->{month}} = $ref->{value}; $rootvalues{8}{$R::byear}{$ref->{month}} = $ref->{value}; } $formhtml = getform("calendar", \%bucalendardata); $formhtml =~ s/%occup%/$replacer{occup}/gsi; ##STEVEN 2019-05-18 - changed %bcalcids to use dynamic name $results = $dbh->prepare("SELECT sect_name FROM bucalendar WHERE f_status<100 and shop_id = $shop{id} and byear=$R::byear;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $sect_name = $ref->{sect_name} ; my($other_income_name,$venue_name); $results = $dbh->selectall_arrayref("SELECT id,name from stocktypes WHERE account_type=1",{ Slice=>{} }) ; foreach(@$results){ $other_income_name = $_->{name} if $_->{name}=~/other\s+income\s+/i; $venue_name = $_->{name} if $_->{name}=~/other\s+sales\s+/i; } #Non-Income Turnover: Management Meals --> Non-Income Turnover: Promotions #Non-Income Turnover: Promo & Returns --> Non-Income Turnover: Discounts & Returns my %bcalcids = (1 => "Shop Sales", 2 => "Non-Income Turnover: Promotions", 3 => $sect_name ? "Section Sales($sect_name)" : "Section Sales" , #hide 4 => "Staff Transport", 5 => "Non-Income Turnover: Discounts & Returns", 6 => $venue_name||"Other Sales", 8 => $other_income_name||"Other Income" ); ##########END STEVEN ############################### #Lets now get the root cache calculations and display them nicely:) my $calchtml; $results = $dbh->prepare("SELECT * from burootcache where shop_id=$shop{id} and byear=$R::byear;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ $rootvalues{$ref->{calc_id}}{$R::byear}{$ref->{month}} = $ref->{value}; } $calchtml = ""; $calchtml .= ""; #2..11,0..2 for ($bstartmonth-1..11,0..$bstartmonth-2) {$calchtml .= ""} $calchtml .= ""; foreach (sort keys %bcalcids) { $calchtml .= ""; #2..11,0..2 for my $month ($bstartmonth-1..11,0..$bstartmonth-2) {$calchtml .= ""} $calchtml .= ""; } $calchtml .= "
    Calculation$mnames{$_}
    $bcalcids{$_}".pr($rootvalues{$_}{$R::byear}{$month})."
    "; $formhtml =~ s/%calcs%/$calchtml/sgi; $formhtml =~ s/\@shopname\@/$shop{name}/sgi; $temphtml .= $formhtml; } # update form $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } #/ END Budget ACTION elsif ($socketflag == 1 and $R::action eq "Fixed Costs Editor") { my $moveturnoveshtml = 0; $onload="document.form1.name.focus();" if ($R::command ne "Modify Data"); my $temphtml; my $mturnover; #month turnover from bucalendar my %rootval; #listmenu is givving month id if ($R::monthid ne "") {$tempdb{current_month_id} = $R::monthid} if ($tempdb{current_month_id} eq "") {$tempdb{current_month_id} = 2} my %bgroups = (1=>"COST OF SALES",2=>"FIXED COSTS",3=>"SALARIES & WAGES - (Cost to Company)",4=>"Capital Expenses"); my %btotals; $template =~ s/\@title\@/Budget for $months{$tempdb{current_month_id}+1} $R::byear /sgi; $temphtml = "
    "; #commands Fixed Costs if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { my ($vtype,$vsource); #determine the vtype (1,2,3) if ($R::source eq "source" and ! $R::total) {$vtype = 1; } if ($R::source ne "source" and ! $R::total) {$vtype = 2; $vsource=$R::source} if ($R::source eq "source" and $R::total and $R::master eq "master") {$vtype = 3; } #create year record with value for the current month #determine is this a master or child entry my $parent; if ($R::master eq "master") { $parent = "NULL" } else { $parent = $R::master; $results = $dbh->prepare("SELECT grp FROM bufc WHERE id='$R::master' and shop_id=$shop{id} and year=$R::byear;"); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $R::group= $ref->{grp}; } #create the record $results = $dbh->prepare(" INSERT INTO bufc (shop_id, year, grp, name, code, type, vtype,factorsrc, parent) values ('$shop{id}','$R::byear','$R::group','$R::name','$R::code','$R::type','$vtype',?,".$parent.");"); $results->execute($vsource) or die $results->errstr(); #get new id for value purposes $results = $dbh->prepare("SELECT LAST_INSERT_ID() lastid FROM bufc limit 1;"); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $lastid = $ref->{lastid}; $R::id = $lastid; #create the value record $results = $dbh->prepare(" INSERT INTO bufc_values (shop_id, month, bufc_id, value) values ('$shop{id}','$tempdb{current_month_id}','$lastid','$R::value');"); $results->execute() or die $results->errstr(); $mess = "NEW RECORD $R::name CREATED"; } elsif ($R::command eq "delete") { #delete for year $results = $dbh->prepare(" UPDATE bufc SET f_status=101 WHERE shop_id=$shop{id} and id=$R::id or parent=$R::id;"); $results->execute() or die $results->errstr(); #delete values $results = $dbh->prepare(" UPDATE bufc_values SET f_status=101 WHERE shop_id=$shop{id} and bufc_id=$R::id;"); $results->execute() or die $results->errstr(); #delete values of children $results = $dbh->prepare(" SELECT id FROM bufc WHERE parent=$R::id and shop_id=$shop{id};"); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $subresults = $dbh->prepare(" UPDATE bufc_values SET f_status=101 WHERE shop_id=$shop{id} and bufc_id=$ref->{id};"); $subresults->execute() or die $subresults->errstr(); } $mess = "RECORD DELETED"; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { my ($vtype,$vsource); #determine the vtype (1,2,3) if ($R::source eq "source" and ! $R::total) {$vtype = 1; } if ($R::source ne "source" and ! $R::total) {$vtype = 2; $vsource=$R::source} if ($R::source eq "source" and $R::total and $R::master eq "master") {$vtype = 3; } #modify year record with value for the current month #determine is this a master or child entry my $parent; if ($R::master eq "master") { $parent = "NULL" } else { $parent = $R::master; $results = $dbh->prepare("SELECT grp FROM bufc WHERE id='$R::master' and shop_id=$shop{id} and year=$R::byear;"); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $R::group= $ref->{grp}; } #modify the record $results = $dbh->prepare(" UPDATE bufc SET grp='$R::group', name='$R::name', code='$R::code', type='$R::type', vtype='$vtype', factorsrc=?, parent=".$parent.",f_status=1 WHERE id='$R::id' and shop_id=$shop{id} and year='$R::byear';"); $results->execute($vsource) or die $results->errstr(); #CREATE VALUE RECORDS IF NEEDED, because we use only update for the values table below $subresults1 = $dbh->prepare(" SELECT count(id) count FROM bufc_values WHERE month='$tempdb{current_month_id}' and bufc_id='$R::id' and f_status<100 and shop_id=$shop{id};"); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); if (! $subref1->{count}) { #no value record for this month and this budget item; create $results = $dbh->do("INSERT INTO bufc_values (shop_id, month, bufc_id) values ('$shop{id}','$tempdb{current_month_id}','$R::id');") or die $dbh->errstr(); } #modify the value record $results = $dbh->prepare(" UPDATE bufc_values SET value='$R::value', f_status=1 where shop_id = '$shop{id}' and month='$tempdb{current_month_id}' and bufc_id='$R::id';"); $results->execute() or die $results->errstr(); # move children to new parent if current parent is child already if ($parent ne "NULL") { $results = $dbh->prepare(" UPDATE bufc SET parent=".$parent.", f_status=1 WHERE parent='$R::id' and shop_id=$shop{id} and year='$R::byear';"); $results->execute() or die $results->errstr(); } # change group of children $results = $dbh->prepare(" UPDATE bufc SET grp='$R::group',f_status=1 WHERE parent='$R::id' and shop_id=$shop{id} and year='$R::byear';"); $results->execute() or die $results->errstr(); $mess = "RECORD MODIFIED"; } elsif ($R::command eq "copy") { my (@mlist,$mslice,@budgetids,%vals); if ($tempdb{current_month_id} > 1) { @mlist = ($tempdb{current_month_id}..11,0..1); } else { @mlist = ($tempdb{current_month_id}..1); } #fetch all budget record ids $results = $dbh->prepare(" SELECT id FROM bufc WHERE year=$R::byear and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) {push (@budgetids,$ref->{id})} #fetch all budget values for the current month from values table my $bufcids; $bufcids = join (",",@budgetids); $subresults1 = $dbh->prepare(" SELECT value,bufc_id FROM bufc_values WHERE bufc_id in($bufcids) and month='$tempdb{current_month_id}' and f_status<100 and shop_id=$shop{id};"); $subresults1->execute() or die $subresults1->errstr(); while ($subref1 = $subresults1->fetchrow_hashref()) {$vals{$subref1->{bufc_id}}=$subref1->{value}} #CREATE VALUE RECORDS IF NEEDED, because we use only update for the values table below foreach my $bid (@budgetids) { foreach my $mid (@mlist) { $subresults1 = $dbh->prepare(" SELECT count(id) count FROM bufc_values WHERE month='$mid' and bufc_id='$bid' and f_status<100 and shop_id=$shop{id};"); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); if (! $subref1->{count}) { #no value record for this month and this budget item; create $results = $dbh->do("INSERT INTO bufc_values (shop_id, month, bufc_id) values ('$shop{id}','$mid','$bid');") or die $dbh->errstr(); } } } # slice of months to update values $mslice = join (",", @mlist); foreach (@budgetids) { $results = $dbh->do(" UPDATE bufc_values SET value='$vals{$_}',f_status=1 where shop_id = '$shop{id}' and month in($mslice) and bufc_id='$_';"); } } #copy command #get month turnover root values my %root_values; $results = $dbh->prepare("SELECT * from burootcache where shop_id=$shop{id} and byear=$R::byear;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ $root_values{$ref->{calc_id}}{$R::byear}{$ref->{month}} = $ref->{value}; } # create months listmenu my ($listhtml,%monthsel); $monthsel{$tempdb{current_month_id}} = "SELECTED"; $listhtml = "CHANGE MONTH:

    "; $temphtml .= $listhtml; #javascript for radio buttons $temphtml .= qq~ ~; #draw table for the fc budget $temphtml .= " Jump to Modified Record "; $temphtml .= $table{start}; $temphtml .= " grp cat src [Code] Name Factor Value a.type Commands "; my ($modifiedgroup, $groupsel, %mturnsel,$sourcesel, $mastersel, $modifiedparent, $modifiedvaluetext); $modifiedvaluetext="value (R)"; $modifiedgroup = 1; #fetch radio states for modify if ($R::command eq "modify") { #retreive value type for the modified value $results = $dbh->prepare(" SELECT vtype,parent,grp,factorsrc FROM bufc WHERE id=$R::id and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $modifiedgroup = $ref->{grp}; #used to select group $modifiedparent = $ref->{parent}; #used to select master $mastersel = "checked" if (! $ref->{parent}); #this is master if ($ref->{vtype} == 2) {$mturnsel{$ref->{factorsrc}} = "checked"; $modifiedvaluetext="value (R)"} else {$sourcesel = "checked"}; } my $turnovershtml; $turnovershtml .= "     SHOP SALES (Gross Shop Sales + Hotel Sales + O.Income) $currency".pr( $root_values{1}{$R::byear}{$tempdb{current_month_id}}+ $root_values{6}{$R::byear}{$tempdb{current_month_id}}+ $root_values{3}{$R::byear}{$tempdb{current_month_id}}+ $root_values{5}{$R::byear}{$tempdb{current_month_id}}+ $root_values{8}{$R::byear}{$tempdb{current_month_id}}+ $root_values{9}{$R::byear}{$tempdb{current_month_id}})."Index 1   "; $rootval{1} = $root_values{1}{$R::byear}{$tempdb{current_month_id}}+ $root_values{6}{$R::byear}{$tempdb{current_month_id}}+ $root_values{3}{$R::byear}{$tempdb{current_month_id}}+ $root_values{5}{$R::byear}{$tempdb{current_month_id}}+ $root_values{8}{$R::byear}{$tempdb{current_month_id}}+ $root_values{9}{$R::byear}{$tempdb{current_month_id}}; $turnovershtml .= "        NET SALES $currency".pr($root_values{1}{$R::byear}{$tempdb{current_month_id}})."Index 2   "; $rootval{2} = $root_values{1}{$R::byear}{$tempdb{current_month_id}}; $turnovershtml .= "        SECTION SALES $currency".pr($root_values{9}{$R::byear}{$tempdb{current_month_id}})."Index 9   "; $rootval{9} = $root_values{9}{$R::byear}{$tempdb{current_month_id}}; $turnovershtml .= "        SHOP & SECTION SALES $currency".pr($root_values{1}{$R::byear}{$tempdb{current_month_id}}+ $root_values{9}{$R::byear}{$tempdb{current_month_id}})."Index 10   "; $rootval{10} = $root_values{1}{$R::byear}{$tempdb{current_month_id}} + $root_values{9}{$R::byear}{$tempdb{current_month_id}}; $turnovershtml .= "        OTHER INCOME $currency".pr($root_values{8}{$R::byear}{$tempdb{current_month_id}})."Index 8   "; $rootval{8} = $root_values{8}{$R::byear}{$tempdb{current_month_id}}; $turnovershtml .= "        Non-Income Turnover: Promotions $currency".pr($root_values{3}{$R::byear}{$tempdb{current_month_id}})."Index 3   "; $rootval{3} = $root_values{3}{$R::byear}{$tempdb{current_month_id}}; $turnovershtml .= "        Non-Income Turnover: Discounts & Returns $currency".pr($root_values{5}{$R::byear}{$tempdb{current_month_id}})."Index 4   "; $rootval{4} = $root_values{5}{$R::byear}{$tempdb{current_month_id}}; $turnovershtml .= "     GROSS SALES (=net shop sales + non-income t/o) $currency".pr($root_values{1}{$R::byear}{$tempdb{current_month_id}}+ $root_values{5}{$R::byear}{$tempdb{current_month_id}}+ $root_values{3}{$R::byear}{$tempdb{current_month_id}})."Index 5   "; $rootval{5} = $root_values{1}{$R::byear}{$tempdb{current_month_id}}+ $root_values{5}{$R::byear}{$tempdb{current_month_id}}+ $root_values{3}{$R::byear}{$tempdb{current_month_id}}; $turnovershtml .= "     HOTEL SALES $currency".pr($root_values{6}{$R::byear}{$tempdb{current_month_id}})."Index 6   "; $rootval{6} = $root_values{6}{$R::byear}{$tempdb{current_month_id}}; $turnovershtml .= "     NET SALES + HOTEL SALES $currency".pr($root_values{6}{$R::byear}{$tempdb{current_month_id}} + $root_values{1}{$R::byear}{$tempdb{current_month_id}})."Index 7   "; $rootval{7} = $root_values{6}{$R::byear}{$tempdb{current_month_id}} + $root_values{1}{$R::byear}{$tempdb{current_month_id}}; $temphtml .= $turnovershtml if ($R::command ne "modify" or ($R::command eq "modify" and ! $moveturnoveshtml) ); # IF WAGES MODIFY - do predefined db values for the listed items if ($R::command eq "Re-Calculate Wages" or ($R::command eq "" and $R::hcommand eq "Re-Calculate Wages")) { my $shop_id = $shop{id}; my @byears; my %rootval = (); my %root_values; $byears[0] = $R::byear; my @kids=("[Restaurant Staff Meals]","[Restaurant Management Meals]","[Restaurant Staff Transport]","[Hotel Staff Transport]","[PAYE]","[UIF]","[SETA]","[WCA]","[CMC]"); my %kid_ids; foreach my $byear (@byears) { $results = $dbh->prepare("SELECT * from burootcache where shop_id=$shop_id and byear=$byear;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ $root_values{$ref->{calc_id}}{$byear}{$ref->{month}} = $ref->{value}; } foreach my $name (@kids) { $results = $dbh->prepare("select id from bufc where name like ? and year=$byear and shop_id=$shop_id;") or die $dbh->errstr(); $results->execute($name) or die $results->errstr(); $ref = $results->fetchrow_hashref(); $kid_ids{$name} = $ref->{id}; } for my $month (0..11) { $rootval{1} = $root_values{1}{$byear}{$month}+ $root_values{6}{$byear}{$month}+ $root_values{3}{$byear}{$month}+ $root_values{5}{$byear}{$month}+ $root_values{8}{$byear}{$month}+ $root_values{9}{$byear}{$month}; $rootval{2} = $root_values{1}{$byear}{$month}; $rootval{3} = $root_values{3}{$byear}{$month}; $rootval{4} = $root_values{5}{$byear}{$month}; $rootval{5} = $root_values{1}{$byear}{$month}+ $root_values{5}{$byear}{$month}+ $root_values{3}{$byear}{$month}; $rootval{6} = $root_values{6}{$byear}{$month}; $rootval{7} = $root_values{6}{$byear}{$month}+ $root_values{1}{$byear}{$month}; $rootval{8} = $root_values{8}{$byear}{$month}; $rootval{9} = $root_values{9}{$byear}{$month}; $rootval{10} = $rootval{9}+ $rootval{2}; my $flagche = 0; foreach my $name (@kids) { my $calculation; #check the names # print "BYear: $byear Shop: $shop_id MONTH: $month KID: $name "; if ($name eq "[PAYE]" or $name eq "[UIF]" or $name eq "[SETA]" or $name eq "[WCA]" or $name eq "[CMC]" ) { #wages related my $wages; my $pension_fund; #get the wages $results = $dbh->prepare(" SELECT bu.id id,bu.vtype vtype, bv.value value FROM bufc bu, bufc_values bv WHERE bu.year=$byear and bu.f_status<100 and bu.shop_id=$shop_id and bv.f_status<100 and bv.shop_id=$shop_id and bv.month='$month' and bv.bufc_id=bu.id and (bu.name like 'wages' or bu.name like 'management SALARIES' or bu.name like 'management WAGES');") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($ref->{vtype} == 3) { my $ctotal; $subresults = $dbh->prepare(" SELECT * FROM bufc WHERE parent=$ref->{id} and year=$byear and f_status<100 and shop_id=$shop_id;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { #retreiving values $subresults1 = $dbh->prepare(" SELECT value FROM bufc_values WHERE month='$month' and bufc_id=$subref->{id} and f_status<100 and shop_id=$shop_id;"); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); $subresults1->finish(); if ($subref->{vtype} == 2) { $ctotal += $rootval{$subref->{factorsrc}} * ($subref1->{value}/100)} elsif ($subref->{vtype} == 1) {$ctotal += $subref1->{value}} } $wages += $ctotal; } elsif ($ref->{vtype} == 2) { my $percents = $rootval{$ref->{factorsrc}} * ($ref->{value}/100); $wages += $percents; } elsif ($ref->{vtype} == 1) { $wages += $ref->{value}; } } # get pension fund; $results = $dbh->prepare(" SELECT bu.id id,bu.vtype vtype, bv.value value FROM bufc bu, bufc_values bv WHERE bu.year=$byear and bu.f_status<100 and bu.shop_id=$shop_id and bv.f_status<100 and bv.shop_id=$shop_id and bv.month='$month' and bv.bufc_id=bu.id and bu.name like 'PENSION FUND%';") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $pension_fund = $ref->{value}; my %wf; $results = $dbh->prepare("select wf_paye/100 wf_paye, wf_uif/100 wf_uif, wf_seta, wf_wca, wf_cmc1, wf_cmc2 from bucalendar where shop_id=$shop_id and byear=$byear;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $wf{wf_paye}=$ref->{wf_paye};$wf{wf_uif}=$ref->{wf_uif};$wf{wf_seta}=$ref->{wf_seta};$wf{wf_wca}=$ref->{wf_wca};$wf{wf_cmc1}=$ref->{wf_cmc1};$wf{wf_cmc2}=$ref->{wf_cmc2}; my ($paye, $uif, $seta, $wca, $cmc); $paye = $wages*$wf{wf_paye}; $uif = ($wages+$paye + $pension_fund)*$wf{wf_uif}; $seta = ($wages + $uif + $paye + $pension_fund)*$wf{wf_seta}; $wca = ($wages + $uif + $paye + $pension_fund)*$wf{wf_wca}; $cmc = ($wages + $uif + $paye + $pension_fund)*$wf{wf_cmc1} + $rootval{1}*$wf{wf_cmc2}; if ($name eq "[PAYE]") { $flagche = 1; $calculation = $paye; } elsif ($name eq "[UIF]") { $flagche = 1; $calculation = $uif; } elsif ($name eq "[SETA]") { $flagche = 1; $calculation = $seta; } elsif ($name eq "[WCA]") { $flagche = 1; $calculation = $wca; } elsif ($name eq "[CMC]") { $flagche = 1; $calculation = $cmc; } else { $flagche = 0; } #end case } else { #non-wages related if ($name eq "[Restaurant Staff Meals]") { $flagche = 1; $calculation = $root_values{2}{$byear}{$month}; } elsif ($name eq "[Restaurant Management Meals]") { $flagche = 1; $calculation = $root_values{3}{$byear}{$month}; } elsif ($name eq "[Restaurant Staff Transport]") { $flagche = 1; $calculation = $root_values{4}{$byear}{$month}; } elsif ($name eq "[Hotel Staff Transport]") { $flagche = 1; $calculation = $root_values{7}{$byear}{$month}; } else { $flagche = 0; } #end case } # wages related ? END if ($flagche > 0) { # $temphtml .= "$name updated
    "; $results = $dbh->prepare(" UPDATE bufc_values SET value='$calculation', f_status=1 where shop_id = '$shop_id' and month='$month' and bufc_id='$kid_ids{$name}';"); $results->execute() or die $results->errstr(); # debug print "**ROWS** ".$results->rows." ($calculation)\n"; } } #kids } #months } #byears } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { my $byear = $R::byear; if ($bgroups{$R::group} =~ /WAGES/si) {# the right group } } # DISPLAY GROUPS foreach my $group (sort {$a<=>$b} keys %bgroups) { #groups selected my ($gctotal,$ctotal); $subresults = $dbh->prepare(" SELECT * FROM bufc WHERE grp=$group and vtype in(1,2) and year=$R::byear and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { #retreiving values $subresults1 = $dbh->prepare(" SELECT value FROM bufc_values WHERE month='$tempdb{current_month_id}' and bufc_id=$subref->{id} and f_status<100 and shop_id=$shop{id};"); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); #$subresults1->finish(); if ($subref->{vtype} == 2) { $gctotal += $rootval{$subref->{factorsrc}} * ($subref1->{value}/100);} elsif ($subref->{vtype} == 1) {$gctotal += $subref1->{value};} } if ($group == $modifiedgroup) {$groupsel = "checked"} else {$groupsel = ""}; $temphtml .= " $bgroups{$group} $currency \@gtotal$group\@ "; $results = $dbh->prepare(" SELECT * FROM bufc WHERE parent is NULL and grp=$group and year=$R::byear and f_status<100 and shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::id != $ref->{id}) ) { my $msel; $msel = "checked" if ($ref->{id} == $modifiedparent); $temphtml .= "{id}) ? "class=ccel" : "" ).">   {id} onClick=\"document.all.tot.innerText=''\"> ".( $ref->{factorsrc} > 0 ? " [$ref->{factorsrc}] " : " ")." {vtype} == 3); $temphtml .= ">".( ($R::id == $ref->{id}) ? " [M] " : "" )."{id}&command=modify\">[$ref->{code}] $ref->{name}"; #retreiving values $subresults1 = $dbh->prepare(" SELECT value FROM bufc_values WHERE month='$tempdb{current_month_id}' and bufc_id=$ref->{id} and f_status<100 and shop_id=$shop{id};"); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); $subresults1->finish(); if ($ref->{vtype} == 3) { my $ctotal; $subresults = $dbh->prepare(" SELECT * FROM bufc WHERE parent=$ref->{id} and year=$R::byear and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while ($subref = $subresults->fetchrow_hashref()) { #retreiving values $subresults1 = $dbh->prepare(" SELECT value FROM bufc_values WHERE month='$tempdb{current_month_id}' and bufc_id=$subref->{id} and f_status<100 and shop_id=$shop{id};"); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); $subresults1->finish(); if ($subref->{vtype} == 2) { $ctotal += $rootval{$subref->{factorsrc}} * ($subref1->{value}/100)} elsif ($subref->{vtype} == 1) {$ctotal += $subref1->{value}} } $temphtml .= "total: $currency".pr($ctotal).""; } elsif ($ref->{vtype} == 2) { my $percents = $rootval{$ref->{factorsrc}} * ($subref1->{value}/100); $temphtml .= "$subref1->{value}%$currency".pr($percents).""; } elsif ($ref->{vtype} == 1) { $temphtml .= " $currency".pr($subref1->{value}).""; } #check vs purchases whether there is usage of the item $subresults = $dbh->prepare(" select max(id) lastid from purchases where othertype = '$ref->{id}' and f_status<101 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $othertypeusage = $subref->{lastid}; #check for children $subresults = $dbh->prepare(" select id lastid from bufc where parent = '$ref->{id}' and f_status<101 and shop_id=$shop{id};") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $othertypeusage += $subref->{lastid}; $temphtml .= " $bufctype{$ref->{type}} "; $temphtml .= "{id}&command=delete\" onclick=\"return confirm('DELETE: $ref->{name} ?');\">$icons{d} " if (! $othertypeusage); $temphtml .= "{id}&command=modify\">$icons{m} "; } else { # MODIFY LINE $temphtml .= $turnovershtml if ($moveturnoveshtml); my (%typesel,$valsel, $totsel); $typesel{$ref->{type}} = "checked"; $totsel = "checked" if ($ref->{vtype} == 3); #retreiving values $subresults1 = $dbh->prepare(" SELECT value FROM bufc_values WHERE month='$tempdb{current_month_id}' and bufc_id=$ref->{id} and f_status<100 and shop_id=$shop{id};"); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); $subresults1->finish(); $valsel = $subref1->{value} if ($ref->{vtype} == 1 or $ref->{vtype} == 2); $temphtml .= "  
    {code}\">{name}\"> TOTAL
    **value (R)
    "; } # fetch children $subresults = $dbh->prepare(" SELECT * FROM bufc WHERE parent=$ref->{id} and year=$R::byear and f_status<100 and shop_id=$shop{id} ORDER BY name;") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); while($subref = $subresults->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::id != $subref->{id}) ) { #$temphtml .= "" if ($R::id == $subref->{id}); $temphtml .= "{id}) ? "class=ccel" : "" ).">     ".( $subref->{factorsrc} > 0 ? " [$subref->{factorsrc}] " : " ")."     ".( ($R::id == $subref->{id}) ? " [M] " : "" )."$icons{corn} {id}&command=modify\">[$subref->{code}] $subref->{name}"; #retreiving values $subresults1 = $dbh->prepare(" SELECT value FROM bufc_values WHERE month='$tempdb{current_month_id}' and bufc_id=$subref->{id} and f_status<100 and shop_id=$shop{id};"); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); $subresults1->finish(); if ($subref->{vtype} == 2) { my $percents = $rootval{$subref->{factorsrc}} * ($subref1->{value}/100); $temphtml .= "$subref1->{value}%$currency".pr($percents).""; } elsif ($subref->{vtype} == 1) { $temphtml .= " $currency".pr($subref1->{value}).""; } $temphtml .=" $bufctype{$subref->{type}} "; #check vs purchases whether there is usage of the item $subresults1 = $dbh->prepare(" select max(id) lastid from purchases where othertype = '$subref->{id}' and f_status<101 and shop_id=$shop{id} "); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); my $othertypeusage1 = $subref1->{lastid}; $temphtml .="{id}&command=delete\" onclick=\"return confirm('DELETE: $subref->{name} ?');\">$icons{d} " if (! $othertypeusage1); $temphtml .="{id}&command=modify\">$icons{m} "; } else { #submodify $temphtml .= $turnovershtml if ($moveturnoveshtml); my (%typesel,$valsel); $typesel{$subref->{type}} = "checked"; #retreiving values $subresults1 = $dbh->prepare(" SELECT value FROM bufc_values WHERE month='$tempdb{current_month_id}' and bufc_id=$subref->{id} and f_status<100 and shop_id=$shop{id};"); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); $subresults1->finish(); $valsel = $subref1->{value} if ($subref->{vtype} == 1 or $subref->{vtype} == 2); $temphtml .= "  
        $icons{corn} {code}\">{name}\">
    value (R)
    "; } } #subwhile } #masters/parents while #puting/calculating group totals if ($group == 1) { my $display=pr($gctotal); $temphtml =~ s/\@gtotal$group\@/$display/gsi ; $btotals{$group} = $gctotal; }elsif ($group == 2) { $subresults = $dbh->prepare(" SELECT bu.vtype, bv.value value FROM bufc bu, bufc_values bv WHERE bu.year=$R::byear and bu.f_status<100 and bu.shop_id=$shop{id} and bv.f_status<100 and bv.shop_id=$shop{id} and bv.month='$tempdb{current_month_id}' and bv.bufc_id=bu.id and bu.name like 'service fees%'") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); my $display=pr($gctotal); $temphtml =~ s/\@gtotal$group\@/$display/gsi; $btotals{$group} = $gctotal; } elsif ($group == 3) { my $display=pr($gctotal); $temphtml =~ s/\@gtotal$group\@/$display/gsi; $btotals{$group} = $gctotal; # totals my $totals; $totals = $rootval{1} - $btotals{1}; $temphtml .= "
  • GROSS PROFIT $currency".pr($totals)." "; $totals = $btotals{2} + $btotals{3}; $temphtml .= "
  • TOTAL FIXED COST $currency".pr($totals)." "; $totals = ($rootval{1} - $btotals{1}); $totals -= ($btotals{2} + $btotals{3}); $temphtml .= "
  • NETT INCOME/(EXPENSE) $currency".pr($totals)." "; } elsif ($group == 4) { my $display=pr($gctotal); $temphtml =~ s/\@gtotal$group\@/$display/gsi; $btotals{$group} = $gctotal; } } #foreach bgroups #commands bufc if ($R::command ne "modify") { $subresults = $dbh->prepare(" SELECT max(id) maxid from bufc ") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $subref->{maxid} += 1; $temphtml .= "  
    {maxid}\"> TOTAL
    value (R)
    "; } # modify check $temphtml .= qq ~ Jump to Modified Record ~; $temphtml .= $table{end}; $temphtml .= "
    Populate values from this month to the end of the year"; $temphtml .= ""; $temphtml .= ""; $temphtml .= "

    "; $temphtml .= "
    "x300; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
  • "; $template =~ s/\@content\@/$temphtml/sgi; } #/ END FixCost Budget ACTION elsif ($socketflag == 1 and $R::action eq "Copy Budget") { my $temphtml = ""; $template =~ s/\@title\@/Copy Budget/sgi; $temphtml = "
    "; #logit("$sys_settings{'shop_id'} =>$sys_settings{'location'}"); #print "HERE!!! $R::action"; if ($R::command eq "Copy Budget" and $R::syear and $R::dyear and $R::sshopid and $R::dshopid) { my %shopname = ($sys_settings{'shop_id'} =>$sys_settings{'location'} );#($settings::shop_id => $settings::location); # if ($R::syear==$R::dyear and $R::sshopid==$R::dshopid) { $temphtml .= "$error Cannot copy the same year and the same shop

    " } else { # COPY CALENDAR my @columns; $results = $dbh->prepare("SHOW COLUMNS FROM bucalendar;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while (my @vu = $results->fetchrow_array()) {push @columns, $vu[0] if ($vu[0] ne "id" and $vu[0] ne "shop_id" and $vu[0] ne "f_status" and $vu[0] ne "last_update")} # get calendar from source $results = $dbh->prepare(" SELECT * FROM bucalendar WHERE byear=$R::syear and f_status<100 and shop_id=$R::sshopid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $results->finish(); my ($sqlvals,@prepared); ## ## TEMPORARY SECTION - TO BE OPTIMIZED ## my %daysmonth = ( 0 => [4,4,4,5,5,5,4], #2004 1 => [4,4,4,4,4,4,5], #2004 2 => [5,4,4,4,4,5,5], 3 => [4,5,5,4,4,4,4], 4 => [4,4,4,5,5,5,4], 5 => [5,4,4,4,4,4,5], 6 => [4,5,5,5,4,4,4], 7 => [4,4,4,4,5,5,5], 8 => [5,5,4,4,4,4,4], 9 => [4,4,5,5,5,4,4], 10 => [4,4,4,4,4,5,5], 11 => [5,5,5,4,4,4,4] ); foreach (sort {$a<=>$b} keys %mnames) { my $monthto; foreach my $day (sort {$a<=>$b} keys %dnames) { $monthto += $ref->{tover} * (eval("\$ref->{td_".$dnames{$day}."}") / 100) * # corrected turnover for this day (${$daysmonth{$_}}[$day]); # how many of this day in this month ? } #ideal month turnover total in $monthto $monthto *= (eval("\$ref->{tm_".$mnames{$_}."}") / 100); #adjusted monthly turnover for this month eval("\$ref->{tmv_".$mnames{$_}."}"."=".$monthto); } # #prepare SQL update $ref->* -> SQL # $ref->{byear} = $R::dyear; @prepared=@columns; $_ = "$_='".eval("\$ref->{$_"."}")."'" foreach (@prepared); $sqlvals = join (",", @prepared); $sqlvals .= ",f_status=1"; #check for record $results = $dbh->prepare(" SELECT id FROM bucalendar WHERE byear=$R::dyear and f_status<100 and shop_id=$R::dshopid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); if ($ref->{id}<=0) { #create if no record $results = $dbh->prepare(" INSERT INTO bucalendar (byear,shop_id) values ($R::dyear,$R::dshopid);") or die $dbh->errstr(); $results->execute() or die $results->errstr(); } #update $results = $dbh->prepare("UPDATE bucalendar SET $sqlvals where shop_id='$R::dshopid' and byear='$R::dyear' and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); # COPY BUDGET FCOSTS #delete existing records for destination #delete destination values! $results = $dbh->prepare("SELECT * FROM bufc WHERE shop_id='$R::dshopid' and year='$R::dyear' and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $subresults = $dbh->do("UPDATE bufc_values SET f_status=101 WHERE bufc_id=$ref->{id} and f_status<100;") or die $dbh->errstr(); } #delete destination bufc $subresults = $dbh->do("UPDATE bufc SET f_status=101 WHERE shop_id='$R::dshopid' and year='$R::dyear' and f_status<100;") or die $dbh->errstr(); my %crossed; #copy bufc and store crosslinks to update parents ids with the inserted parent ids $results = $dbh->prepare("SELECT * FROM bufc WHERE shop_id='$R::sshopid' and year='$R::syear' and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { #copy straight $ref->{parent} = "NULL" if (! $ref->{parent}); $subresults = $dbh->prepare("INSERT INTO bufc (shop_id,year,grp,name,type,vtype,parent,factorsrc) values ('$R::dshopid','$R::dyear','$ref->{grp}','$ref->{name}','$ref->{type}','$ref->{vtype}',".$ref->{parent}.",'$ref->{factorsrc}');") or die $dbh->errstr(); $subresults->execute() or die $subresults->errstr(); #get new id for %crossed $subresults = $dbh->prepare("SELECT LAST_INSERT_ID() lastid FROM bufc limit 1;"); $subresults->execute() or die $subresults->errstr(); $subref = $subresults->fetchrow_hashref(); $crossed{$ref->{id}} = $subref->{lastid}; } #update with new parents from crossed foreach (keys %crossed) { $subresults = $dbh->prepare("UPDATE bufc SET parent='$crossed{$_}',f_status=1 where parent=$_ and shop_id='$R::dshopid' and year='$R::dyear' and f_status<100;"); $subresults->execute() or die $subresults->errstr(); } #create the new bufc_values for march #fetch all budget values for the current month from values table my %vals; my $bufcids; $bufcids = join (",",keys %crossed); $subresults1 = $dbh->prepare(" SELECT value,bufc_id FROM bufc_values WHERE bufc_id in($bufcids) and month='$bstartmonth' and f_status<100 and shop_id='$R::sshopid';"); $subresults1->execute() or die $subresults1->errstr(); while ($subref1 = $subresults1->fetchrow_hashref()) {$vals{$subref1->{bufc_id}}=$subref1->{value}} foreach my $bid (values %crossed) { $results = $dbh->do("INSERT INTO bufc_values (shop_id, month, bufc_id) values ('$R::dshopid','2','$bid');") or die $dbh->errstr(); } foreach (keys %crossed) { $results = $dbh->do(" UPDATE bufc_values SET value='$vals{$_}',f_status=1 where shop_id = '$R::dshopid' and month=2 and bufc_id='$crossed{$_}';"); } #PRINT SUCCESS $temphtml .= "Copy completed.
    Budget database from $shopname{$R::sshopid}, year $R::syear
    successfuly transfered to $shopname{$R::dshopid}, year $R::dyear
    "; } } else { my %shopname = ($sys_settings{'shop_id'}=>$sys_settings{'location'});#($settings::shop_id => $settings::location); # $temphtml .= " Please provide the information required below

    "; %formvars = (); $formvars{syear} = $R::syear; $formvars{dyear} = $R::dyear; $formhtml = getform("copybudget",\%formvars); $temphtml = $formhtml; my $listhtml; $listhtml = ""; $temphtml =~ s/\@sshops\@/$listhtml/sgi; $listhtml = ""; $temphtml =~ s/\@dshops\@/$listhtml/sgi; } $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; $temphtml = ""; } elsif ($socketflag == 1 and $R::action eq "Budget Report") { my $temphtml; my $ltemp; my $mturnover; #month turnover from bucalendar #listmenu is givving byear id if ($R::byearid ne "") {$tempdb{budget_byear_id} = $R::byearid;} if (! $tempdb{budget_byear_id}) {$tempdb{budget_byear_id} = 2006;} my $byear = $tempdb{budget_byear_id}; $template =~ s/\@title\@/Budget report $byear /sgi; $temphtml = "
    "; my %reportcolumns = ( '1'=>'BUDGET', '2'=>'ACTUAL', '3'=>'FORECAST', '4'=>'BUDGET vs FORECAST', '5'=>'BUDGET vs ACTUAL' ); if ($R::command eq "Report") { my $byear = $R::byearid; my $reporttype = $R::reporttype; my @selectedmonths = (@R::monthid); my %year; $year{$_} = $byear foreach ($bstartmonth-1..11);#2..11 $year{$_} = $byear+1 foreach (0..$bstartmonth-2); #0..1 &turnoversm::calculateturnover($shop{id},$byear,1,$database); # generate cached_day, montho my %categories = (1=>"LESS: COST OF SALES",2=>"LESS: EXPENSES",3=>"LESS: PAYROLL BURDEN - (Cost to Company)",4=>"Capital Expenses"); my %sources = (1=>"p",2=>"e",3=>"s"); my %months = (1 => "January", 2 => "February", 3 => "March", 4 => "April", 5 => "May",6 => "June", 7 => "July", 8 => "August", 9 => "September", 10 => "October",11 => "November", 12 => "December"); my %dayspermonth; #helper - coming from turnover.pm $results = $dbh->prepare("SELECT sect_name FROM bucalendar WHERE f_status<100 and shop_id = $shop{id} and byear=$byear;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $sect_name = $ref->{sect_name} ; my($other_income_name,$venue_name); $results = $dbh->selectall_arrayref("SELECT id,name from stocktypes WHERE account_type=1",{ Slice=>{} }); foreach(@$results){ $other_income_name = $_->{name} if $_->{name}=~/other\s+income\s+/i; $venue_name = $_->{name} if $_->{name}=~/other\s+sales\s+/i; } my %roots = ( 1=>"TOTAL SALES", 2=>"Shop Sales", 3=>"Non-Income Turnover: Promotions", 4=>"Non-Income Turnover: Discounts & Returns", 5=>"Total Shop Sales", 6=>$venue_name||"Other Sales", 8=>$other_income_name||"Other Income", 9=>$sect_name ? "Section Sales($sect_name)" : "Section Sales" , 10=>"Shop & Section Sales" #7=>"NET REST. SALES + BREAKFAST SALES" ); my %structure=(); # pseudo structure - HASH # {category_id}->@{id}{} # my %data =(); my %groupz =(); my %parents =(); my %idgroups =(); #get budget structure in HASH structure - use PERL - because it is working with HASH without time consuming methods $results = $dbh->prepare("SELECT * FROM bufc WHERE f_status<100 and shop_id = $shop{id} and year=$byear;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { #push @{ $structure{$ref->{grp}} }, $ref->{id}; $idgroups{$ref->{id}} = $ref->{grp}; $data{name}{$ref->{id}} = $ref->{name}; #name per id $data{id_per_name}{$ref->{name}} = $ref->{id}; #id per name $data{unique_names}{$ref->{name}}++; #unique names - todo show error if duplicated name found $data{name}{$ref->{id}} =~ s/^\[//; $data{name}{$ref->{id}} =~ s/\]$//; $data{type}{$ref->{id}} = $ref->{type}; #budget type - p.type,expence, unused (hook) $data{vtype}{$ref->{id}} = $ref->{vtype}; $data{factorsrc}{$ref->{id}} = $ref->{factorsrc} if $ref->{factorsrc}; $data{parent}{$ref->{id}} = $ref->{parent} if $ref->{parent}>0; $parents{$data{parent}{$ref->{id}}} = 1 if $ref->{parent}; push @{$groupz{grouped}{$ref->{parent}}} , $ref->{id} if $ref->{parent}; push @{$groupz{ungrouped}} , $ref->{id} if !$ref->{parent} and $ref->{vtype} <=2; } #end structure retreival #&logit("data:\n".Dumper(\%data)); #$data{parent}{"-100".$byear} = "-100".$byear; #$data{parent}{"-101".$byear} = "-101".$byear; #$data{parent}{"-102".$byear} = "-102".$byear; #create display structure foreach my $pid (sort {$data{name}{$a} cmp $data{name}{$b}} keys %parents) { push @{ $structure{$idgroups{$pid}} }, $pid; foreach my $id ( sort {$data{name}{$a} cmp $data{name}{$b}} @{$groupz{grouped}{$pid}}) { push @{ $structure{$idgroups{$id}} }, $id; } } if (ref $groupz{ungrouped} eq 'ARRAY'){ foreach my $id ( sort {$data{name}{$a} cmp $data{name}{$b}} @{$groupz{ungrouped}}) { push @{ $structure{$idgroups{$id}} }, $id; } } #------------------------------------------------------------------------------ #retreive calendar cashe values my %root_values; $results = $dbh->prepare("SELECT * from burootcache where shop_id=$shop{id} and byear=$byear;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()){ $root_values{$ref->{calc_id}}{$byear}{$ref->{month}} = $ref->{value}; } #THE WHOLE BUDGET IS IN THE MEMORY!!! #------------------------------------------------------------------------------ #calculate the root values (used for factors - factorsrc) my %rootval; my %frootval; #forecast my %drootval; #difference for my $month (0..11) { $rootval{1}{$month} = $root_values{1}{$byear}{$month}+ $root_values{6}{$byear}{$month}+ $root_values{3}{$byear}{$month}+ $root_values{5}{$byear}{$month}+ $root_values{8}{$byear}{$month}+ $root_values{9}{$byear}{$month}; $rootval{2}{$month} = $root_values{1}{$byear}{$month}; $rootval{3}{$month} = $root_values{3}{$byear}{$month}; $rootval{4}{$month} = $root_values{5}{$byear}{$month}; $rootval{5}{$month} = $root_values{1}{$byear}{$month}+ $root_values{5}{$byear}{$month}+ $root_values{3}{$byear}{$month}; $rootval{6}{$month} = $root_values{6}{$byear}{$month}; $rootval{7}{$month} = $root_values{6}{$byear}{$month}+ $root_values{1}{$byear}{$month}; $rootval{8}{$month} = $root_values{8}{$byear}{$month};#Other income $rootval{9}{$month} = $root_values{9}{$byear}{$month}; $rootval{10}{$month}= $rootval{9}{$month}+ $rootval{2}{$month}; } #------------------------------------------------------------------------------ #logit("rootval\n".Dumper(\%rootval)); #retreive values my %orgvalues; # a copy of the original my %values; my %avalues = (); my %fvalues = (); my %dvalues = (); my %lastdateregistered; #{month}{$id}=value # last actual date for my $month (1..12) { #white - blue #how many days we have in this month $dayspermonth{$month-1} = &turnoversm::lastday($month,$year{$month-1}); #BUG - this should not register the empty cachup created last night #last registered cashup $results = $dbh->prepare("select DAYOFMONTH(dc.date) lastday from dcash dc, dcashitems dci where dci.dcash_id=dc.id and month(dc.date) = $month and year(dc.date) = $year{$month-1} and dc.f_status<100 and dc.shop_id=$shop{id} and dci.f_status<100 and dci.shop_id=dc.shop_id group by dc.id order by dc.date desc limit 1;;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $lastdateregistered{$month-1} = $ref->{lastday}*1; } $results = $dbh->prepare("select bufc_id,month,value from bufc_values where bufc_id in (select id from bufc where shop_id=$shop{id} and year=$byear and f_status<100) and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $values{$ref->{month}}{$ref->{bufc_id}} = $ref->{value}; $orgvalues{$ref->{month}}{$ref->{bufc_id}} = $ref->{value}; #just make a copy } #calculate percents -> values from rootvals for my $month (0..11) { for my $id (keys %{$data{factorsrc}}) { $values{$month}{$id} = ($rootval{$data{factorsrc}{$id}}{$month} * $values{$month}{$id})/100; } } #get actualz $results = $dbh->prepare("select month(date) month, year(date), sum(price*qty) orgprice, othertype from purchases where ((YEAR(date)=$byear and MONTH(date) >".($bstartmonth-1).") or (YEAR(date)=$byear+1 and MONTH(date) <=".($bstartmonth-1).")) and f_status<100 and othertype is not null and (cnote != 1 or cnote is null or cnote = 0) and shop_id=$shop{id} group by othertype, month(date) order by year(date);") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $avalues{$ref->{month}-1}{$ref->{othertype}} = $ref->{orgprice}; } #&logit("avalues1:\n".Dumper(\%avalues)); $results = $dbh->prepare("select month(date) month, year(date), sum(price*qty) orgprice, othertype from purchases where ((YEAR(date)=$byear and MONTH(date) >".($bstartmonth-1).") or (YEAR(date)=$byear+1 and MONTH(date) <=".($bstartmonth-1).")) and f_status<100 and othertype is not null and cnote = 1 and shop_id=$shop{id} group by othertype, month(date) order by year(date);") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $avalues{$ref->{month}-1}{$ref->{othertype}} -= $ref->{orgprice}; } #&logit("avalues:\n".Dumper(\%avalues)); my @retreived_ids = (keys %{$data{name}} ); push @retreived_ids, "-100"."$byear"; #other income push @retreived_ids, "-101"."$byear"; #breakfast sales my $thisyearids = join(",",@retreived_ids); #bufc_shopvalues - Not used in future... #$results = $dbh->prepare("select month, bufc_id,value from bufc_shopvalues where bufc_id in($thisyearids) and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); #$results->execute() or die $results->errstr(); #while ($ref = $results->fetchrow_hashref()) { # $avalues{$ref->{month}}{$ref->{bufc_id}} = $ref->{value}; #} #&logit($thisyearids); #actual purchases my %purchases; #actual for my $month (1..12) { $results = $dbh->prepare("select sum(price*qty) grosspurchases from purchases where (cnote != 1 or cnote is null or cnote = 0) and month(date) = $month and year(date) = $year{$month-1} and f_status<100 and shop_id=$shop{id} and (othertype =0 or othertype is null) and type<>1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $purchases{$month-1} = $ref->{grosspurchases}; $results = $dbh->prepare("select sum(price*qty) grosscpurchases from purchases where cnote = 1 and month(date) = $month and year(date) = $year{$month-1} and f_status<100 and shop_id=$shop{id} and (othertype =0 or othertype is null) and type<>1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $purchases{$month-1} -= $ref->{grosscpurchases}; } #&logit("purchases:\n".Dumper(\%purchases)); #ovveride actuals my %overriden_ids; #bufc_ovveride $results = $dbh->prepare("select month, bufc_id,value from bufc_ovveride where bufc_id in($thisyearids) and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $overriden_ids{originalvalue}{$ref->{month}-1}{$ref->{bufc_id}} = $avalues{$ref->{month}-1}{$ref->{bufc_id}}; $overriden_ids{isoverriden}{$ref->{month}-1}{$ref->{bufc_id}} = 1; #always overriden if we are here - because of the way the records for bufc_ovveride - not existing for unchanged data. $avalues{$ref->{month}-1}{$ref->{bufc_id}} = $ref->{value}; } #//end override #STEVEN 2019-5-13 #we get SECTIN SALES,OTHER INCOME and HOTEL SALES by matching stocktypes name. under cost center =1 #for my $month (1..12) { for my $month2 (@selectedmonths) { #OTHER INCOME my $month = $month2 + 1; # for my $month ($bstartmonth..12,1..$bstartmonth-1) {#3..12,1..2 # my $year = $byear; # $year += 1 if ($month<$bstartmonth); $results = $dbh->prepare("select sum(pu.price * pu.qty) orgprice,year(pu.date) year from purchases pu, stockitems si where si.id = pu.stockitems_id and si.type in (SELECT id from stocktypes WHERE account_type=1 AND f_status<100 AND name LIKE '%Other Income%' ) and (pu.cnote = 0 or pu.cnote is null) and pu.shop_id = $shop{id} and pu.f_status<100 and month(pu.date) = $month and year(pu.date) = $year{$month-1} ")or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $avalues{$month-1}{"-100".$ref->{year}} = $ref->{orgprice} if $ref->{orgprice} > 0; #HOTEL SALES $results = $dbh->prepare("select sum(pu.price * pu.qty) orgprice,year(pu.date) year from purchases pu, stockitems si where si.id = pu.stockitems_id and si.type in (SELECT id from stocktypes WHERE account_type=1 AND f_status<100 AND name LIKE '%Other Sales%' ) and (pu.cnote = 0 or pu.cnote is null) and pu.shop_id = $shop{id} and pu.f_status<100 and month(pu.date) = $month and year(pu.date) = $year{$month-1} ")or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $avalues{$month-1}{"-101".$ref->{year}} = $ref->{orgprice} if $ref->{orgprice} > 0; #### dcash sales. --POS #INCOME & HOTEL $results = $dbh->prepare("select dcash.*, dcinv.tillinvoices_id tillinvoices_id from dcash, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id = dci.shop_id and dcinv.f_status<100 where month(dcash.date) = $month and year(dcash.date) = $year{$month-1} and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); my @allinvoices_id; while ($ref = $results->fetchrow_hashref()) { push @allinvoices_id,$ref->{tillinvoices_id}; } #logit($year{$month-1} . "----".join(",",@allinvoices_id)); $results = $dbh->prepare("SELECT id,name from stocktypes WHERE account_type=1") or die $dbh->errstr(); $results->execute() or die $results->errstr(); my (@COST_INCOME,@COST_HOTEL,@SECTION_SALES,@ALL_COSTS); while ($ref = $results->fetchrow_hashref()) { push @COST_HOTEL, $ref->{id} if $ref->{name}=~/OTHER\s+SALES\s+\(.*?\)/i; push @COST_INCOME, $ref->{id} if $ref->{name}=~/OTHER\s+INCOME\s+\(.*?\)/i; push @SECTION_SALES,$ref->{id} if $ref->{name}=~/Section\s+SALES\s+\(.*?\)/i; push @ALL_COSTS,$ref->{id}; } my $cost_hotel = join(",",@COST_HOTEL); my $cost_income = join(",",@COST_INCOME); my $cost_section = join(",",@SECTION_SALES); my $all_costs = join(",",@ALL_COSTS); my $inv_ids = join(",",@allinvoices_id); #logit("HOTEL:$cost_hotel,INCOME:$cost_income,ALL :" . join(",",@allinvoices_id)); INV:foreach my $invs(@allinvoices_id){ $invs=~s/\s+//g; next INV unless $invs; if(length($all_costs)>0){ $results = $dbh->prepare("SELECT *,year(stamp) year FROM `tillordersdetails` WHERE invoice = $invs AND plu in (SELECT id FROM menu WHERE `type` IN ($all_costs))"); #logit(qq|SELECT *,year(stamp) year FROM `tillordersdetails` WHERE invoice =$invs AND plu in (SELECT id FROM menu WHERE `type` IN ($cost_hotel))|); $results->execute() or die $results->errstr(); while (my $ref2 = $results->fetchrow_hashref()) { $avalues{$month-1}{"-109".$ref2->{year}} += $ref2->{qty} * $ref2->{price} -$ref2->{discount}; } } if(length($cost_hotel)>0){ $results = $dbh->prepare("SELECT *,year(stamp) year FROM `tillordersdetails` WHERE invoice = $invs AND plu in (SELECT id FROM menu WHERE `type` IN ($cost_hotel))"); #logit(qq|SELECT *,year(stamp) year FROM `tillordersdetails` WHERE invoice =$invs AND plu in (SELECT id FROM menu WHERE `type` IN ($cost_hotel))|); $results->execute() or die $results->errstr(); while (my $ref2 = $results->fetchrow_hashref()) { $avalues{$month-1}{"-101".$ref2->{year}} += $ref2->{qty} * $ref2->{price} -$ref2->{discount};# - ($ref2->{qty} * $ref2->{price}) *($ref2->{vatpercent} / 100); #logit("FH:".$ref2->{qty} * $ref2->{price} * (1-$ref2->{discount}/100)); } } if(length($cost_income)>0){ #logit("$year{$month-1},$month,$shop{id} \n"); #SELECT * FROM `dcash` where date >='2020-08-01' AND date <='2020-08-31' $results = $dbh->prepare("SELECT *,year(stamp) year FROM `tillordersdetails` WHERE invoice =$invs AND plu in (SELECT id FROM menu WHERE `type` IN($cost_income))"); $results->execute() or die $results->errstr(); while (my $ref2 = $results->fetchrow_hashref()) { #logit("$ref2->{year}|$month|$ref2->{qty}|$ref2->{price}|$ref2->{vatpercent}\n"); #$avalues{$month-1}{"-100".$ref2->{year}} += $ref2->{qty} * $ref2->{price} -$ref2->{discount} ; if($ref2->{vatpercent}){ $avalues{$month-1}{"-100".$ref2->{year}} += $ref2->{qty} * $ref2->{price} /(1+ $ref2->{vatpercent} / 100) -$ref2->{discount} ; }else{ $avalues{$month-1}{"-100".$ref2->{year}} += $ref2->{qty} * $ref2->{price} -$ref2->{discount} ; } } } if(length($cost_section)>0){ $results = $dbh->prepare("SELECT *,year(stamp) year FROM `tillordersdetails` WHERE invoice =$invs AND plu in (SELECT id FROM menu WHERE `type` IN ($cost_section))"); $results->execute() or die $results->errstr(); while (my $ref2 = $results->fetchrow_hashref()) { $avalues{$month-1}{"-102".$ref2->{year}} += $ref2->{qty} * $ref2->{price} - $ref2->{discount};# - ($ref2->{qty} * $ref2->{price}) *($ref2->{vatpercent} / 100); } } }##end for each INV # logit("100:" .($month-1) .":" . $avalues{$month-1}{"-100".'2021'}); # logit("101:" .($month-1) .":" . $avalues{$month-1}{"-101".'2021'}); # logit("102:" .($month-1) .":" . $avalues{$month-1}{"-102".'2021'}); } ### Inventory Adjustment START my ($ia_lastvalue,$ia_lastmonth); my (%ias, $ia); for my $month ($bstartmonth..12,1..$bstartmonth-1) {#3..12,1..2 my $year = $byear; $year += 1 if ($month<$bstartmonth); $results = $dbh->prepare("select date, sum(value) value from cstock where value > 0 and shop_id='$shop{id}' and stocktype=1 and date <= '$year-$month-01 23:30:00' group by date order by date desc limit 1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $ia = 0; if ($ia_lastvalue) { $ia =$ia_lastvalue -$ref->{value}; $ias{$ia_lastmonth} = $ia; } #debug print "$year-$month-01 ($ref->{value}) $ia\n"; $ia_lastvalue = $ref->{value}; $ia_lastmonth = $month; } $ias{2} = $ia; $ia_lastvalue = undef; for my $month ($bstartmonth..12,1..$bstartmonth-1) {#3..12,1..2 my $year = $byear; $year += 1 if ($month<$bstartmonth); $results = $dbh->prepare("select date, sum(value) value from cstock where value > 0 and shop_id='$shop{id}' and stocktype=2 and date <= '$year-$month-01 23:30:00' group by date order by date desc limit 1;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $ia = 0; if ($ia_lastvalue) { $ia =$ia_lastvalue -$ref->{value}; $ias{$ia_lastmonth} += $ia; } #debug print "$year-$month-01 ($ref->{value}) $ia\n"; $ia_lastvalue = $ref->{value}; $ia_lastmonth = $month; } $ias{2} += $ia; ### Inventory Adjustment END for my $month (0..11) { #INVENTORY ADJUSTMENT $avalues{$month}{$data{id_per_name}{"INVENTORY ADJUSTMENT"}} = $ias{$month+1} if (! defined $avalues{$month}{$data{id_per_name}{"INVENTORY ADJUSTMENT"}}); } #expenses hookers - assign actuals straight #WAITRON SERVICE FEES $results = $dbh->prepare(" select sum(dci.s_fee) sfees, month(dcash.date) month, year(dcash.date) from dcash,dcashitems dci where dci.shop_id=$shop{id} and dcash.shop_id=dci.shop_id and dci.dcash_id=dcash.id and ((YEAR(dcash.date)=$byear and MONTH(dcash.date) >".($bstartmonth-1).") or (YEAR(dcash.date)=$byear+1 and MONTH(dcash.date) <=".($bstartmonth-1).")) group by month(dcash.date); ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $avalues{$ref->{month}-1}{$data{id_per_name}{"WAITRON SERVICE FEES"}} = $ref->{sfees}; } #PARK INN ONLY check whether it must be overridable for my $month (1..12) { $avalues{$month-1}{$data{id_per_name}{"HOTEL AND RESTAURANT STAFF MEALS"}} = $avalues{$month-1}{$data{id_per_name}{"[Restaurant Staff Meals]"}}; $avalues{$month-1}{$data{id_per_name}{"[Restaurant Staff Meals]"}} = 0 if ($data{id_per_name}{"HOTEL AND RESTAURANT STAFF MEALS"}); #HOTEL AND RESTAURANT STAFF MEALS = Restaurant Staff Meals #Restaurant Staff Meals = 0 } #hooker roots my %roothookers; my %coverfrombudget = (); #per month #PROMOS AND RETURNS ,# MANAGEMENT MEALS for my $month (1..12) { #old version #select sum(pdr.promo)/((100 + $cvat)/100) + sum(pdr.retrns)/((100 + $cvat)/100) proret #from pdrcash pdr,dcash #where pdr.dcash_id=dcash.id #and month(dcash.date) = $month and year(dcash.date) = $year{$month-1} #and dcash.f_status<100 and dcash.shop_id=$shop{id} #and pdr.f_status<100 and pdr.shop_id=$shop{id}; #$results = $dbh->prepare(" #select sum(dci.retrns + dci.pro)/((100 + $cvat)/100) proret #from dcash dc, dcashitems dci #where dc.id = dci.dcash_id #and dc.f_status<100 #and dci.f_status<100 #and dc.shop_id=dci.shop_id #and dci.shop_id=$shop{id} #and month(dc.date) = $month #and year(dc.date) = $year{$month-1}; #") or die $dbh->errstr(); #STEVEN REMOVED discount from pro and return #$results = $dbh->prepare(" #select # sum(dcinv.dcinv_turnover_total-dcinv.vat_total) grossto, # # sum(dcinv.covers) covers_total, # # sum(dcinv.staffpromo_total - dcinv.vat_total*dcinv.staffpromo_total/dcinv.dcinv_turnover_total) staff_promo, # # sum(dcinv.returns_total - dcinv.vat_total*dcinv.returns_total/dcinv.dcinv_turnover_total) # + # sum(dcinv.discount_total - dcinv.vat_total*dcinv.discount_total/dcinv.dcinv_turnover_total) proret # # from # dcash, # dcashitems dci # # LEFT JOIN dcashinvoices dcinv ON # dcinv.dcashitems_id = dci.id # and dcinv.shop_id=dci.shop_id # and dcinv.f_status<100 # where # month(dcash.date) = $month # and year(dcash.date) = $year{$month-1} # and dcash.shop_id=$shop{id} # and dci.shop_id=dcash.shop_id # and dcash.id=dci.dcash_id # and dcash.f_status<100 # and dci.f_status<100 # ; #") or die $dbh->errstr(); $results = $dbh->prepare(" select sum(dcinv.dcinv_turnover_total-dcinv.vat_total) grossto, sum(dcinv.covers) covers_total, sum(dcinv.staffpromo_total - dcinv.vat_total*dcinv.staffpromo_total/dcinv.dcinv_turnover_total) staff_promo, sum(dcinv.staffpromo_total - dcinv.vat_total*dcinv.staffpromo_total/dcinv.dcinv_turnover_total) staff_meals, sum(dcinv.returns_total) proret, sum(dcinv.discount_total) discount from dcash, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 where month(dcash.date) = $month and year(dcash.date) = $year{$month-1} and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 ; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $roothookers{$month-1}{4} = $ref->{proret};# /(1+ $cvat / 100); $roothookers{$month-1}{'4'.'discount'} = $ref->{discount}; $avalues{$month-1}{$data{id_per_name}{"Customer Satisfaction (Promotions & Returns)"}} = $roothookers{$month-1}{4}; if ($lastdateregistered{$month-1}<$dayspermonth{$month-1}) { if ($lastdateregistered{$month-1} and ($lastdateregistered{$month-1} != $dayspermonth{$month-1}) ) { for my $day ( (($lastdateregistered{$month-1}+1)..$dayspermonth{$month-1}) ) { $coverfrombudget{4}{$month-1} += $turnoversm::cached_day{$byear}{4}{$month-1}{$day}; } } elsif (! $lastdateregistered{$month-1}) { # nothing actual for the month - use the budget as forecast $coverfrombudget{4}{$month-1} = $rootval{4}{$month-1}; } } #management meanls $roothookers{$month-1}{3} = $ref->{staff_meals}; $avalues{$month-1}{$data{id_per_name}{"[Restaurant Management Meals]"}} = $ref->{staff_meals}; if ($lastdateregistered{$month-1}<$dayspermonth{$month-1}) { if ($lastdateregistered{$month-1} and ($lastdateregistered{$month-1} != $dayspermonth{$month-1}) ) { for my $day ( (($lastdateregistered{$month-1}+1)..$dayspermonth{$month-1}) ) { $coverfrombudget{3}{$month-1} += $turnoversm::cached_day{$byear}{3}{$month-1}{$day}; } } elsif (! $lastdateregistered{$month-1}) { # nothing actual for the month - use the budget as forecast $coverfrombudget{3}{$month-1} = $rootval{3}{$month-1}; } } #meals end } =pre # MANAGEMENT MEALS for my $month (1..12) { $results = $dbh->prepare(" select sum(dcinv.dcinv_turnover_total-dcinv.vat_total) grossto, sum(dcinv.covers) covers_total, sum(dcinv.staffpromo_total - dcinv.vat_total*dcinv.staffpromo_total/dcinv.dcinv_turnover_total) staff_meals, sum(dcinv.returns_total - dcinv.vat_total*dcinv.returns_total/dcinv.dcinv_turnover_total) + sum(dcinv.discount_total - dcinv.vat_total*dcinv.discount_total/dcinv.dcinv_turnover_total) proret from dcash, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 where month(dcash.date) = $month and year(dcash.date) = $year{$month-1} and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100 ; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $roothookers{$month-1}{3} = $ref->{staff_meals}; #management staff meals - Restaurant Management Meals $avalues{$month-1}{$data{id_per_name}{"[Restaurant Management Meals]"}} = $ref->{staff_meals}; if ($lastdateregistered{$month-1}<$dayspermonth{$month-1}) { if ($lastdateregistered{$month-1} and ($lastdateregistered{$month-1} != $dayspermonth{$month-1}) ) { for my $day ( (($lastdateregistered{$month-1}+1)..$dayspermonth{$month-1}) ) { $coverfrombudget{3}{$month-1} += $turnoversm::cached_day{$byear}{3}{$month-1}{$day}; } } elsif (! $lastdateregistered{$month-1}) { # nothing actual for the month - use the budget as forecast $coverfrombudget{3}{$month-1} = $rootval{3}{$month-1}; } } } =cut # NET and GROSS SALES, last sales registered for the month for my $month (1..12) { $results = $dbh->prepare(" select sum(dcinv.dcinv_turnover_total-dcinv.vat_total) gross_vat_excl, sum(dcinv.covers) covers_total, sum(dcinv.staffpromo_total - dcinv.vat_total*dcinv.staffpromo_total/dcinv.dcinv_turnover_total) staff_promo, sum(dcinv.returns_total - dcinv.vat_total*dcinv.returns_total/dcinv.dcinv_turnover_total) + sum(dcinv.discount_total - dcinv.vat_total*dcinv.discount_total/dcinv.dcinv_turnover_total) proret from dcash, dcashitems dci LEFT JOIN dcashinvoices dcinv ON dcinv.dcashitems_id = dci.id and dcinv.shop_id=dci.shop_id and dcinv.f_status<100 where month(dcash.date) = $month and year(dcash.date) = $year{$month-1} and dcash.shop_id=$shop{id} and dci.shop_id=dcash.shop_id and dcash.id=dci.dcash_id and dcash.f_status<100 and dci.f_status<100; ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $roothookers{$month-1}{2} = $ref->{gross_vat_excl} - $roothookers{$month-1}{3} - $roothookers{$month-1}{4}; $roothookers{$month-1}{5} = $ref->{gross_vat_excl}; #cover the month from the budget if ($lastdateregistered{$month-1}<$dayspermonth{$month-1}) { if ($lastdateregistered{$month-1} and ($lastdateregistered{$month-1} != $dayspermonth{$month-1}) ) { for my $day ( (($lastdateregistered{$month-1}+1)..$dayspermonth{$month-1}) ) { $coverfrombudget{2}{$month-1} += $turnoversm::cached_day{$byear}{2}{$month-1}{$day}; $coverfrombudget{5}{$month-1} += $turnoversm::cached_day{$byear}{5}{$month-1}{$day}; } } elsif (! $lastdateregistered{$month-1}) { # nothing actual for the month - use the budget as forecast $coverfrombudget{2}{$month-1} = $rootval{2}{$month-1}; $coverfrombudget{5}{$month-1} = $rootval{5}{$month-1}; } } } # BREAKFAST SALES and NET + BREAKFAST and RESTAURANT SALES (BKST + GROSS) + # overriding other income for my $month (1..12) { my $byear2 = $byear; if($month < $bstartmonth){ $byear2 = $byear +1; } #$results = $dbh->prepare(" #select sum(breakfast_price)/((100 + $cvat)/100) breakfast #from dcash #where #month(date) = $month and year(date) = $year{$month-1} #and f_status<100 and shop_id=$shop{id};") or die $dbh->errstr(); #$results->execute() or die $results->errstr(); #$ref = $results->fetchrow_hashref(); #$roothookers{$month-1}{6} = $ref->{breakfast}; #breakfast sales $roothookers{$month-1}{6} = $avalues{$month-1}{"-101"."$byear2"} if $avalues{$month-1}{"-101"."$byear2"} > 0; #overriden #logit(($month-1) ."breakfast sales:". $roothookers{$month-1}{6} .":" .$avalues{$month-1}{"-101"."$byear2"}); $roothookers{$month-1}{6} = $roothookers{$month-1}{6} /(1+ $cvat / 100); #other income $roothookers{$month-1}{8} = $avalues{$month-1}{"-100"."$byear2"} if $avalues{$month-1}{"-100"."$byear2"} > 0; #overriden #logit(($month-1) ."other income:". $roothookers{$month-1}{8} .":" .$avalues{$month-1}{"-100"."$byear2"}); #2020-11-23 #$roothookers{$month-1}{8} = $roothookers{$month-1}{8} /(1+ $cvat / 100); #section sales $roothookers{$month-1}{9} = $avalues{$month-1}{"-102"."$byear2"} if $avalues{$month-1}{"-102"."$byear2"} > 0; #overriden $roothookers{$month-1}{9} = $roothookers{$month-1}{9} /(1+ $cvat / 100); #logit(($month-1) ."section sales:". $roothookers{$month-1}{9} .":" .$avalues{$month-1}{"-102"."$byear2"}); #all sales $roothookers{$month-1}{2} = $avalues{$month-1}{"-109"."$byear2"} if $avalues{$month-1}{"-109"."$byear2"} > 0; #overriden $roothookers{$month-1}{2} = $roothookers{$month-1}{2} /(1+ $cvat / 100); #logit(($month-1) ."all sales:". $roothookers{$month-1}{2} .":" .$avalues{$month-1}{"-109"."$byear2"}); #management meals $roothookers{$month-1}{3} = $roothookers{$month-1}{3} /(1+ $cvat / 100); $roothookers{$month-1}{7} = $ref->{breakfast} + $roothookers{$month-1}{2}; #$roothookers{$month-1}{1} = $ref->{breakfast} + $roothookers{$month-1}{5}; #$roothookers{$month-1}{1} +=$roothookers{$month-1}{8} + $roothookers{$month-1}{6}; ##Shop Sales my $return_without_VAT = $roothookers{$month-1}{4} /(1+ $cvat / 100); $roothookers{$month-1}{4} = ($roothookers{$month-1}{4} + $roothookers{$month-1}{'4discount'})/(1+ $cvat / 100); $roothookers{$month-1}{2} = $roothookers{$month-1}{2} - $return_without_VAT - $roothookers{$month-1}{9} - $roothookers{$month-1}{8} -$roothookers{$month-1}{6}; #total sales $roothookers{$month-1}{1} = $roothookers{$month-1}{2} + $roothookers{$month-1}{3} + $roothookers{$month-1}{4} + $roothookers{$month-1}{6} + $roothookers{$month-1}{8} + $roothookers{$month-1}{9}; $avalues{$month-1}{$data{id_per_name}{"FRANCHISE FEES/MANAGEMENT FEES"}} = ($roothookers{$month-1}{1}*$orgvalues{$month}{$data{id_per_name}{"FRANCHISE FEES/MANAGEMENT FEES"}})/100; if ($lastdateregistered{$month-1} and ($lastdateregistered{$month-1} < $dayspermonth{$month-1}) ) { #the month is in the middle - ie. there is actual cachup days already for my $day ( (($lastdateregistered{$month-1}+1)..$dayspermonth{$month-1}) ) { $coverfrombudget{6}{$month-1} += $turnoversm::cached_day{$byear}{6}{$month-1}{$day}; $coverfrombudget{7}{$month-1} += $turnoversm::cached_day{$byear}{7}{$month-1}{$day}; $coverfrombudget{1}{$month-1} += $turnoversm::cached_day{$byear}{1}{$month-1}{$day}; $coverfrombudget{1}{$month-1} -= $turnoversm::cached_day{$byear}{6}{$month-1}{$day}; #let's use same logic as Shop Sales $coverfrombudget{9}{$month-1} += $turnoversm::cached_day{$byear}{9}{$month-1}{$day}; #$coverfrombudget{1}{$month-1} += $turnoversm::cached_day{$byear}{9}{$month-1}{$day}; } #override forecast for breakfast and other income = budget # detailed explanation: # because breakfast sales and other income is registered after the month end # is passed - we always forecast the budget, and the avalue is always 0 # this makes the forecast = avalue when it registers - in two words - for b.sales: # the daily income for breakfast - as per budget (cached_day{6}) is ignored # as for the other income - there is no cached_day - because the budget is presenting # this as monthly values $coverfrombudget{6}{$month-1} = $rootval{6}{$month-1} if !$roothookers{$month-1}{6}; $coverfrombudget{1}{$month-1} += $coverfrombudget{6}{$month-1}; $coverfrombudget{8}{$month-1} = $rootval{8}{$month-1} if !$roothookers{$month-1}{8}; $coverfrombudget{1}{$month-1} += $coverfrombudget{8}{$month-1}; # warning !! there is no arootval for the other income (8)!!! # $lastdateregistered{$month-1} == $dayspermonth{$month-1} # means this is a historical month already } elsif (! $lastdateregistered{$month-1}) { # nothing actual for the month - use the budget as forecast $coverfrombudget{6}{$month-1} = $rootval{6}{$month-1}; $coverfrombudget{7}{$month-1} = $rootval{7}{$month-1}; $coverfrombudget{1}{$month-1} = $rootval{1}{$month-1}; $coverfrombudget{8}{$month-1} = $rootval{8}{$month-1}; } } #FORECAST AND DIFFERENCE FOR ROOTVALUES foreach my $root (sort keys %rootval) { foreach my $month (0..11) { $frootval{$root}{$month} = $roothookers{$month}{$root} + $coverfrombudget{$root}{$month}; #$frootval{$root}{$month} = $rootval{$root}{$month} if $root == 8;#Other income if($root == 8){ if ($lastdateregistered{$month}<$dayspermonth{$month}) { $frootval{$root}{$month} = $rootval{$root}{$month}; }else{ $frootval{$root}{$month} = $roothookers{$month}{$root}; } } $drootval{$root}{$month} = $frootval{$root}{$month} - $rootval{$root}{$month}; } } #reset total focast. STEVEN foreach my $month (0..11) { $frootval{1}{$month} = $frootval{2}{$month} + $frootval{3}{$month} + $frootval{4}{$month} + $frootval{6}{$month} + $frootval{8}{$month} + $frootval{9}{$month}; } ### #we must retreive the hook avalues here - before the forecast !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #HERE !!! #------------------------------------------------------------------------------ #calculate the forecast my %foodcost; my $purchases_id; my $corrected_for_purchases_id; for my $month (0..11) { for my $id (keys %{$data{name}}) { if($data{name}{$id} =~ /PURCHASES/si) { # both purchases are % of T.O. that's why we calculate the forecast as a % from forecast for the turnover if ( ($data{name}{$id} !~ /breakfast/si) and ($data{name}{$id} !~ /sushi/si) ) { #restaurant purchases $avalues{$month}{$id} = $purchases{$month} if (! defined $avalues{$month}{$id}); #replace in case not overriden $foodcost{$month} = ($avalues{$month}{$id} / $roothookers{$month}{2}) * 100 if ($roothookers{$month}{2}); $purchases_id = $id; #$fvalues{$month}{$id} = $frootval{5}{$month}*($orgvalues{$month}{$id}/100); # % of frootval - rest. t.o. #$fvalues{$month}{$id} = $avalues{$month}{$id} if ($avalues{$month}{$id} > $values{$month}{$id}); my $perc; #print "|rh5 $roothookers{$month}{5}|"; if ($roothookers{$month}{5} != 0) { $perc = $purchases{$month} / $roothookers{$month}{5} ; $fvalues{$month}{$id} = ($frootval{5}{$month} * $perc) - $avalues{$month}{$data{id_per_name}{"INVENTORY ADJUSTMENT"}}; } else { $fvalues{$month}{$id} = $frootval{5}{$month}*($orgvalues{$month}{$id}/100); } } else { #breakfast purchases $fvalues{$month}{$id} = $frootval{6}{$month}*($orgvalues{$month}{$id}/100); # % of frootval - bfst sales $fvalues{$month}{$id} = $avalues{$month}{$id} if ($avalues{$month}{$id} > $values{$month}{$id}); } } else { if ($avalues{$month}{$id} > $values{$month}{$id} and $id != $data{id_per_name}{"WAITRON SERVICE FEES"} and $id != $data{id_per_name}{"FRANCHISE FEES/MANAGEMENT FEES"} ) { $fvalues{$month}{$id} = $avalues{$month}{$id} } else{ #this is the case where the expence is fixed value $fvalues{$month}{$id} = $values{$month}{$id}; if ($data{factorsrc}{$id}) { #this is the case where the expence is % of T.O. calculation and not fixed value #override $fvalues #orgvalue percent from forecast $fvalues{$month}{$id} = ($frootval{$data{factorsrc}{$id}}{$month} * $orgvalues{$month}{$id} ) /100; #exception WAITRON SERV FEES if ($id == $data{id_per_name}{"WAITRON SERVICE FEES"}) { if ($roothookers{$month}{$data{factorsrc}{$id}} > 0) { #actual turnover = true my $perc = $avalues{$month}{$id} / $roothookers{$month}{$data{factorsrc}{$id}}; #print "$frootval{$data{factorsrc}{$id}}{$month} $perc]"; $fvalues{$month}{$id} = ($frootval{$data{factorsrc}{$id}}{$month} * $perc ); } } } }; } # if the month is passed - then we do the forecast to be the actual here: # OVERRIDE IF... $fvalues{$month}{$id} = $avalues{$month}{$id} if $lastdateregistered{$month} == $dayspermonth{$month}; #override the forecast for the Inventory adjustment $fvalues{$month}{$id} = $avalues{$month}{$id} if $id == $data{id_per_name}{"INVENTORY ADJUSTMENT"}; #calculate the difference columns $dvalues{$month}{$id} = $fvalues{$month}{$id} - $values{$month}{$id}; $dvalues{$month}{$id} *= -1; } #ids } #month #------------------------------------------------------------------------------ #calculate the totals for my $month (0..11) { for my $id (keys %{$data{parent}}) { $values{$month}{$data{parent}{$id}} += $values{$month}{$id};# if (exists $data{parent}{$id}); $avalues{$month}{$data{parent}{$id}} += $avalues{$month}{$id};# if (exists $data{parent}{$id}); $fvalues{$month}{$data{parent}{$id}} += $fvalues{$month}{$id};# if (exists $data{parent}{$id}); $dvalues{$month}{$data{parent}{$id}} += $dvalues{$month}{$id};# if (exists $data{parent}{$id}); } } #&logit("data\n".Dumper(\%data)."\navalues:\n".Dumper(\%avalues)); #------------------------------------------------------------------------------ #calculate the grouptotals my %cattotals; my %acattotals; my %fcattotals; my %dcattotals; # {month}{gid} = total value for my $month (0..11) { foreach my $cat (keys %categories) { foreach my $id (@{ $structure{$cat} }) { $cattotals{$month}{$cat} += $values{$month}{$id} if (! exists $data{parent}{$id}); # no group cells $acattotals{$month}{$cat} += $avalues{$month}{$id} if (! exists $data{parent}{$id}); $fcattotals{$month}{$cat} += $fvalues{$month}{$id} if (! exists $data{parent}{$id}); } if ($cat != 1) { #not for purchases - less than budget = budget #if ($acattotals{$month}{$cat} < $cattotals{$month}{$cat}) {$fcattotals{$month}{$cat} = $cattotals{$month}{$cat}} #else {$fcattotals{$month}{$cat} = $acattotals{$month}{$cat}} $dcattotals{$month}{$cat} = $fcattotals{$month}{$cat} - $cattotals{$month}{$cat}; $dcattotals{$month}{$cat} *= -1; } else { $dcattotals{$month}{$cat} = $fcattotals{$month}{$cat} - $cattotals{$month}{$cat}; $dcattotals{$month}{$cat} *= -1; } } } #calculate bottom line my %grossproffit; my %agrossproffit; my %fgrossproffit; my %dgrossproffit; for my $month (0..11) { $grossproffit{$month} = $rootval{1}{$month} - $cattotals{$month}{1}; $agrossproffit{$month} = $roothookers{$month}{1} - $acattotals{$month}{1}; $fgrossproffit{$month} = $frootval{1}{$month} - $fcattotals{$month}{1}; $dgrossproffit{$month} = $drootval{1}{$month} - $dcattotals{$month}{1}*-1; } my %totalfixcost; my %atotalfixcost; my %ftotalfixcost; my %dtotalfixcost; for my $month (0..11) { $totalfixcost{$month} = $cattotals{$month}{2} + $cattotals{$month}{3}; $atotalfixcost{$month} = $acattotals{$month}{2} + $acattotals{$month}{3}; $ftotalfixcost{$month} = $fcattotals{$month}{2} + $fcattotals{$month}{3}; $dtotalfixcost{$month} = $dcattotals{$month}{2} + $dcattotals{$month}{3}; } my %netincome; my %anetincome; my %fnetincome; my %dnetincome; for my $month (0..11) { $netincome{$month} = $rootval{1}{$month} - ($cattotals{$month}{1}+$cattotals{$month}{3}+$cattotals{$month}{2}); $anetincome{$month} = $roothookers{$month}{1} - ($acattotals{$month}{1}+$acattotals{$month}{3}+$acattotals{$month}{2}); $fnetincome{$month} = $frootval{1}{$month} - ($fcattotals{$month}{1}+$fcattotals{$month}{3}+$fcattotals{$month}{2}); $dnetincome{$month} = $drootval{1}{$month} - ($dcattotals{$month}{1}*-1+$dcattotals{$month}{3}*-1+$dcattotals{$month}{2}*-1); } my %nettcash; my %anettcash; my %fnettcash; my %dnettcash; for my $month (0..11) { $nettcash{$month} = $netincome{$month} - $cattotals{$month}{4}; $anettcash{$month} = $anetincome{$month} - $acattotals{$month}{4}; $fnettcash{$month} = $fnetincome{$month} - $fcattotals{$month}{4}; #$dnettcash{$month} = $dnetincome{$month} - $dcattotals{$month}{4}; $dnettcash{$month} = $fnettcash{$month} - $nettcash{$month}; } #DEBUG #we must get actuals before this... # ok.. lets calculate all values for the year my %actualvsb; for my $month (0..11) { for my $id (keys %{$data{name}}) { $actualvsb{value}{$id}{$month} = $values{$month}{$id} - $avalues{$month}{$id}; } foreach my $root (sort keys %rootval) { $actualvsb{root}{$root}{$month} = $rootval{$root}{$month} - $roothookers{$month}{$root}; } foreach my $cat (keys %categories) { $actualvsb{cat}{$cat}{$month} = $cattotals{$month}{$cat} - $acattotals{$month}{$cat}; } $actualvsb{nettcash}{$month} = $nettcash{$month} - $anettcash{$month}; $actualvsb{netincome}{$month} = $netincome{$month} - $anetincome{$month}; $actualvsb{grossproffit}{$month} = $grossproffit{$month} - $agrossproffit{$month}; } #****************************************************************************** #****************************************************************************** my %columns; $columns{$_} = 1 foreach (@R::reportcolumns); if ( ($reporttype eq "year" and ! $R::limitactuals) or ($reporttype eq "year" and scalar @R::monthid > 0 and $R::limitactuals) ) { #year to date my $actualsto = undef; my %dontmonths = (); if (scalar @R::monthid > 0 and $R::limitactuals ) { $actualsto = $R::monthid[-1]; $temphtml .= "Actuals only up to month of "; $temphtml .= $months{$actualsto + 1}; $temphtml .= " (including)"; my $limityes = 0; #(2..11,0..1) foreach ($bstartmonth-1..11,0..$bstartmonth-2) { $dontmonths{$_} = $limityes; $limityes = 1 if ($_ == $actualsto); } } my %yactualvsb; my $daysperyear; my $actualdays; my %yrootval; my %yroothookers; my %yfrootval; my %ydrootval; my %ycattotals; my %yacattotals; my %yfcattotals; my %ydcattotals; my %yvalues; my %yavalues; my %yfvalues; my %ydvalues; #my $yactualdayscovered; my $ygrossproffit;my $yagrossproffit;my $yfgrossproffit;my $ydgrossproffit; my $ytotalfixcost;my $yatotalfixcost;my $yftotalfixcost;my $ydtotalfixcost; my $ynetincome; my $yanetincome; my $yfnetincome; my $ydnetincome; my $ynettcash; my $yanettcash; my $yfnettcash; my $ydnettcash; my $ypurchases; #get the year total foreach my $month (0..11) { $daysperyear += $dayspermonth{$month}; $actualdays += $lastdateregistered{$month} if (! $dontmonths{$month} ); foreach my $root (keys %rootval) { $yrootval{$root} += $rootval{$root}{$month}; #budget if (!$dontmonths{$month}) { $yroothookers{$root} += $roothookers{$month}{$root}; #actual $yfrootval{$root} += $frootval{$root}{$month}; #forecast $ydrootval{$root} += $drootval{$root}{$month}; #forecast vs budget $yactualvsb{root}{$root} += $actualvsb{root}{$root}{$month}; #actual vs budget } else { $yroothookers{$root} += 0; # ignore actual $yfrootval{$root} += $rootval{$root}{$month}; # forecast = budget $ydrootval{$root} += 0; # no difference between actual and forecast $yactualvsb{root}{$root} += 0 - $rootval{$root}{$month}; # actual vs budget } } foreach my $category (sort keys %categories) { $ycattotals{$category} += $cattotals{$month}{$category}; if (!$dontmonths{$month}) { $yacattotals{$category} += $acattotals{$month}{$category}; $yfcattotals{$category} += $fcattotals{$month}{$category}; $ydcattotals{$category} += $dcattotals{$month}{$category}; } else { $yacattotals{$category} += 0; $yfcattotals{$category} += $cattotals{$month}{$category}; # forecash = budget $ydcattotals{$category} += 0; #forecast vs budget = 0 } foreach my $id (@{ $structure{$category} }) { $yvalues{$id} += $values{$month}{$id}; if (!$dontmonths{$month}) { $yavalues{$id} += $avalues{$month}{$id}; $yfvalues{$id} += $fvalues{$month}{$id}; $ydvalues{$id} += $dvalues{$month}{$id}; } else { $yavalues{$id} += 0; $yfvalues{$id} += $values{$month}{$id}; $ydvalues{$id} += 0; } } } #bottomline #budget $ygrossproffit += $grossproffit{$month}; $ynettcash += $nettcash{$month}; $ynetincome += $netincome{$month}; $ytotalfixcost += $totalfixcost{$month}; if (!$dontmonths{$month}) { #actuals $yagrossproffit += $agrossproffit{$month}; $yatotalfixcost += $atotalfixcost{$month}; $yanetincome += $anetincome{$month}; $yanettcash += $anettcash{$month}; #forecasts $yfgrossproffit += $fgrossproffit{$month}; $yftotalfixcost += $ftotalfixcost{$month}; $yfnetincome += $fnetincome{$month}; $yfnettcash += $fnettcash{$month}; #fcst vs budget $ydgrossproffit += $dgrossproffit{$month}; $ydtotalfixcost += $dtotalfixcost{$month}; $ydnetincome += $dnetincome{$month}; $ydnettcash += $dnettcash{$month}; #actual purchases; $ypurchases += $purchases{$month}; for my $id (keys %{$data{name}}) { $yactualvsb{value}{$id} += 0 - $values{$month}{$id}; } foreach my $cat (keys %categories) { $yactualvsb{cat}{$cat} += $actualvsb{cat}{$cat}{$month}; } $yactualvsb{nettcash} += $actualvsb{nettcash}{$month}; $yactualvsb{netincome} += $actualvsb{netincome}{$month}; $yactualvsb{grossproffit} += $actualvsb{grossproffit}{$month}; } else { #ignored month #actuals = 0 $yagrossproffit += 0; $yatotalfixcost += 0; $yanetincome += 0; $yanettcash += 0; #forecasts = budget $yfgrossproffit += $grossproffit{$month}; $yftotalfixcost += $totalfixcost{$month}; $yfnetincome += $netincome{$month}; $yfnettcash += $nettcash{$month}; #fcst vs budget $ydgrossproffit += 0; $ydtotalfixcost += 0; $ydnetincome += 0; $ydnettcash += 0; #actual purchases; $ypurchases += 0; for my $id (keys %{$data{name}}) { $yactualvsb{value}{$id} += 0 - $actualvsb{value}{$id}{$month}; } foreach my $cat (keys %categories) { $yactualvsb{cat}{$cat} += 0 - $cattotals{$month}{$cat}; } $yactualvsb{nettcash} += 0 - $nettcash{$month}; $yactualvsb{netincome} += 0 - $netincome{$month}; $yactualvsb{grossproffit} += 0 - $grossproffit{$month}; } } #12 months starting 0 my $yfoodcost = ($yavalues{$purchases_id} / $yroothookers{2}) * 100 if ($yroothookers{1}); $temphtml .= ""; #display header $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "" if ($columns{1}); $temphtml .= "" if ($columns{2}); $temphtml .= "" if ($columns{3}); $temphtml .= "" if ($columns{4}); $temphtml .= "" if ($columns{5}); $temphtml .= ""; #budget, actual, forecast, diff #display roots foreach my $root (1,2,9,3,4,8,6) { $temphtml .= ""; $temphtml .= "" if ($columns{1}); $temphtml .= "" if ($columns{2}); $temphtml .= "" if ($columns{3}); $temphtml .= "" if ($columns{4}); $temphtml .= "" if ($columns{5}); $temphtml .= ""; } #get categoriez:) foreach my $category (sort keys %categories) { if ($category == 2) { $temphtml .= ""; $temphtml .= "" if ($columns{1}); $temphtml .= "" if ($columns{2}); $temphtml .= "" if ($columns{3}); $temphtml .= "" if ($columns{4}); $temphtml .= "" if ($columns{5}); } elsif ($category == 4) { $temphtml .= ""; $temphtml .= "" if ($columns{1}); $temphtml .= "" if ($columns{2}); $temphtml .= "" if ($columns{3}); $temphtml .= "" if ($columns{4}); $temphtml .= "" if ($columns{5}); $temphtml .= ""; } #category name $temphtml .= ""; $temphtml .= "" if ($columns{1}); $temphtml .= "" if ($columns{2}); $temphtml .= "" if ($columns{3}); $temphtml .= "" if ($columns{4}); $temphtml .= "" if ($columns{5}); $temphtml .= ""; #items foreach my $id (@{ $structure{$category} }) { #NOTE - for tr. $temphtml .= ""; my $suffix; #$suffix = "(".sprintf("%d",$yfoodcost)."%) " if ($id == $purchases_id); $temphtml .= "" if ($columns{1}); $temphtml .= "" if ($columns{2}); $temphtml .= "" if ($columns{3}); $temphtml .= "" if ($columns{4}); $temphtml .= "" if ($columns{5}); } } #net cash $temphtml .= ""; $temphtml .= "" if ($columns{1}); $temphtml .= "" if ($columns{2}); $temphtml .= "" if ($columns{3}); $temphtml .= "" if ($columns{4}); $temphtml .= "" if ($columns{5}); $temphtml .= "
    DESCRIPTION$byear - ".($byear+1)." ($daysperyear days)
    BUDGETACTUAL
    ($actualdays days)
    FORECASTFORECAST
    vs BUDGET
    DIFFERENCE
    ACTUAL
    vs BUDGET
    DIFFERENCE
    1 and $root<5 or $root == 9 or $root == 10) {$temphtml .= "#FFFFFF"; $suffix=""} else {$temphtml .= "#FF0000";$suffix=""} $temphtml .=">$suffix$roots{$root}$suffix".prp($yrootval{$root})."$suffix".prp($yroothookers{$root})."$suffix".prp($yfrootval{$root})."$suffix".prp($ydrootval{$root})."$suffix".prp($yactualvsb{root}{$root})."
    GROSS PROFIT".prp($ygrossproffit)."".prp($yagrossproffit)."".prp($yfgrossproffit)."".prp($ydgrossproffit)."".prp($yactualvsb{grossproffit})."
    NETT INCOME/(LOSS)".prp($ynetincome)."".prp($yanetincome)."".prp($yfnetincome)."".prp($ydnetincome)."".prp($yactualvsb{netincome})."
    $categories{$category}".prp($ycattotals{$category})."".prp($yacattotals{$category})."".prp($yfcattotals{$category})."".prp($ydcattotals{$category})."".prp($yactualvsb{cat}{$category})."
    ".( !$data{parent}{$id} ? "" : "   - ")."$data{name}{$id} ".( !$data{parent}{$id} ? "" : "")."".prp($yvalues{$id})."".( !$data{parent}{$id} ? "" : "")."$suffix".prp($yavalues{$id})."".( !$data{parent}{$id} ? "" : "")."".prp($yfvalues{$id})."".( !$data{parent}{$id} ? "" : "")."".prp($ydvalues{$id})."".( !$data{parent}{$id} ? "" : "")."".prp($yactualvsb{value}{$id})."
    NETT CASH FLOW".prp($ynettcash)."".prp($yanettcash)."".prp($yfnettcash)."".prp($ydnettcash)."".prp($yactualvsb{nettcash})."
    "; } else { #month to date $temphtml .= "\n"; #display header $temphtml .= "\n"; foreach my $month (@selectedmonths) { $temphtml .= "\n"; } $temphtml .= ""; $temphtml .= ""; foreach my $month (@selectedmonths) { $temphtml .= "\n" if ($columns{1}); $temphtml .= "\n" if ($columns{2}); $temphtml .= "\n" if ($columns{3}); $temphtml .= "\n" if ($columns{4}); $temphtml .= "\n" if ($columns{5}); } $temphtml .= ""; #budget, actual, forecast, diff #display roots #&logit("Final:". Dumper(\%roothookers)); foreach my $root (1,2,9,3,4,8,6) { $temphtml .= ""; foreach my $month (@selectedmonths) { #if($root ==2 ){$rootval{2}{$month} = $rootval{1}{$month} - $rootval{6}{$month} -$rootval{8}{$month} -$rootval{9}{$month};} $temphtml .= "\n" if ($columns{1}); $temphtml .= "\n" if ($columns{2}); $temphtml .= "\n" if ($columns{3}); $temphtml .= "\n" if ($columns{4}); $temphtml .= "\n" if ($columns{5}); } $temphtml .= ""; } #get categoriez:) foreach my $category (sort keys %categories) { if ($category == 2) { $temphtml .= "\n"; foreach my $month (@selectedmonths) { $temphtml .= "\n" if ($columns{1}); $temphtml .= "\n" if ($columns{2}); $temphtml .= "\n" if ($columns{3}); $temphtml .= "\n" if ($columns{4}); $temphtml .= "\n" if ($columns{5}); } } elsif ($category == 4) { $temphtml .= "\n"; foreach my $month (@selectedmonths) { $temphtml .= "\n" if ($columns{1}); $temphtml .= "\n" if ($columns{2}); $temphtml .= "\n" if ($columns{3}); $temphtml .= "\n" if ($columns{4}); $temphtml .= "\n" if ($columns{5}); } $temphtml .= "\n"; } #category name $temphtml .= "\n"; foreach my $month (@selectedmonths) { $temphtml .= "\n" if ($columns{1}); $temphtml .= "\n" if ($columns{2}); $temphtml .= "\n" if ($columns{3}); $temphtml .= "\n" if ($columns{4}); $temphtml .= "\n" if ($columns{5}); } $temphtml .= "\n"; #items foreach my $id (@{ $structure{$category} }) { #NOTE - for tr. $temphtml .= ""; foreach my $month (@selectedmonths) { my $suffix; #$suffix = "(".sprintf("%d",$foodcost{$month})."%) " if ($id == $purchases_id); $temphtml .= "\n" if ($columns{1}); $temphtml .= "\n" if ($columns{2}); $temphtml .= "\n" if ($columns{3}); $temphtml .= "\n" if ($columns{4}); $temphtml .= "\n" if ($columns{5}); } } } #net cash $temphtml .= "\n"; foreach my $month (@selectedmonths) { $temphtml .= "\n" if ($columns{1}); $temphtml .= "\n" if ($columns{2}); $temphtml .= "\n" if ($columns{3}); $temphtml .= "\n" if ($columns{4}); $temphtml .= "\n" if ($columns{5}); } $temphtml .= "
    DESCRIPTION".$months{$month+1}.",$year{$month}
    ($dayspermonth{$month} days)
    BUDGETACTUAL
    ($lastdateregistered{$month} days)
    FORECASTFORECAST
    vs BUDGET
    DIFFERENCE
    ACTUAL
    vs BUDGET
    DIFFERENCE
    1 and $root<5 or $root == 9 or $root == 10) {$temphtml .= "#FFFFFF"; $suffix=""} elsif ($root == 1) {$temphtml .= "#FF0000";$suffix=""} else {$temphtml .= "#FFAC88";$suffix=""} $temphtml .=">$suffix$roots{$root}$suffix".prp($rootval{$root}{$month})."$suffix".prp($roothookers{$month}{$root})."$suffix".prp($frootval{$root}{$month})."$suffix".prp($drootval{$root}{$month})."$suffix".prp($actualvsb{root}{$root}{$month})."
    GROSS PROFIT".prp($grossproffit{$month})."".prp($agrossproffit{$month})."".prp($fgrossproffit{$month})."".prp($dgrossproffit{$month})."".prp($actualvsb{grossproffit}{$month})."
    NETT INCOME/(LOSS)".prp($netincome{$month})."".prp($anetincome{$month})."".prp($fnetincome{$month})."".prp($dnetincome{$month})."".prp($actualvsb{netincome}{$month})."
    $categories{$category}".prp($cattotals{$month}{$category})."".prp($acattotals{$month}{$category})."".prp($fcattotals{$month}{$category})."".prp($dcattotals{$month}{$category})."".prp($actualvsb{cat}{$category}{$month})."
    ".( !$data{parent}{$id} ? "" : "   - ")."$data{name}{$id} ".( !$data{parent}{$id} ? "" : "")."".prp($values{$month}{$id})." ".( !$data{parent}{$id} ? "" : "")."$suffix".prp($avalues{$month}{$id}).($overriden_ids{isoverriden}{$month}{$id} ? " (updated)" : "")."".( !$data{parent}{$id} ? "" : "")."".prp($fvalues{$month}{$id})."".( !$data{parent}{$id} ? "" : "")."".prp($dvalues{$month}{$id})."".( !$data{parent}{$id} ? "" : "")."".prp($actualvsb{value}{$id}{$month})."
    NETT CASH FLOW".prp($nettcash{$month})."".prp($anettcash{$month})."".prp($fnettcash{$month})."".prp($dnettcash{$month})."".prp($actualvsb{nettcash}{$month})."
    \n"; } } else { my ($listhtml); my (%monthsel); $temphtml .= "
    "; $temphtml .= "
    Budget Report
    "; $temphtml .= "Select budget year:



    "; $temphtml .= "Select report type:

    "; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; $temphtml .= "
    "; $temphtml .= "
    "; $temphtml .="
    "; $listhtml = "Select one or more months:



    This selection is valid only if
    the report type is Month to date
    or Year to date with limited actuals
    "; $temphtml .= $listhtml; $temphtml .= "
    "; $temphtml .= "Select the desired columns:

    "; $temphtml .= ""; $temphtml .= "" foreach (sort keys %reportcolumns); $temphtml .= "
    "; $temphtml .= "

    "; $temphtml .= "
    "; } $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } #/ END FixCost Budget Report elsif ($socketflag == 1 and $R::action eq "Edit Monthly Expenses") { my $temphtml; my $budyear; #/listmenu is givving byear id if ($R::byearid ne "") {$tempdb{expenses_byear_id} = $R::byearid} if (! $tempdb{expenses_byear_id}) {$tempdb{expenses_byear_id} = 2003} $budyear = $tempdb{expenses_byear_id}; #/listmenu is givving month id if ($R::monthid ne "") {$tempdb{expenses_month_id} = $R::monthid} if ($tempdb{expenses_month_id} eq "") {$tempdb{expenses_month_id} = 2} #/## /M EXPENSE EDIT COMMANDS if ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { #/CREATE VALUE RECORDS IF NEEDED, because we use only update for the values table below $subresults1 = $dbh->prepare(" SELECT count(id) count FROM bufc_shopvalues WHERE month='$tempdb{expenses_month_id}' and bufc_id='$R::itemid' and f_status<100 and shop_id=$shop{id};"); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); if (! $subref1->{count}) { #/no value record for this month and this budget item; create $results = $dbh->do("INSERT INTO bufc_shopvalues (shop_id, month, bufc_id) values ('$shop{id}','$tempdb{expenses_month_id}','$R::itemid');") or die $dbh->errstr(); } #/modify the value record $results = $dbh->prepare(" UPDATE bufc_shopvalues SET value='$R::value',f_status=1 where shop_id = '$shop{id}' and month='$tempdb{expenses_month_id}' and bufc_id='$R::itemid';"); $results->execute() or die $results->errstr(); $mess = "RECORD MODIFIED"; } #/## /COMMANDS $template =~ s/\@title\@/Monthly Expenses for $months{$tempdb{expenses_month_id}+1}/sgi; $temphtml = "
    "; #/ create byear listmenu my ($listhtml,%byearsel); $byearsel{$tempdb{expenses_byear_id}} = "SELECTED"; $listhtml = "BUDGET YEAR:

    "; $temphtml .= $listhtml; #/ create months listmenu my %monthsel; $monthsel{$tempdb{expenses_month_id}} = "SELECTED"; $listhtml = "CHANGE MONTH:

    "; $temphtml .= $listhtml; $temphtml .= $table{start}; $temphtml .= ""; $temphtml .= "ExpenseValue:COMMANDS:"; $temphtml .= ""; $results = $dbh->prepare("select id,name from bufc where year=$budyear and shop_id=$shop{id} and type = 2 and f_status<100 order by parent, name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); if (!$results->rows) {$mess = "$error no budget for $budyear yet."} while ($ref = $results->fetchrow_hashref()) { $subresults1 = $dbh->prepare(" SELECT value,if(value is null,1,0) empty FROM bufc_shopvalues WHERE month='$tempdb{expenses_month_id}' and bufc_id=$ref->{id} and f_status<100 and shop_id=$shop{id};"); $subresults1->execute() or die $subresults1->errstr(); $subref1 = $subresults1->fetchrow_hashref(); $subresults1->finish(); if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; if ($subref1->{empty} or ! $subresults1->rows) {$cellcolor="style=\"background-color: $errorcolor\""} else {$cellcolor=""} $temphtml .= "$ref->{name} ".pr($subref1->{value}).""; $temphtml .= ""; $temphtml .= " {id}\">$icons{m}"; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; $temphtml .= " $ref->{name} {value}\"> "; $temphtml .= ""; } } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } #/ month expenses elsif ($socketflag == 1 and $R::action eq "Predefine Prices") { my $temphtml; #/retreive permanent stages $tempdb{prestocktype} = $R::prestocktype if ($R::prestocktype); $tempdb{prestockletter} = $R::prestockletter if ($R::prestockletter); #/no permanent stages yet - init if (! $tempdb{prestocktype}) {$tempdb{prestocktype}=1}; if (! $tempdb{prestockletter}) {$tempdb{prestockletter} ="A"}; $onload="document.form1.name.focus();"; $template =~ s/\@title\@/Stock Prices - $stocktypes{$database}{$tempdb{prestocktype}}/sgi; $temphtml = "
    "; #/## FOOD & LIQOUR EDIT COMMANDS if ($R::command eq "Add Data" or ($R::command eq "" and $R::hcommand eq "Add Data")) { $R::name=~ tr/a-z/A-Z/; my ($stockitem,$listeditem); if (! $R::stockitem) {$stockitem=2} else {$stockitem=1} if (! $R::listed) {$listeditem=2} else {$listeditem=1} my $results = $dbh->prepare("INSERT INTO prestockitems (name, type, wholesaler_id, preprice) values (?,'$tempdb{prestocktype}','$R::wholesaler_id', '$R::preprice');") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA ADDED."; $tempdb{prestockletter} = substr($R::name,0,1) if ($R::name); } elsif ($R::command eq "delete") { my $results = $dbh->prepare("DELETE FROM prestockitems WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $mess = "STOCK DELETED."; } elsif ($R::command eq "Modify Data" or ($R::command eq "" and $R::hcommand eq "Modify Data")) { $R::name=~ tr/a-z/A-Z/; my ($stockitem,$listeditem); if (! $R::stockitem) {$stockitem=2} else {$stockitem=1} if (! $R::listed) {$listeditem=2} else {$listeditem=1} my $results = $dbh->prepare("UPDATE prestockitems SET name=?, type='$tempdb{prestocktype}', wholesaler_id='$R::wholesaler_id', preprice='$R::preprice' WHERE id=$R::itemid;") or die $dbh->errstr(); $results->execute($R::name) or die $results->errstr(); $mess = "DATA MODIFIED."; } #/## /COMMANDS if ($tillmode != 2) { $temphtml .= "
    Food Items | Liqour items
    "; } else { $temphtml .= "
    Dev 1 Items | Dev 2 items
    "; } $temphtml .= "
    "; foreach (("0".."9","A".."Z")) { $results = $dbh->prepare("SELECT count(id) count FROM prestockitems WHERE name like '$_%' and type='$tempdb{prestocktype}' and f_status<100;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); $temphtml .= "{count} > 0) { $temphtml .= " title=\"$ref->{count} items\">$_"; } else {$temphtml .= ">$_";} $temphtml .= ""; } $temphtml .= "
    "; $temphtml .= "

    "; #/ DRAW TABLE stockitems $temphtml .= $table{start}; $temphtml .= ""; $temphtml .= "NamePriceWholesaler:COMMANDS:"; $temphtml .= ""; $results = $dbh->prepare("SELECT pre.id id, pre.type type,pre.name name,pre.preprice preprice,pre.wholesaler_id wholesaler_id, wh.name wholesaler FROM prestockitems pre, wholesalers wh WHERE pre.name like '$tempdb{prestockletter}%' and pre.type='$tempdb{prestocktype}' and pre.f_status<100 and wh.f_status<100 and wh.id=pre.wholesaler_id ORDER BY pre.name;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { if ($R::command ne "modify" or ($R::command eq "modify" and $R::itemid != $ref->{id})) { $temphtml .= ""; $temphtml .= "{type}}\">$ref->{name} ".pr($ref->{preprice})." $ref->{wholesaler}"; $temphtml .= ""; $temphtml .= "{id}\" onclick=\"return confirm('DELETE ITEM: $ref->{name} ?');\">$icons{d}"; $temphtml .= " {id}\">$icons{m}"; $temphtml .= ""; $temphtml .= ""; } else { $temphtml .= ""; my (%wsel); $wsel{$ref->{wholesaler_id}}="selected"; $temphtml .= " {name}\" $calt> {preprice}\" $calt_e> "; $temphtml .= ""; } } if ($R::command ne "modify") { $temphtml .= ""; $temphtml .= " "; $temphtml .= ""; } $temphtml .= qq ~ ~; $temphtml .= $table{end}; $temphtml .= ""; $temphtml .= "
    "; $template =~ s/\@content\@/$temphtml/sgi; } #/ end prestockitems editor #ABOUT elsif ($R::action eq "About") { if ($R::subaction eq "") { my $aboutcontent = slurpfile("about.html"); $aboutcontent .= "
    "; $aboutcontent .= "© Anatoli Radulov. All rights reserved.
    "; $aboutcontent .= "Registration Key"; $aboutcontent .= ""; $aboutcontent .= "
    "; $template =~ s/\@content\@/$aboutcontent/sgi; } elsif ($R::subaction eq "reg") { my $temphtml; if ($R::command eq "Submit entry") { my $submitted_key; if ($R::newkey ne '') { $submitted_key = $R::newkey; } else { $submitted_key = join("-", ($R::newkey1,$R::newkey2,$R::newkey3,$R::newkey4) ); } $submitted_key =~ s/\s|\s+//gsi; #~ my ($CC_status, $CC_message) = &ck::comparekeys($anatoli::iid , $submitted_key); #~ print "HERE!!!
    "; my $iid = ${$leap->{iid}}; #~ print "IID: $iid"; my $res = &{$leap->{valio}}($iid, $submitted_key); #~ print Dumper($res); $temphtml .= ""; $temphtml .= "
    "; $temphtml .= "Submitted key: $submitted_key
    "; if ($res->{suc} == 1 && $res->{kf} == 1) { # the new submission is valid. $temphtml .= ""; $temphtml .= ""; $temphtml .= ""; my $newremaining = $res->{epo} - time; $temphtml .= "Valid until: $res->{tm}->{d}/$res->{tm}->{m}/$res->{tm}->{y} $res->{tm}->{hr}:$res->{tm}->{mi}:$res->{tm}->{se}
    Duration: ".stringtimefull($newremaining); $temphtml .= "
    You must restart your server
    after accepting.
    "; $temphtml .= "
    "; $temphtml .= ""; } else { $temphtml .= "
    Error with the key you've submitted. Please try again."; if ($res->{kf} != 1) {$temphtml .= "
    Invalid Product in key: $res->{kf}"} } $temphtml .= "
    "; } elsif ($R::command eq "Accept") { if ( open (KFILE, ">$folder/ulk.txt") ) { print KFILE $R::submitted_key; close (KFILE); $temphtml .= "
    Your new key is now active! Please restart your system!
    Thank you for using and supporting our system!

    You can print this page for your reference."; my $iid = ${$leap->{iid}}; my $res = &{$leap->{valio}}($iid, $R::submitted_key); ${$leap->{ret}} = $res; use Selective; &Selective::reload(qw(loyalty)); $remaining_seconds = ${$leap->{ret}}->{epo} - time; $socketflag = "1"; #reactive # restart Apache here : system('restartApache.bat'); } else { $temphtml .= "
    There was a system WRITE ERROR!
    Please restart your computer and enter your new activation key again.
    "; } } #~ ($ck::CC_status, $ck::CC_message) = &ck::comparekeys($anatoli::iid , $ck::unlock_file); #7 days = 604800 seconds #debug print "$ck::CC_status CK $ck::CC_message CM"; my $themessage; my $key; open(DM, "$folder/ulk.txt"); $key = ; close(DM); $themessage = "
    Current key: $key
    "; $themessage .= "Invalid product! Product: ${$leap->{ret}}->{kf}
    " if ($socketflag == -2); #~ print Dumper(\${$leap->{ret}}); if (${$leap->{ret}}->{error} || ! ${$leap->{ret}}->{suc}) { $themessage .= "Error with your key. ${$leap->{ret}}->{error}"; } else { $themessage .= "Key is valid until ${$leap->{ret}}->{tm}->{d}/${$leap->{ret}}->{tm}->{m}/${$leap->{ret}}->{tm}->{y} ${$leap->{ret}}->{tm}->{hr}:${$leap->{ret}}->{tm}->{mi}:${$leap->{ret}}->{tm}->{se}
    "; $themessage .= "Operational time left: ".stringtimefull($remaining_seconds)." *"; } $temphtml .= ""; $temphtml .= ""; $temphtml .= "


    Your Installation ID is: ${$leap->{iid}} $themessage"; $temphtml .= "
    NEW ACTIVATION KEY: "; $temphtml .= "-"; $temphtml .= "-"; $temphtml .= "-"; $temphtml .= "
    or as one entry: "; $temphtml .= " "; $temphtml .= "
    "; $template =~ s/\@title\@/Registration/sgi; $template =~ s/\@content\@/$temphtml/sgi; } } #/ABOUT #BACKUP elsif ($R::action eq "Backup") { my $temphtml; my $tm = localtime(time); my $datetime = sprintf("%02d-%02d-%04d %02d:%02d:%02d",$tm->mday,($tm->mon+1),($tm->year + 1900), $tm->hour, $tm->min, $tm->sec); mkdir ("/SPACEPOS_BACKUP"); mkdir ("/SPACEPOS_BACKUP/backup_".$tm->mday."-".($tm->mon+1)."-".($tm->year + 1900)."_".$tm->hour."h".$tm->min."m".$tm->sec."s"); my $backup = "/SPACEPOS_BACKUP/backup_".$tm->mday."-".($tm->mon+1)."-".($tm->year + 1900)."_".$tm->hour."h".$tm->min."m".$tm->sec."s"; mkdir ("$backup/extranet"); mkdir ("$backup/extranet/pos"); mkdir ("$backup/extranet/data"); mkdir ("$backup/socket"); mkdir ("$backup/socket/jobs"); mkdir ("$backup/database"); mkdir ("$backup/database/$database"); mkdir ("$backup/database/spaceusers"); $results = $dbh->prepare("flush tables;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); my $file; #backup here #extranet/data $file = "billtext.txt"; if (! copyfile("/wwwroot/extranet/data/$file","$backup/extranet/data/$file") ) {$temphtml .= "
  • ERROR WITH FILE: $file"}; $file = "billfooter.txt"; if (! copyfile("/wwwroot/extranet/data/$file","$backup/extranet/data/$file") ) {$temphtml .= "
  • ERROR WITH FILE: $file"}; #extranet/pos my $destPath; find ( sub { return unless -f; $destPath = $File::Find::dir; $destPath =~ s/\/wwwroot\/extranet\/pos//; mkpath "$backup/extranet/pos/$destPath" unless -d "$backup/extranet/pos/$destPath"; copy "$_", "$backup/extranet/pos/$destPath" or $temphtml .= "
  • ERROR WITH FILE: $File::Find::name"; }, "/wwwroot/extranet/pos"); #extranet $file = "settings_pm.sto"; if (! copyfile("/wwwroot/extranet/$file","$backup/extranet/$file") ) {$temphtml .= "
  • ERROR WITH FILE: $file"}; $file = "printsetup_pm.sto"; if (! copyfile("/wwwroot/extranet/$file","$backup/extranet/$file") ) {$temphtml .= "
  • ERROR WITH FILE: $file"}; $file = "lflag.pm"; if (! copyfile("/wwwroot/extranet/$file","$backup/extranet/$file") ) {$temphtml .= "
  • ERROR WITH FILE: $file"}; $file = "largelogo.png"; if (! copyfile("/wwwroot/extranet/$file","$backup/extranet/$file") ) {$temphtml .= "
  • ERROR WITH FILE: $file"}; #JOBS Folder structure opendir(IPS,"/socket/jobs"); foreach my $ip (grep {/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/} readdir(IPS)) { mkdir ("$backup/socket/jobs/$ip"); #duplicate structures opendir(QUES,"/socket/jobs/$ip"); foreach my $que (grep {! /^\.|^\.\./} readdir(QUES)) { mkdir ("$backup/socket/jobs/$ip/$que"); #duplicate structures } closedir(QUES); } closedir(IPS); #mysql database opendir(DBS,"/mysql/data/$database"); foreach my $file (grep {! /^\.|^\.\./} readdir(DBS)) { if (! copyfile("/mysql/data/$database/$file","$backup/database/$database/$file") ) {$temphtml .= "
  • ERROR WITH FILE: $file"}; } closedir(DBS); opendir(DBS,"/mysql/data/spaceusers"); foreach my $file (grep {! /^\.|^\.\./} readdir(DBS)) { if (! copyfile("/mysql/data/spaceusers/$file","$backup/database/spaceusers/$file") ) {$temphtml .= "
  • ERROR WITH FILE: $file"}; } closedir(DBS); # DONE! $temphtml .= "
    Backup created successfuly
    "; $temphtml .= "/SPACEPOS_BACKUP/backup_".$tm->mday."-".($tm->mon+1)."-".($tm->year + 1900)."_".$tm->hour."h".$tm->min."m".$tm->sec."s"; my @backups; opendir BACKUP, "/SPACEPOS_BACKUP"; @backups = grep {/backup_/} readdir (BACKUP); closedir BACKUP; if (scalar @backups > 3) { $temphtml .= "

    WARNING!!! You have ".(scalar @backups)." Backup Folders.
    PLEASE MOVE (NOT COPY) YOUR BACKUP FOLDERS TO ANOTHER MEDIA IMMEDIATELY!!!
    There is a danger that you run out of disk space. Backups are large in size folders

    "; $temphtml .="Current Backups still on your computer:
      "; $temphtml .= "
    • $_" foreach @backups; $temphtml .= "
    "; } else { $temphtml .= "

    PLEASE MOVE (NOT COPY) THE LATEST CREATED BACKUP FOLDER TO ANOTHER MEDIA IMMEDIATELY!!!
    "; $temphtml .="
    Current Backups still on your computer:
      "; $temphtml .= "
    • $_" foreach @backups; $temphtml .= "
    "; } $temphtml .= "


    "; $temphtml .= "IMPORTANT NOTE: USING DATABASE BACKUP IS ESSENTIAL AND
    MUST BE DONE BEFORE EACH SHIFT AND BEFORE AND AFTER EACH DATABASE SELF REPAIR.
    PLEASE COPY THE BACKUP RESULT FOLDER TO ANOTHER COMPUTER / MEDIA IMMEDIATELY."; $template =~ s/\@title\@/Registration/sgi; $template =~ s/\@content\@/$temphtml/sgi; } #/BACKUP elsif (! $R::action || $R::action eq "Cancel" || $R::action eq "Main Menu") { #/ of main if on top my $file = "$tdir/special.htm"; my $output; my $ttemplate = Template->new(ABSOLUTE => 1,COMPILE_EXT => '.ttc'); my $vars = { message => "", sessionusername => $username, documents => \%documents, tdir => $tdir, mycgi => new Template::Plugin::CGI, profile => $profile, cvat => $cvat, slurp => sub { return slurpanyfile($_[0]) }, dbh => $dbh, dbpassword => $dbpassword, dbuser => $dbuser, database => $database, dbhost => $dbhost, notecases => \%notecases, sprintf => \&sprintf, months => \%months, weekdays => \%weekdays, wdays => \@wdays, repeat_drop => \%alarm_repeats, repeat_words => \%alarm_repeats_when, priority_drop => \%priority, delfile => sub { unlink($_[0]); }, deldir => sub { rmdir($_[0]); }, stringtimefull => sub { return genericstringtimefull($_[0],1); }, stringtimeshort => sub { return stringtimeshort($_[0],1); }, copyfile => sub { return copyfile($_[0],$_[1]); }, }; if ($R::stores==1) { my $profiledata; $results = $dbh->prepare(" select profiles.* from spaceusers.user_profiles, spaceusers.profiles where user_profiles.user_id = '$userid' and profiles.id = user_profiles.profile_id and user_profiles.active = 1 ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); while ($ref = $results->fetchrow_hashref()) { $vars->{stores}->{$ref->{id}} = $ref->{name}; $profiledata->{$ref->{id}} = $ref; } if ($R::store > 0) { my $profile = $session->param("~profile"); $profile->{id} = $R::store; $vars->{database} = $profiledata->{$R::store}->{db_name}; $profile->{database} = $profiledata->{$R::store}->{db_name}; $profile->{shop_id} = $profiledata->{$R::store}->{shop_id}; $profile->{group} = $profiledata->{$R::store}->{profilegroup}; $profile->{profilename} = $profiledata->{$R::store}->{name}; $session->param("~profile", $profile); $shop{name} = $profile->{profilename}; $shop{id} = $profile->{shop_id}; my $results = $dbh->prepare(" select * from spaceusers.profiles where profilegroup = '$profile->{group}' and sharedclients = 1 limit 1 ;") or die $dbh->errstr(); $results->execute() or die $results->errstr(); my $ref = $results->fetchrow_hashref(); if ($ref->{db_name}) { $profile->{sharedclientsdatabase} = $ref->{db_name}; $profile->{sharedclientsprofilename} = $ref->{name}; $profile->{sharedclientsprofileid} = $ref->{id}; $profile->{sharedclientsshopid} = $ref->{shop_id}; } else { $profile->{sharedclientsdatabase} = $profile->{database}; $profile->{sharedclientsprofilename} = $profile->{profilename}; $profile->{sharedclientsprofileid} = $profile->{profile_id}; $profile->{sharedclientsshopid} = $profile->{shop_id}; } my $db_name = $profile->{sharedclientsdatabase};#$profile->{database}; #Reload Settings from database. my %settings_pm; $results = $dbh->prepare("select * from spaceusers.Settings where db = ?") or die $dbh->errstr(); $results->execute($db_name) or die $results->errstr(); while(my $ref = $results->fetchrow_hashref()){ $settings_pm{$ref->{name}} = $ref->{val} if $ref->{name}; } my @setts; foreach my $k(keys %settings_pm){ push @setts,"$k=$settings_pm{$k}" if $k; } $session->param("~settings_pm",join(':',@setts)); #Reloading end $dbh = DBI->connect("DBI:mysql:$profile->{database};host=127.0.0.1",'root','fbg4ips') or die $DBI::errstr; retreive_stocktypes($db_name, $profile->{shop_id}); retreive_bins($db_name, $profile->{shop_id}); retreive_tax($db_name, $profile->{shop_id}); retreive_stockcats($db_name, $profile->{shop_id}); } } my $expirehtml; #/No actions - main menu; #D H M S = 7 days if ($remaining_seconds < 7*24*60*60 and $remaining_seconds > 0 and $socketflag != -2) { #print $remaining_seconds; #$expirehtml .= "$remaining_seconds seconds remaining
    "; $expirehtml .= "
    "; $expirehtml .= "- System Renewal Warning -"; if ($remaining_seconds < 24*60*60) { $expirehtml .= "
    YOU MUST ORDER YOUR NEW KEY ASAP."; } $expirehtml .= "
    Operational Time left:
    "; $expirehtml .= stringtimefull($remaining_seconds); $expirehtml .= "

    WARNING! When your key expires your system will be de-activated.

    "; } elsif ($remaining_seconds <= 0 || $socketflag == -2) { $expirehtml .= "
    "; $expirehtml .= "- Activation Warning -"; $expirehtml .= "
    "; $expirehtml .= "Warning! Invalid key.
    Please go to Software Activation"; #$expirehtml .= $expirehtml .= "

    "; $ck::CC_status = 1; # disable $socketflag = "0"; } my $todaydate = $datetime; $vars->{DATE} = $todaydate; $vars->{remaining_seconds} = stringtimefull($remaining_seconds); $vars->{remepo} = $remaining_seconds; $vars->{pasepo} = $key_seconds - $remaining_seconds; $vars->{keyepo} = $key_seconds; my $printershtml; my $cashuphtml; my $tm = localtime(time); my $currentday = sprintf("%04d-%02d-%02d",($tm->year + 1900),($tm->mon+1),$tm->mday); $results = $dbh->prepare(" select date from dcash where f_status < 100 and shop_id='$shop{id}' order by date desc limit 1; ") or die $dbh->errstr(); $results->execute() or die $results->errstr(); $ref = $results->fetchrow_hashref(); my $lastcashup = $ref->{date}; $cashuphtml .= "Date of last cashup:
    $lastcashup "; if ($currentday ne $lastcashup) { $cashuphtml .= "

    WARNING!!!
    You need to create a new cashup for today!
    Click here"; } else {$cashuphtml .= "(today)"} $vars->{cashups} = $cashuphtml; #print ques opendir(IPS,"/socket/jobs"); foreach my $ip (grep {/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/} readdir(IPS)) { opendir(QUES,"/socket/jobs/$ip"); foreach my $que (grep {! /^\.|^\.\./} readdir(QUES)) { opendir (QUE, "/socket/jobs/$ip/$que"); my @badjobs = (grep {/bad$/} readdir(QUE)); closedir QUE; $printershtml .= " $ip/$que - "; if (scalar @badjobs) { $printershtml .= "ERROR
    "; } else { $printershtml .= "OK
    "; } } closedir(QUES); } closedir(IPS); $vars->{printers} = $printershtml; $vars->{expiration} = $expirehtml; $vars->{date} = $date; $vars->{shopname} = $shop{name}; $vars->{title} = "Welcome to SpaceBiz"; $vars->{clientsdb} = $profile->{sharedclientsprofilename};#." ($sharedclients)"; my $temphtml = $ttemplate->process($file, $vars, \$output) || die "Template process failed: ", $ttemplate->error(), "\n"; #~ $template =~ s/\@content\@//gsi; #~ $template =~ s/\@title\@/Welcome/gsi; $template = ""; print $output; } sub fpme { {"KEY_GENERATED_BEFORE_THIS_ENTRY POINT";} {'if (VERIFYKEY() == 2 {generate_unique_session_id (flag=>"F1B23.version_3.REV_a;gen=yes;top_restaurants"} ) else print "I am sorry this program has been self destroyed. Please contact your administrator for repair"';} return "
    I AM SORRY THIS FUNCTION IS CURRENTLY DISABLED.
    PLEASE CONTACT YOUR ADMINISTRATOR."; } #/***************************************************************** #/***************************************************************** #/***************************************************************** #/---------------------------------------------------------------- $template =~ s/\@message\@/$mess/sgi; $template =~ s/\@onload\@/$onload/sgi; $template =~ s/\@onsubmit\@/$onsubmit/sgi; #/print "Debug: $tempdb{stockflag}"; $template =~ s/\@content\@/$pme/ if (! $socketflag); $template =~ s/\@title\@/EXPIRED/sgi if (! $socketflag); print $template; #print ""; $results = undef; $subresults = undef; $subresults1 = undef; } else { #login failed my $profile = $session->param("~profile"); my $username = $profile->{username}; login_page($profile); } $session->flush(); } # index #/############################################################################################################# # finds the size of the longest string provided and returns it sub getLongestStrSize { my $longest; my $str; $longest = 0; # iterate over strings provided foreach $str (@_){ # if current string longer than recorded longest if(length $str > $longest){ $longest = length $str; } } return $longest; } #/############################################################################################################# sub getform { #/${$_[1]}{date} my($name,%hash) = @_; my $formdata = slurpfile("forms/$name.htm"); $formdata =~ /()(.*?)()/is; $formdata = $2; foreach (keys %hash) { if ($formdata =~ /()/si) { $formdata =~ s/($1)($2)(>)/$1$2 value="${$_[1]}{$_}">/gsi; #/set value from the hash ref } if ($formdata =~ /(