array( 'GSTIN/UIN of Recipient', 'Receiver Name', 'Invoice Number', 'Invoice date', 'Invoice Value', 'Place Of Supply', 'Reverse Charge', 'Applicable % of Tax Rate', 'Invoice Type', 'E-Commerce GSTIN', 'Rate', 'Taxable Value', 'Cess Amount' ), 'b2cl' => array( 'Invoice Number', 'Invoice date', 'Invoice Value', 'Place Of Supply', 'Applicable % of Tax Rate', 'Rate', 'Taxable Value', 'Cess Amount', 'E-Commerce GSTIN' ), 'b2cs' => array( 'Type', 'Place Of Supply', 'Applicable % of Tax Rate', 'Rate', 'Taxable Value', 'Cess Amount', 'E-Commerce GSTIN' ), 'hsn_b2b' => array( 'HSN', 'Description', 'UQC', 'Total Quantity', 'Total Value', 'Rate', 'Taxable Value', 'Integrated Tax Amount', 'Central Tax Amount', 'State/UT Tax Amount', 'Cess Amount' ), 'hsn_b2c' => array( 'HSN', 'Description', 'UQC', 'Total Quantity', 'Total Value', 'Rate', 'Taxable Value', 'Integrated Tax Amount', 'Central Tax Amount', 'State/UT Tax Amount', 'Cess Amount' ), ); /** Max HSN description length accepted by the offline tool. */ const HSN_DESCRIPTION_LIMIT = 30; /** * Wire hooks. */ public static function init() { add_action( 'admin_post_ebgi_gstr1_export', array( __CLASS__, 'handle_export' ) ); } /* --------------------------------------------------------------------- Pure builders */ /** * "27-Maharashtra". * * @param array $record Invoice record. * @return string */ public static function pos_label( array $record ) { return $record['computed']['place_of_supply_code'] . '-' . $record['computed']['place_of_supply_name']; } /** * Offline-tool date: dd-Mon-yy (e.g. 05-Oct-26). * * @param string $ymd Y-m-d. * @return string */ public static function format_date( $ymd ) { $ts = strtotime( $ymd . ' 00:00:00 UTC' ); return false === $ts ? '' : gmdate( 'd-M-y', $ts ); } /** * Money with exactly 2 decimals. * * @param float $n Amount. * @return string */ public static function money( $n ) { return number_format( EBGI_GSTIN_Validator::round_money( $n ), 2, '.', '' ); } /** * Taxable value per rate for one invoice. * * @param array $record Invoice record. * @return array slab => taxable */ private static function taxable_by_rate( array $record ) { $by = array(); foreach ( $record['computed']['lines'] as $line ) { $slab = (string) $line['slab']; $by[ $slab ] = ( isset( $by[ $slab ] ) ? $by[ $slab ] : 0 ) + EBGI_GSTIN_Validator::to_paise( $line['split']['taxable_amount'] ); } ksort( $by, SORT_NUMERIC ); foreach ( $by as $k => $v ) { $by[ $k ] = $v / 100; } return $by; } /** * Classify an invoice into a GSTR-1 section. * * @param array $record Invoice record. * @param float $threshold B2CL invoice value threshold. * @return string b2b | b2cl | b2cs | exp */ public static function classify( array $record, $threshold ) { if ( '' !== (string) $record['buyer']['gstin'] ) { return 'b2b'; } if ( EBGI_GSTIN_Validator::OTHER_COUNTRIES_CODE === $record['computed']['place_of_supply_code'] ) { return 'exp'; } if ( 'INTER' === $record['computed']['supply_type'] && (float) $record['computed']['grand_total'] > (float) $threshold ) { return 'b2cl'; } return 'b2cs'; } /** * Rows for one section. * * @param string $section b2b | b2cl | b2cs | hsn_b2b | hsn_b2c. * @param array $records Invoice records. * @param float $threshold B2CL threshold. * @return array */ public static function rows( $section, array $records, $threshold = 100000 ) { $rows = array(); $agg = array(); foreach ( $records as $r ) { $type = self::classify( $r, $threshold ); if ( 'b2b' === $section && 'b2b' === $type ) { $name = '' !== (string) $r['buyer']['legal_name'] ? $r['buyer']['legal_name'] : $r['buyer']['name']; foreach ( self::taxable_by_rate( $r ) as $slab => $taxable ) { $rows[] = array( $r['buyer']['gstin'], $name, $r['invoice_number'], self::format_date( $r['invoice_date'] ), self::money( $r['computed']['grand_total'] ), self::pos_label( $r ), 'N', '', 'Regular B2B', '', (string) $slab, self::money( $taxable ), '0.00' ); } } elseif ( 'b2cl' === $section && 'b2cl' === $type ) { foreach ( self::taxable_by_rate( $r ) as $slab => $taxable ) { $rows[] = array( $r['invoice_number'], self::format_date( $r['invoice_date'] ), self::money( $r['computed']['grand_total'] ), self::pos_label( $r ), '', (string) $slab, self::money( $taxable ), '0.00', '' ); } } elseif ( 'b2cs' === $section && 'b2cs' === $type ) { foreach ( self::taxable_by_rate( $r ) as $slab => $taxable ) { $key = self::pos_label( $r ) . '|' . $slab; if ( ! isset( $agg[ $key ] ) ) { $agg[ $key ] = array( self::pos_label( $r ), (string) $slab, 0 ); } $agg[ $key ][2] += EBGI_GSTIN_Validator::to_paise( $taxable ); } } elseif ( ( 'hsn_b2b' === $section && 'b2b' === $type ) || ( 'hsn_b2c' === $section && 'b2b' !== $type ) ) { foreach ( $r['computed']['lines'] as $line ) { $hsn = isset( $line['hsn'] ) ? (string) $line['hsn'] : ''; $uqc = isset( $line['uqc'] ) && '' !== $line['uqc'] ? (string) $line['uqc'] : 'NOS-NUMBERS'; $key = $hsn . '|' . $uqc . '|' . $line['slab']; if ( ! isset( $agg[ $key ] ) ) { $desc = isset( $line['name'] ) ? (string) $line['name'] : ''; $agg[ $key ] = array( 'hsn' => $hsn, 'desc' => function_exists( 'mb_substr' ) ? mb_substr( $desc, 0, self::HSN_DESCRIPTION_LIMIT ) : substr( $desc, 0, self::HSN_DESCRIPTION_LIMIT ), 'uqc' => $uqc, 'qty' => 0, 'val' => 0, 'rate' => (string) $line['slab'], 'tx' => 0, 'igst' => 0, 'cgst' => 0, 'sgst' => 0, ); } $sp = $line['split']; $agg[ $key ]['qty'] += (float) ( isset( $line['qty'] ) ? $line['qty'] : 0 ); $agg[ $key ]['val'] += EBGI_GSTIN_Validator::to_paise( $line['gross'] ); $agg[ $key ]['tx'] += EBGI_GSTIN_Validator::to_paise( $sp['taxable_amount'] ); $agg[ $key ]['igst'] += EBGI_GSTIN_Validator::to_paise( $sp['igst_amount'] ); $agg[ $key ]['cgst'] += EBGI_GSTIN_Validator::to_paise( $sp['cgst_amount'] ); $agg[ $key ]['sgst'] += EBGI_GSTIN_Validator::to_paise( $sp['sgst_amount'] ); } } } if ( 'b2cs' === $section ) { ksort( $agg ); foreach ( $agg as $a ) { $rows[] = array( 'OE', $a[0], '', $a[1], self::money( $a[2] / 100 ), '0.00', '' ); } } elseif ( 'hsn_b2b' === $section || 'hsn_b2c' === $section ) { ksort( $agg ); foreach ( $agg as $a ) { $rows[] = array( $a['hsn'], $a['desc'], $a['uqc'], rtrim( rtrim( number_format( $a['qty'], 3, '.', '' ), '0' ), '.' ), self::money( $a['val'] / 100 ), $a['rate'], self::money( $a['tx'] / 100 ), self::money( $a['igst'] / 100 ), self::money( $a['cgst'] / 100 ), self::money( $a['sgst'] / 100 ), '0.00' ); } } return $rows; } /** * Counts per section + data-quality warnings. * * @param array $records Invoice records. * @param float $threshold B2CL threshold. * @return array */ public static function summary( array $records, $threshold = 100000 ) { $out = array( 'invoices' => count( $records ), 'b2b' => 0, 'b2cl' => 0, 'b2cs' => 0, 'exp' => 0, 'missing_hsn' => 0, 'taxable' => 0, 'tax' => 0, ); foreach ( $records as $r ) { ++$out[ self::classify( $r, $threshold ) ]; $out['taxable'] += EBGI_GSTIN_Validator::to_paise( $r['computed']['total_taxable'] ); $out['tax'] += EBGI_GSTIN_Validator::to_paise( $r['computed']['total_tax'] ); foreach ( $r['computed']['lines'] as $line ) { if ( empty( $line['hsn'] ) ) { ++$out['missing_hsn']; } } } $out['taxable'] /= 100; $out['tax'] /= 100; return $out; } /** * RFC 4180 CSV with spreadsheet formula-injection protection. * * @param array $headers Header row. * @param array $rows Rows. * @return string */ public static function to_csv( array $headers, array $rows ) { $lines = array( self::csv_line( $headers ) ); foreach ( $rows as $row ) { $lines[] = self::csv_line( $row ); } return implode( "\r\n", $lines ) . "\r\n"; } /** * One CSV line. * * @param array $cells Cells. * @return string */ private static function csv_line( array $cells ) { $out = array(); foreach ( $cells as $cell ) { $cell = (string) $cell; if ( '' !== $cell && in_array( $cell[0], array( '=', '+', '-', '@' ), true ) && ! is_numeric( $cell ) ) { $cell = "'" . $cell; } if ( preg_match( '/[",\r\n]/', $cell ) ) { $cell = '"' . str_replace( '"', '""', $cell ) . '"'; } $out[] = $cell; } return implode( ',', $out ); } /* --------------------------------------------------------------------- WooCommerce adapter */ /** * Load invoice records for paid orders created in [from, to] (inclusive, store timezone). * * Read-only by default. Only the capability- and nonce-checked CSV export passes $assign_numbers. * * @param string $from Y-m-d. * @param string $to Y-m-d. * @param bool $assign_numbers Save an invoice number on orders that have none. * @return array */ public static function collect( $from, $to, $assign_numbers = false ) { $records = array(); $page = 1; do { $result = wc_get_orders( array( 'type' => 'shop_order', 'status' => EBGI_Invoice::ready_statuses(), 'date_created' => $from . '...' . $to, 'orderby' => 'date', 'order' => 'ASC', 'limit' => 100, 'page' => $page, 'paginate' => true, ) ); foreach ( $result->orders as $order ) { if ( $assign_numbers ) { EBGI_Invoice::ensure_number( $order ); } $records[] = EBGI_Invoice::get_data( $order ); } ++$page; } while ( $page <= (int) $result->max_num_pages ); return $records; } /** * Is this a real calendar month in Y-m format? * * @param string $month Month. * @return bool */ public static function is_valid_month( $month ) { return 1 === preg_match( '/^\d{4}-(0[1-9]|1[0-2])$/', (string) $month ); } /** * Parse the requested period. * * @param array $src Request array. * @return array array( from, to, label ) or empty array when invalid. */ public static function period_from_request( array $src ) { $month = isset( $src['ebgi_month'] ) ? sanitize_text_field( wp_unslash( $src['ebgi_month'] ) ) : ''; $from = isset( $src['ebgi_from'] ) ? sanitize_text_field( wp_unslash( $src['ebgi_from'] ) ) : ''; $to = isset( $src['ebgi_to'] ) ? sanitize_text_field( wp_unslash( $src['ebgi_to'] ) ) : ''; if ( self::is_valid_month( $month ) ) { $first = $month . '-01'; return array( $first, gmdate( 'Y-m-t', strtotime( $first . ' 00:00:00 UTC' ) ), str_replace( '-', '', $month ) ); } if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $from ) && preg_match( '/^\d{4}-\d{2}-\d{2}$/', $to ) && $from <= $to ) { return array( $from, $to, str_replace( '-', '', $from ) . '-' . str_replace( '-', '', $to ) ); } return array(); } /** * admin-post: stream one CSV section. */ public static function handle_export() { if ( ! current_user_can( 'manage_woocommerce' ) ) { wp_die( esc_html__( 'You are not allowed to do this.', '8-bit-gst-invoice-for-woocommerce' ), 403 ); } check_admin_referer( 'ebgi_gstr1_export' ); $section = isset( $_POST['ebgi_section'] ) ? sanitize_key( wp_unslash( $_POST['ebgi_section'] ) ) : ''; $period = self::period_from_request( array( 'ebgi_month' => isset( $_POST['ebgi_month'] ) ? sanitize_text_field( wp_unslash( $_POST['ebgi_month'] ) ) : '', 'ebgi_from' => isset( $_POST['ebgi_from'] ) ? sanitize_text_field( wp_unslash( $_POST['ebgi_from'] ) ) : '', 'ebgi_to' => isset( $_POST['ebgi_to'] ) ? sanitize_text_field( wp_unslash( $_POST['ebgi_to'] ) ) : '', ) ); if ( ! array_key_exists( $section, self::HEADERS ) || empty( $period ) ) { EBGI_Admin::redirect_with_notice( 'gstr1', __( 'Choose a valid month (or date range) and section.', '8-bit-gst-invoice-for-woocommerce' ), 'error' ); } $records = self::collect( $period[0], $period[1], true ); $csv = self::to_csv( self::HEADERS[ $section ], self::rows( $section, $records, (float) EBGI_Settings::get( 'b2cl_threshold' ) ) ); nocache_headers(); header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename="GSTR1-' . $section . '-' . $period[2] . '.csv"' ); echo $csv; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSV download, cells are sanitised in csv_line(). exit; } }