Plugin Directory

Changeset 2249413


Ignore:
Timestamp:
02/24/2020 04:06:10 PM (6 years ago)
Author:
munger41
Message:

cleaned code
comments cleaned
tested with WP 5.3+

Location:
export-stripe-csv/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • export-stripe-csv/trunk/readme.txt

    r1864017 r2249413  
    33Tags: stripe, csv, custom, export
    44Requires at least: 4.0
    5 Tested up to: 4.8
     5Tested up to: 5.3
    66
    77Create CSV custom exports for accountancy needs (including VAT)
     
    2121== Changelog ==
    2222
     231.2.2
     24
    23251.2.1 - cumulated debt and served fixed
    2426
  • export-stripe-csv/trunk/stripe_csv_exports.php

    r1910410 r2249413  
    11<?php
    2 
    32/*
    43 * Plugin Name: Stripe CSV Exports
     
    65 * Description: Query Stripe API to create custom CSV exports for accountancy needs
    76 * Author: Termel
    8  * Version: 1.2.1
     7 * Version: 1.2.2
    98 * Author URI: http://www.maxizone.fr/
    109 */
     
    1514// If you're using Composer, use Composer's autoload
    1615$stripe_api_path = dirname( __FILE__ ) . '/vendor/autoload.php';
    17 // Logger::getLogger("default")->debug("File : " . $stripe_api_path);
    1816$stripe_api_path = realpath( $stripe_api_path );
    1917require_once $stripe_api_path;
     
    5452        function __construct() {
    5553           
    56             // $this->setUpLogger();
    5754            add_action(
    5855                is_multisite() ? 'network_admin_menu' : 'admin_menu',
     
    6562            add_action( 'admin_init', array( $this, 'strcsvexp_email_report_now' ) );
    6663           
    67             // Logger::getLogger("default")->debug("construct strcsvexp_stripe_source_plugin");
    6864            self::getLogger()->trace( "Adding Module : " . __CLASS__ );
    6965            add_filter( "strcsvexp_stripe_file_to_array", array( $this, "stripe_to_array" ), 10, 2 );
     
    149145        static function getLogger() {
    150146            if ( self::$logger == null ) {
    151                 // gfchartreports_log ( "#################################" );
    152147                strcsvexp_log( "########" );
    153148                $dir = plugin_dir_path( __FILE__ );
     
    195190                return $this;
    196191            } else {
    197                 // add_options_page( string $page_title, string $menu_title, string $capability, string $menu_slug,
    198                 // callable $function = '' )
     192
    199193                add_options_page(
    200194                    $pageTitle,
     
    355349                    $end = $current - 5;
    356350                    while ( $year >= $end ) :
    357                         ?>                     
    358                
    359                
    360                
    361                
     351                        ?>         
    362352                <option value="<?php echo $year; ?>"><?php echo $year; ?></option>
    363353                        <?php
     
    368358                </select> <select name="strcsvexp-month" id="strcsvexp-month">
    369359                <option value="0"><?php _e( 'All months', 'strcsvexp' ); ?>
    370                     <?php for( $i = 1; $i <= 12; $i++ ) : ?>               
    371                
    372                
    373                
    374                
    375                
    376                
    377                
    378                
    379                
     360                    <?php for( $i = 1; $i <= 12; $i++ ) : ?>
    380361                <option value="<?php echo $i; ?>"><?php echo $this->strcsvexp_get_month_name( $i ); ?></option>
    381362                    <?php endfor; ?>
     
    400381                value="<?php _e( 'Send report NOW', 'strcsvexp' ); ?>" /> <input
    401382                type="hidden" name="strcsvexp-action" value="send-report-email" />
    402         </p>
    403        
    404                 <?php /*wp_nonce_field('strcsvexp_nonce', 'strcsvexp_nonce');*/ ?>
    405                 <?php /*submit_button('Send Now');*/ ?>
    406  
     383        </p>
    407384            </form>
    408385    <?php
    409386                } else
    410                     if ( $active_tab == 'encours_options' ) {
    411                        
     387                    if ( $active_tab == 'encours_options' ) {                       
    412388                        ?>
    413389    <!-- payments export -->
     
    426402                        while ( $year >= $end ) :
    427403                            ?> 
    428                
    429                
    430                
    431                
    432                
    433                
    434                
    435                
    436                
    437                
    438                
    439                
    440                
    441                
    442                 <option value="<?php echo $year; ?>"><?php echo $year; ?></option>
     404                    <option value="<?php echo $year; ?>"><?php echo $year; ?></option>
    443405                        <?php
    444406                            $year--;
     
    448410                </select> <select name="strcsvexp-month" id="strcsvexp-month">
    449411                <option value="0"><?php _e( 'All months', 'strcsvexp' ); ?>
    450                     <?php for( $i = 1; $i <= 12; $i++ ) : ?>               
    451                
    452                
    453                
    454                
    455                
    456                
    457                
    458                
    459                
    460                
    461                
    462                
    463                
    464                
    465                 <option value="<?php echo $i; ?>"><?php echo $this->strcsvexp_get_month_name( $i ); ?></option>
     412                    <?php for( $i = 1; $i <= 12; $i++ ) : ?>    <option value="<?php echo $i; ?>"><?php echo $this->strcsvexp_get_month_name( $i ); ?></option>
    466413                    <?php endfor; ?>
    467414                </select> <select name="strcsvexp-groupby" id="strcsvexp-groupby">
     
    543490            // add parameter to write the file for attachement
    544491            if ( $writeFile ) {
    545                 // $csv = Writer::createFromPath('/path/to/the/final.csv');
    546                
    547                 /*
    548                  * $file = new SplTempFileObject ();
    549                  * $file->setFlags ( SplFileObject::READ_CSV );
    550                  * $csv = Writer::createFromFileObject ( $file );
    551                  */
    552                 /*
    553                  * $upload_dir = wp_upload_dir(); // Array of key => value pairs
    554                  * $outputDir = $upload_dir['path'];
    555                  * self::getLogger ()->debug ('Writing to '.$outputDir); //=>
    556                  * C:\path\to\wordpress\wp-content\uploads\2010\05
    557                  * $csv = Writer::createFromPath($outputDir.$completeFilename);
    558                  */
     492               
    559493                $upload_dir = wp_upload_dir(); // Array of key => value pairs
    560494                $outputDir = $upload_dir['path'];
     
    590524
    591525        function strcsvexp_export_payments() {
    592             // Logger::getLogger("default")->debug($csv);
     526
    593527            if ( isset( $_POST['strcsvexp-action'] ) ) {
    594528               
     
    622556                        $shortcodeContent = '[strcsvexpStripe json="' . $jsonCharts . '"]';
    623557                        self::getLogger()->trace( $shortcodeContent );
    624                         // echo do_shortcode($shortcodeContent);
    625                         // die();
    626558                    }
    627559            }
     
    719651                                        "[$dataTypeKey][$yearKey] [$monthKey] [$weekKey] [$lineId]" );
    720652                                    $data[$dataTypeKey][$yearKey][$monthKey][$weekKey][$lineId][] = $payoutLinked;
    721                                     // self::getLogger ()->debug ($data [$dataTypeKey][$yearKey] [$monthKey] [$weekKey]
    722                                 // [$lineId]);
     653   
    723654                                }
    724655                            }
     
    728659            }
    729660           
    730             // self::getLogger()->trace($data);
    731            
    732661            return $data;
    733662        }
     
    737666            $result = array( );
    738667               
    739             // $refund = $this->addRefundIfExists($allRefunds, $report, $csv, $this->dateFormat);
    740668            $decimalAmont = $refund->amount / 100;
    741669            $creation_date = date( $this->dateFormat, $refund->created );
     
    798726                '' // number_format ($to_be_served_CA, $this->nbOfDecimals,',', ' '),
    799727            );
    800            
    801             /*
    802              * $report = array(
    803      
    804                     $id,
    805                 $description,
    806                 $chargeCreationDate,
    807                 $amount,
    808                 $export,
    809                 $vatValue,
    810                 $tvaAmount,
    811                 $HTamount,
    812                 $fee,
    813                 $finalGain,
    814                 $currency,
    815                 $plan_name,
    816                 $creation_date,
    817                 $start_date,
    818                 $end_subscription,
    819                 $cancelled_date,
    820                 $served_CA,
    821                 $to_be_served_CA );
    822              */
    823            
     728       
    824729            self::getLogger()->debug($report);
    825730            $result = array(
     
    871776            } else {
    872777                self::getLogger()->error( "Cannot find balance transaction for charge " . $id );
    873                 //self::getLogger()->error("### ". $bal_transaction);
    874                 //self::getLogger()->error("No impact on FEE ???");
    875                
    876778                return null;
    877779            }
     
    883785                return null;
    884786            }
    885             // self::getLogger ()->debug ( "working on first subscription " );
    886787           
    887788            $tva = $firstSubs->tax_percent;
     
    955856            $chargesAndRefunds = array_merge( $allCharges, $allRefunds->data );
    956857           
    957             //self::getLogger()->debug($chargesAndRefunds);
    958858            // sort by date
    959859           
     
    963863            }
    964864            array_multisort( $dateArray, $this->dateSort, $chargesAndRefunds );
    965            
    966             //self::getLogger()->debug($chargesAndRefunds);
    967            
    968            
    969            
    970             /*
    971              * $dateArray = array();
    972              * foreach ($refunds as $key => $row) {
    973              * $dateArray[$key] = $row->created;
    974              * }
    975              * array_multisort($dateArray, $this->dateSort, $refunds);
    976              */
    977865           
    978866            // sort end
     
    1030918                    $current_start_subscription->format( $this->dateFormat ) . ' #### Iterate from ' .
    1031919                    $currentMonthDate->format( $this->dateFormat ) . ' -> ' . $endIteration->format( $this->dateFormat ) );
    1032                 // $startOfTimeFrame = $currentMonthDate;
     920
    1033921                if ( strval( $groupby ) == 'none' ||  strval( $groupby ) == 'month' ||  strval( $groupby ) == 'week') {
    1034922                   
     
    1043931                    while ( $currentMonthDate < $endIteration ) {
    1044932                        $currentMonthDate = $currentMonthDate->add( $time_interval );
    1045                         // strtotime('this week', time());
    1046933                       
    1047934                        if ( strval( $groupby ) == 'month' ) {
     
    1062949                        self::getLogger()->debug( $current_period_start);
    1063950                        self::getLogger()->debug( $current_period_end);
    1064                        
    1065                        
    1066                         // Logger::getLogger("default")->debug('Compute served for '.$description.' between
    1067                         // '.$current_period_start->format($this->dateFormat).' ->
    1068                         // '.$current_period_end->format($this->dateFormat));
     951
    1069952                        if ( $current_period_start < $current_start_subscription &&
    1070                             $current_start_subscription < $current_period_end ) {
    1071                                
     953                            $current_start_subscription < $current_period_end ) {                           
    1072954                             
    1073                             // $debtArray = $this->getServed($subsNbOfDays, $day_price, $current_start_subscription,
    1074                             // $current_period_end, $current_end_date);
    1075955                            $reportArray[$export][$currentYear][$currentMonth][$currentWeek][$timestamp] = $report;
    1076956                            self::getLogger()->info( $idx.' / '.$totalOperations.' Inside timeframe');
    1077957                            self::getLogger()->debug('New report (charge) line : ' . implode( ' | ', $report ) );
    1078                             /*
    1079                              * $refund = $this->addRefundIfExists($allRefunds, $report, $csv, $this->dateFormat);
    1080                              * if ($refund) {
    1081                              * $creation_date = $refund[2];
    1082                              * // if ($current_period_start < $creation_date && $creation_date < $current_period_end) {
    1083                              * // $debtArray = $this->getServed($subsNbOfDays, $day_price, $current_start_subscription, $current_period_end, $current_end_date);
    1084                              * $reportArray[$export][$currentYear][$currentMonth][$currentWeek][] = $refund;
    1085                              * self::getLogger()->info('New report (refund) line : ' . implode(' - ', $report));
    1086                              * // }
    1087                              * }
    1088                              */
     958                       
    1089959                            } else {
    1090960                                self::getLogger()->trace(
     
    1094964                            }
    1095965                       
    1096                         // Logger::getLogger("default")->debug($current_start_subscription->format($this->dateFormat). ' / '.$current_period_start->format($this->dateFormat).' / '.$current_period_end->format($this->dateFormat).' - '.$debtArray['served'].' - '.$debtArray['debt']);
    1097966                    }
    1098967                }
     
    13201189               
    13211190                if ($stripe_charge) {
    1322                     /*
    1323                      * if ($subscription->id== 'sub_Aj7K0GYCgaGmk1') {
    1324                      * Logger::getLogger("default")->debug($stripe_charge);
    1325                      *
    1326                      * }
    1327                      */
     1191                   
    13281192                    // $amount = $stripe_charge->amount / 100;
    13291193                    $tva = $subscription->tax_percent / 100;
     
    13411205                       
    13421206                        $stripe_transaction = \Stripe\BalanceTransaction::retrieve ( $balId );
    1343                         /*
    1344                          * if ($subscription->id== 'sub_Aj7K0GYCgaGmk1') {
    1345                          * Logger::getLogger("default")->debug($stripe_transaction);
    1346                          * }
    1347                          */
     1207               
    13481208                        $fee = $stripe_transaction->fee / 100; // $subscription->application_fee_percent;
    13491209                                                               // self::getLogger()->debug("=> fee in transaction " . $fee);
     
    13991259            }
    14001260           
    1401             //Logger::getLogger ( "default" )->debug ( 'Compute served for ' . $type . ' ' . $day_price . '   SERVED:' . $result ['served'] . '  DEBT:' . $result ['debt'] . '  AMOUNT:' . $pricesArray [$type] );
     1261            Logger::getLogger ( "default" )->trace ( 'Compute served for ' . $type . ' ' . $day_price . '   SERVED:' . $result ['served'] . '  DEBT:' . $result ['debt'] . '  AMOUNT:' . $pricesArray [$type] );
    14021262           
    14031263            return $result;
     
    14141274                // Get the required charge information and assign to variables
    14151275                $id = $subscription->id;
    1416                 /*
    1417                  * if ($id == 'sub_Aj7K0GYCgaGmk1') {
    1418                  * self::getLogger()->info($subscription);
    1419                  * }
    1420                  */
     1276               
    14211277               
    14221278                $creation_date = date ( $this->dateFormat, $subscription->created );
     
    14361292                $current_start_subscription = new DateTime ( $current_start_date );
    14371293                self::getLogger ()->info ( "######### Process sub : " . $id );
    1438                 /*
    1439                  * if ($subscription->status != 'active') {
    1440                  * self::getLogger()->warn("skips " . $subscription->status . " subs " . $id);
    1441                  * continue;
    1442                  * }
    1443                  */
     1294       
    14441295                if ($current_start_subscription < $start_reference || $current_start_subscription > $reference_date) {
    14451296                    self::getLogger ()->warn ( $current_start_date );
    14461297                    self::getLogger ()->warn ( "outside ref date range" );
    1447                     /*self::getLogger ()->warn ( $start_reference );
    1448                     self::getLogger ()->warn ( $reference_date );*/
     1298           
    14491299                    continue;
    14501300                } else {
    14511301                    self::getLogger ()->info ( $id . ' -- ' . $month_start . " < " . $creation_date . " (" . $current_start_date . ") " . ' < ' . $reportEndDate );
    1452                     // Logger::getLogger("default")->debug($month_start." -> ".$reportEndDate);
     1302                    Logger::getLogger("default")->trace($month_start." -> ".$reportEndDate);
    14531303                }
    14541304               
     
    14721322                $subsNbOfDays = $this->getSubscriptionDayDuration ( $current_start_subscription, new DateTime ( $end_date ) );
    14731323               
    1474                 /*
    1475                  *
    1476                  * $net_day_price = $finalGain / $subsNbOfDays;
    1477                  * $ttc_day_price = $pricesArray['TTC']/ $subsNbOfDays;
    1478                  * $ht_day_price = $pricesArray['HT']/ $subsNbOfDays;
    1479                  */
    1480                
    1481                 // Logger::getLogger("default")->debug("Day Price : $day_price = $finalGain / $subsNbOfDays");
    1482                 // served : CA SUR SERVICE
    1483                
    1484                 // Logger::getLogger("default")->debug($current_start_subscription->date);
     1324           
    14851325               
    14861326                if (strval ( $groupby ) != 'none') {
     
    15271367                                $debtArray [$type] = $this->getServed ( $subsNbOfDays, $type, $pricesArray, $current_start_subscription, $current_month_end, $current_end_date );
    15281368                            } else {
    1529                                 /*
    1530                                  * $debtArray[$type]['served'] = 0;
    1531                                  * $debtArray[$type]['debt'] = 0;
    1532                                  */
     1369                   
    15331370                                continue;
    15341371                            }
     
    15771414                        }
    15781415                        $debtArray [$type] = $this->getServed ( $subsNbOfDays, $type, $pricesArray, $current_start_subscription, new DateTime ( $current_month_end ), new DateTime ( $current_end_date ) );
    1579                         /*
    1580                          * $globalDebt[$chargeType][$currentYear][$currentMonth][$type]['served'] += $debtArray[$type]['served'];
    1581                          * $globalDebt[$chargeType][$currentYear][$currentMonth][$type]['debt'] += $debtArray[$type]['debt'];
    1582                          */
     1416               
    15831417                        self::getLogger ()->debug ("---- SERVED / DEBT ".$type." ----");
    15841418                        self::getLogger ()->debug ($debtArray [$type]);
     
    16131447                   
    16141448                    $globalDebt [$chargeType] [] = $report;
    1615                     /*
    1616                      * $sumReport [] = $report;
    1617                      * $formatted_export = $this->getFormattedArrayValues ( $report );
    1618                      * // array_map(function($num){return !is_numeric($num) ? $num: number_format($num,$this->nbOfDecimals,',', ' ');}, $report);
    1619                      *
    1620                      * $csv->insertOne ( $formatted_export );
    1621                      *
    1622                      */
     1449                   
    16231450                }
    16241451            }
     
    16941521                    $bigTotDebtNET += $sumTotDebt;
    16951522                   
    1696                     /*
    1697                      * $sumCumulServed = array_sum ( array_column ( $allLines, 6 ) );
    1698                      * //$bigTotCumulServed += $sumCumulServed;
    1699                      * $sumCumulDebt = array_sum ( array_column ( $allLines, 7 ) );
    1700                      * //$bigTotCumulDebt += $sumCumulDebt;
    1701                      * $reportLine = array(
    1702                      * '',
    1703                      * '',
    1704                      * '',
    1705                      * __('Total'). ' '.$globalType,
    1706                      * $sumTotServed,
    1707                      * $sumTotDebt,
    1708                      * $sumCumulServed,
    1709                      * $sumCumulDebt
    1710                      * );
    1711                      * $formatted_line = $this->getFormattedArrayValues($reportLine);
    1712                      */
     1523                   
    17131524                    $csv->insertOne (array());
    1714                     /*
    1715                      * $csv->insertOne($formatted_line);
    1716                      * $csv->insertOne();
    1717                      */
     1525           
    17181526                }
    17191527               
     
    17631571                    $defaultValues = $defaultValues + $endOfLine;
    17641572                    $formatted_sums_line = $this->getAggregatedData ( $globalData, $defaultValues, $groupby );
    1765                     /*
    1766                      * self::getLogger()->info($totalTitle);
    1767                      * self::getLogger()->info($formatted_sums_line);
    1768                      */
     1573           
    17691574                    $csv->insertOne ( $formatted_sums_line );
    17701575                    $csv->insertOne (array());
     
    20581863                if (is_readable ( $realPathFilename )) {
    20591864                    try {
    2060                         // $reader = Reader::createFromPath($realPathFilename);
    2061                         // load the CSV document
    2062                         /*
    2063                          * $csv = Reader::createFromPath($realPathFilename)->addStreamFilter('convert.iconv.ISO-8859-1/UTF-8')->setDelimiter(';')->setHeaderOffset(0);
    2064                          * $results = $csv->fetchAll();
    2065                          */
     1865                   
    20661866                        $csv = Reader::createFromPath ( $realPathFilename );
    20671867                        // get the first row, usually the CSV header
     
    22002000                   
    22012001                    $numericValueToCatch = $this->tofloat ( $csvCell );
    2202                     /*
    2203                      * $valueToCatch = $csvCell;
    2204                      * $trimed = $this->clean($valueToCatch);
    2205                      * Logger::getLogger("default")->trace($valueToCatch . ' => ' . $trimed);
    2206                      * if (is_numeric($trimed)) {
    2207                      * $valueToCatch = $trimed; // str_replace (' ','',$values [$yCol]);
    2208                      * } else {
    2209                      * $valueToCatch = '"' . $this->removeQuotesAndConvertHtml($valueToCatch) . '"';
    2210                      * }
    2211                      */
     2002                   
    22122003                    self::getLogger ()->debug ( '*** Process ' . $csvRowKey . ' (' . $currentRowTitle . ') / ' . $csvColKey . ' (' . $colTitle . ') -> ' . $csvCell );
    22132004                   
    22142005                    $reportFields [0] ['datasets'] [$colTitle] ['data'] [$currentRowTitle] = $numericValueToCatch;
    2215                     // $reportFields [0] ['datasets'] ['label'] = $colTitle;
    2216                    
    2217                     /*
    2218                      * $reportFields [$id] ['datasets'] [$datasetNameLabel] ['data'] [$datasetValLabel] = $scoreValue;
    2219                      * $reportFields [$id] ['labels'] [] = $datasetValLabel;
    2220                      */
     2006           
    22212007                }
    22222008                $entriesProcessed ++;
     
    23062092                            $valueToCatch = $trimed; // str_replace (' ','',$values [$yCol]);
    23072093                        } else {
    2308                             /*
    2309                              * $idx ++;
    2310                              * continue;
    2311                              */
     2094                           
    23122095                            $valueToCatch = '"' . $this->removeQuotesAndConvertHtml ( $valueToCatch ) . '"';
    23132096                        }
Note: See TracChangeset for help on using the changeset viewer.