uc_reports.admin.inc 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  1. <?php
  2. /**
  3. * @file
  4. * Reports administration menu items.
  5. */
  6. /**
  7. * Displays the customer report.
  8. */
  9. function uc_reports_customers() {
  10. $address_preference = variable_get('uc_customer_list_address', 'billing');
  11. $first_name = ($address_preference == 'billing') ? 'billing_first_name' : 'delivery_first_name';
  12. $last_name = ($address_preference == 'billing') ? 'billing_last_name' : 'delivery_last_name';
  13. $page = isset($_GET['page']) ? intval($_GET['page']) : 0;
  14. $page_size = isset($_GET['nopage']) ? UC_REPORTS_MAX_RECORDS : variable_get('uc_reports_table_size', 30);
  15. $order_statuses = uc_reports_order_statuses();
  16. $rows = array();
  17. $csv_rows = array();
  18. $header = array(
  19. array('data' => t('#')),
  20. array('data' => t('Customer'), 'field' => "ou.$last_name"),
  21. array('data' => t('Username'), 'field' => "u.name"),
  22. array('data' => t('Orders'), 'field' => 'orders'),
  23. array('data' => t('Products'), 'field' => 'products'),
  24. array('data' => t('Total'), 'field' => 'total', 'sort' => 'desc'),
  25. array('data' => t('Average'), 'field' => 'average'),
  26. );
  27. $csv_rows[] = array(t('#'), t('Customer'), t('Username'), t('Orders'), t('Products'), t('Total'), t('Average'));
  28. $query = db_select('users', 'u', array('fetch' => PDO::FETCH_ASSOC))->extend('PagerDefault')->extend('TableSort');
  29. $query->leftJoin('uc_orders', 'ou', 'u.uid = ou.uid');
  30. $query->fields('u', array(
  31. 'uid',
  32. 'name',
  33. ))
  34. ->fields('ou', array(
  35. $first_name,
  36. $last_name,
  37. ))
  38. ->condition('u.uid', 0, '>')
  39. ->groupBy('u.uid');
  40. $query->addExpression("(SELECT COUNT(DISTINCT(order_id)) FROM {uc_orders} o WHERE o.uid = u.uid AND o.order_status IN (:statuses))", 'orders', array(':statuses' => $order_statuses));
  41. $query->addExpression("(SELECT SUM(qty) FROM {uc_order_products} ps LEFT JOIN {uc_orders} os ON ps.order_id = os.order_id WHERE os.order_status IN (:statuses2) AND os.uid = u.uid)", 'products', array(':statuses2' => $order_statuses));
  42. $query->addExpression("(SELECT SUM(ot.order_total) FROM {uc_orders} ot WHERE ot.uid = u.uid AND ot.order_status IN (:statuses3))", 'total', array(':statuses3' => $order_statuses));
  43. $query->addExpression("ROUND((SELECT SUM(ot.order_total) FROM {uc_orders} ot WHERE ot.uid = u.uid AND ot.order_status IN (:sum_statuses))/(SELECT COUNT(DISTINCT(order_id)) FROM {uc_orders} o WHERE o.uid = u.uid AND o.order_status IN (:count_statuses)), 2)", 'average', array(':sum_statuses' => $order_statuses, ':count_statuses' => $order_statuses));
  44. $count_query = db_select('users', 'u');
  45. $count_query->leftJoin('uc_orders', 'ou', 'u.uid = ou.uid');
  46. $count_query->addExpression('COUNT(DISTINCT u.uid)');
  47. $count_query->condition('u.uid', 0, '>');
  48. $query->setCountQuery($count_query);
  49. $query->groupBy('u.uid')
  50. ->groupBy('u.name')
  51. ->groupBy("ou.$first_name")
  52. ->groupBy("ou.$last_name")
  53. ->orderByHeader($header)
  54. ->limit($page_size);
  55. $customers = $query->execute();
  56. foreach ($customers as $customer) {
  57. $name = (!empty($customer[$last_name]) || !empty($customer[$first_name])) ? l($customer[$last_name] . ', ' . $customer[$first_name], 'admin/store/customers/orders/' . $customer['uid']) : l($customer['name'], 'admin/store/customers/orders/' . $customer['uid']);
  58. $customer_number = ($page * variable_get('uc_reports_table_size', 30)) + (count($rows) + 1);
  59. $customer_order_name = (!empty($customer[$last_name]) || !empty($customer[$first_name])) ? $customer[$last_name] . ', ' . $customer[$first_name] : $customer['name'];
  60. $customer_name = $customer['name'];
  61. $orders = !empty($customer['orders']) ? $customer['orders'] : 0;
  62. $products = !empty($customer['products']) ? $customer['products'] : 0;
  63. $total_revenue = uc_currency_format($customer['total']);
  64. $average_revenue = uc_currency_format($customer['average']);
  65. $rows[] = array(
  66. array('data' => $customer_number),
  67. array('data' => $name),
  68. array('data' => l($customer_name, 'user/' . $customer['uid'])),
  69. array('data' => $orders),
  70. array('data' => $products),
  71. array('data' => $total_revenue),
  72. array('data' => $average_revenue),
  73. );
  74. $csv_rows[] = array($customer_number, $customer_order_name, $customer_name, $orders, $products, $customer['total'], $customer['average']);
  75. }
  76. $csv_data = uc_reports_store_csv('uc_customers', $csv_rows);
  77. $build['report'] = array(
  78. '#theme' => 'table',
  79. '#header' => $header,
  80. '#rows' => $rows,
  81. '#attributes' => array('width' => '100%', 'class' => array('uc-sales-table')),
  82. '#empty' => t('No customers found'),
  83. );
  84. $build['pager'] = array(
  85. '#theme' => 'pager',
  86. );
  87. $build['links'] = array(
  88. '#prefix' => '<div class="uc-reports-links">',
  89. '#suffix' => '</div>',
  90. );
  91. $build['links']['export_csv'] = array(
  92. '#markup' => l(t('Export to CSV file.'), 'admin/store/reports/getcsv/' . $csv_data['report'] . '/' . $csv_data['user']),
  93. '#suffix' => '&nbsp;&nbsp;&nbsp;',
  94. );
  95. if (isset($_GET['nopage'])) {
  96. $build['links']['toggle_pager'] = array(
  97. '#markup' => l(t('Show paged records'), 'admin/store/reports/customers'),
  98. );
  99. }
  100. else {
  101. $build['links']['toggle_pager'] = array(
  102. '#markup' => l(t('Show all records'), 'admin/store/reports/customers', array('query' => array('nopage' => '1'))),
  103. );
  104. }
  105. return $build;
  106. }
  107. /**
  108. * Displays the product reports.
  109. */
  110. function uc_reports_products() {
  111. $views_column = module_exists('statistics') && variable_get('statistics_count_content_views', FALSE);
  112. $page = isset($_GET['page']) ? intval($_GET['page']) : 0;
  113. $page_size = isset($_GET['nopage']) ? UC_REPORTS_MAX_RECORDS : variable_get('uc_reports_table_size', 30);
  114. $order_statuses = uc_reports_order_statuses();
  115. $row_cell = $page * variable_get('uc_reports_table_size', 30) + 1;
  116. $rows = array();
  117. $csv_rows = array();
  118. // Hard code the ignore of the product kit for this report.
  119. $ignored_types = array('product_kit');
  120. // Build an array of valid product types to include on the report.
  121. $product_types = array();
  122. foreach (uc_product_types() as $type) {
  123. // Pass over any ignored types.
  124. if (!in_array($type, $ignored_types)) {
  125. $product_types[] = $type;
  126. }
  127. }
  128. $query = db_select('node', 'n', array('fetch' => PDO::FETCH_ASSOC))
  129. ->extend('PagerDefault')
  130. ->extend('TableSort')
  131. ->limit($page_size);
  132. $query->addField('n', 'nid');
  133. $query->addField('n', 'title');
  134. $query->addExpression("(SELECT SUM(uop.qty) FROM {uc_order_products} uop LEFT JOIN {uc_orders} uo ON uop.order_id = uo.order_id WHERE uo.order_status IN (:statuses) AND uop.nid = n.nid)", 'sold', array(':statuses' => $order_statuses));
  135. $query->addExpression("(SELECT (SUM(uop.price * uop.qty) - SUM(uop.cost * uop.qty)) FROM {uc_order_products} uop LEFT JOIN {uc_orders} uo ON uop.order_id = uo.order_id WHERE uo.order_status IN (:statuses2) AND uop.nid = n.nid)", 'gross', array(':statuses2' => $order_statuses));
  136. $query->addExpression("(SELECT (SUM(uop.price * uop.qty)) FROM {uc_order_products} uop LEFT JOIN {uc_orders} uo ON uop.order_id = uo.order_id WHERE uo.order_status IN (:statuses3) AND uop.nid = n.nid)", 'revenue', array(':statuses3' => $order_statuses));
  137. $header = array(
  138. array('data' => t('#')),
  139. array('data' => t('Product'), 'field' => 'n.title'),
  140. array('data' => t('Sold'), 'field' => 'sold'),
  141. array('data' => t('Revenue'), 'field' => 'revenue', 'sort' => 'desc'),
  142. array('data' => t('Gross'), 'field' => 'gross'),
  143. );
  144. $csv_rows[] = array(t('#'), t('Product'), t('Sold'), t('Revenue'), t('Gross'));
  145. if ($views_column) {
  146. $header[] = array('data' => t('Views'), 'field' => 'nc.totalcount');
  147. $csv_rows[0][] = t('Views');
  148. }
  149. $query->orderByHeader($header);
  150. if ($views_column) {
  151. $query->leftJoin('node_counter', 'nc', 'n.nid = nc.nid');
  152. $query->addField('nc', 'totalcount');
  153. }
  154. $query->condition('n.type', $product_types, 'IN')
  155. ->groupBy('n.nid')
  156. ->groupBy('n.title');
  157. $products = $query->execute();
  158. foreach ($products as $product) {
  159. $product_cell = l($product['title'], 'node/' . $product['nid']);
  160. $product_csv = $product['title'];
  161. $sold_cell = empty($product['sold']) ? 0 : $product['sold'];
  162. $sold_csv = $sold_cell;
  163. $revenue_csv = empty($product['revenue']) ? 0 : $product['revenue'];
  164. $revenue_cell = uc_currency_format($revenue_csv);
  165. $gross_csv = empty($product['gross']) ? 0 : $product['gross'];
  166. $gross_cell = uc_currency_format($gross_csv);
  167. $row = array(
  168. 'data' => array(
  169. $row_cell,
  170. $product_cell,
  171. "<strong>$sold_cell</strong>",
  172. "<strong>$revenue_cell</strong>",
  173. "<strong>$gross_cell</strong>",
  174. ),
  175. 'primary' => TRUE,
  176. );
  177. $csv_row = array($row_cell, $product_csv, $sold_csv, $revenue_csv, $gross_csv);
  178. if ($views_column) {
  179. $views = isset($product['totalcount']) ? $product['totalcount'] : 0;
  180. $row['data'][] = $views;
  181. $csv_row[] = $views;
  182. }
  183. $rows[] = $row;
  184. $csv_rows[] = $csv_row;
  185. if (module_exists('uc_attribute')) {
  186. // Get the SKUs from this product.
  187. $models = uc_reports_product_get_skus($product['nid']);
  188. // Add the product breakdown rows
  189. foreach ($models as $model) {
  190. $sold = db_query("SELECT SUM(qty) FROM {uc_order_products} p LEFT JOIN {uc_orders} o ON p.order_id = o.order_id WHERE o.order_status IN (:statuses) AND p.model = :model AND p.nid = :nid", array(':statuses' => $order_statuses, ':model' => $model, ':nid' => $product['nid']))->fetchField();
  191. $revenue = db_query("SELECT SUM(p.price * p.qty) FROM {uc_order_products} p LEFT JOIN {uc_orders} o ON p.order_id = o.order_id WHERE o.order_status IN (:statuses) AND p.model = :model AND p.nid = :nid", array(':statuses' => $order_statuses, ':model' => $model, ':nid' => $product['nid']))->fetchField();
  192. $gross = db_query("SELECT (SUM(p.price * p.qty) - SUM(p.cost * p.qty)) FROM {uc_order_products} p LEFT JOIN {uc_orders} o ON p.order_id = o.order_id WHERE o.order_status IN (:statuses) AND p.model = :model AND p.nid = :nid", array(':statuses' => $order_statuses, ':model' => $model, ':nid' => $product['nid']))->fetchField();
  193. $breakdown_product = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$model";
  194. $product_csv = " $model";
  195. $sold_csv = !empty($sold) ? $sold : 0;
  196. $breakdown_sold = $sold_csv;
  197. $revenue_csv = !empty($revenue) ? $revenue : 0;
  198. $breakdown_revenue = theme('uc_price', array('price' => $revenue_csv));
  199. $gross_csv = !empty($gross) ? $gross : 0;
  200. $breakdown_gross = theme('uc_price', array('price' => $gross_csv));
  201. $row = array(
  202. 'data' => array(
  203. '',
  204. $breakdown_product,
  205. $breakdown_sold,
  206. $breakdown_revenue,
  207. $breakdown_gross,
  208. ),
  209. );
  210. $csv_row = array('', $product_csv, $sold_csv, $revenue_csv, $gross_csv);
  211. if ($views_column) {
  212. $row['data'][] = '';
  213. $csv_row[] = '';
  214. }
  215. $rows[] = $row;
  216. $csv_rows[] = $csv_row;
  217. }
  218. }
  219. $row_cell++;
  220. }
  221. $csv_data = uc_reports_store_csv('uc_products', $csv_rows);
  222. $build['report'] = array(
  223. '#theme' => 'uc_reports_product_table',
  224. '#header' => $header,
  225. '#rows' => $rows,
  226. '#attributes' => array('width' => '100%', 'class' => array('uc-sales-table')),
  227. '#empty' => t('No products found'),
  228. );
  229. $build['pager'] = array(
  230. '#theme' => 'pager',
  231. );
  232. $build['links'] = array(
  233. '#prefix' => '<div class="uc-reports-links">',
  234. '#suffix' => '</div>',
  235. );
  236. $build['links']['export_csv'] = array(
  237. '#markup' => l(t('Export to CSV file.'), 'admin/store/reports/getcsv/' . $csv_data['report'] . '/' . $csv_data['user']),
  238. '#suffix' => '&nbsp;&nbsp;&nbsp;',
  239. );
  240. if (isset($_GET['nopage'])) {
  241. $build['links']['toggle_pager'] = array(
  242. '#markup' => l(t('Show paged records'), 'admin/store/reports/products'),
  243. );
  244. }
  245. else {
  246. $build['links']['toggle_pager'] = array(
  247. '#markup' => l(t('Show all records'), 'admin/store/reports/products', array('query' => array('nopage' => '1'))),
  248. );
  249. }
  250. $build['instructions'] = array('#markup' => '<small>*' . t('Make sure %setting_name is set to %state in the <a href="!url">access log settings page</a> to enable views column.', array('%setting_name' => 'count content views', '%state' => 'enabled', '!url' => url('admin/config/system/statistics', array('query' => array('destination' => 'admin/store/reports/products'))))) . '</small>');
  251. return $build;
  252. }
  253. /**
  254. * Gets the SKUs on a product, including adjustments and past orders.
  255. *
  256. * @param $nid
  257. * The product's node ID.
  258. *
  259. * @return
  260. * A unique sorted array of all skus.
  261. */
  262. function uc_reports_product_get_skus($nid) {
  263. // Product SKU.
  264. $models = array(db_query("SELECT model FROM {uc_products} WHERE nid = :nid", array(':nid' => $nid))->fetchField());
  265. // Adjustment SKUs.
  266. $models = array_merge($models, db_query("SELECT model FROM {uc_product_adjustments} WHERE nid = :nid", array(':nid' => $nid))->fetchCol());
  267. // SKUs from orders.
  268. $models = array_merge($models, db_query("SELECT DISTINCT model FROM {uc_order_products} WHERE nid = :nid", array(':nid' => $nid))->fetchCol());
  269. // Unique, sorted.
  270. $models = array_unique($models);
  271. asort($models);
  272. return $models;
  273. }
  274. /**
  275. * Displays the custom product report.
  276. */
  277. function uc_reports_products_custom() {
  278. $views_column = module_exists('statistics') && variable_get('statistics_count_content_views', FALSE);
  279. $page = isset($_GET['page']) ? intval($_GET['page']) : 0;
  280. $page_size = isset($_GET['nopage']) ? UC_REPORTS_MAX_RECORDS : variable_get('uc_reports_table_size', 30);
  281. $rows = array();
  282. $csv_rows = array();
  283. // Hard code the ignore of the product kit for this report.
  284. $ignored_types = array('product_kit');
  285. // Build an array of valid product types to include on the report.
  286. $product_types = array();
  287. foreach (uc_product_types() as $type) {
  288. // Pass over any ignored types.
  289. if (!in_array($type, $ignored_types)) {
  290. $product_types[] = $type;
  291. }
  292. }
  293. // Use default report parameters if we don't detect values in the URL.
  294. if (arg(5) == '') {
  295. $args = array(
  296. 'start_date' => mktime(0, 0, 0, date('n'), 1, date('Y') - 1),
  297. 'end_date' => REQUEST_TIME,
  298. 'status' => uc_reports_order_statuses(),
  299. );
  300. }
  301. else {
  302. $args = array(
  303. 'start_date' => arg(5),
  304. 'end_date' => arg(6),
  305. 'status' => explode(',', arg(7)),
  306. );
  307. }
  308. $query = db_select('node', 'n', array('fetch' => PDO::FETCH_ASSOC))
  309. ->extend('PagerDefault')
  310. ->extend('TableSort')
  311. ->limit($page_size)
  312. ->fields('n', array(
  313. 'nid',
  314. 'title',
  315. ))
  316. ->condition('type', $product_types, 'IN')
  317. ->groupBy('n.nid');
  318. $query->addExpression("(SELECT SUM(qty) FROM {uc_order_products} p LEFT JOIN {uc_orders} o ON p.order_id = o.order_id WHERE o.order_status IN (:statuses) AND p.nid = n.nid AND o.created >= :start AND o.created <= :end)", 'sold', array(':statuses' => $args['status'], ':start' => $args['start_date'], ':end' => $args['end_date']));
  319. $query->addExpression("(SELECT (SUM(p2.price * p2.qty)) FROM {uc_order_products} p2 LEFT JOIN {uc_orders} o ON p2.order_id = o.order_id WHERE o.order_status IN (:statuses) AND p2.nid = n.nid AND o.created >= :start AND o.created <= :end)", 'revenue', array(':statuses' => $args['status'], ':start' => $args['start_date'], ':end' => $args['end_date']));
  320. $query->addExpression("(SELECT (SUM(p3.price * p3.qty) - SUM(p3.cost * p3.qty)) FROM {uc_order_products} p3 LEFT JOIN {uc_orders} o ON p3.order_id = o.order_id WHERE o.order_status IN (:statuses) AND p3.nid = n.nid AND o.created >= :start AND o.created <= :end)", 'gross', array(':statuses' => $args['status'], ':start' => $args['start_date'], ':end' => $args['end_date']));
  321. $header = array(
  322. array('data' => t('#')),
  323. array('data' => t('Product'), 'field' => 'n.title'),
  324. array('data' => t('Sold'), 'field' => 'sold'),
  325. array('data' => t('Revenue'), 'field' => 'revenue', 'sort' => 'desc'),
  326. array('data' => t('Gross'), 'field' => 'gross'),
  327. );
  328. $csv_rows[] = array(t('#'), t('Product'), t('Sold'), t('Revenue'), t('Gross'));
  329. if ($views_column) {
  330. $header[] = array('data' => t('Views'), 'field' => 'nc.totalcount');
  331. $csv_rows[0][] = t('Views');
  332. }
  333. $query->orderByHeader($header);
  334. if ($views_column) {
  335. $query->leftJoin('node_counter', 'c', 'n.nid = c.nid');
  336. $query->addField('c', 'totalcount');
  337. }
  338. $products = $query->execute();
  339. foreach ($products as $product) {
  340. $row_cell = ($page * variable_get('uc_reports_table_size', 30)) + count($rows) + 1;
  341. $product_cell = l($product['title'], 'node/' . $product['nid']);
  342. $product_csv = $product['title'];
  343. $sold_cell = empty($product['sold']) ? 0 : $product['sold'];
  344. $sold_csv = $sold_cell;
  345. $revenue_csv = empty($product['revenue']) ? 0 : $product['revenue'];
  346. $revenue_cell = uc_currency_format($revenue_csv);
  347. $gross_csv = empty($product['gross']) ? 0 : $product['gross'];
  348. $gross_cell = uc_currency_format($gross_csv);
  349. if (module_exists('uc_attribute')) {
  350. $breakdown_product = $breakdown_sold = $breakdown_revenue = $breakdown_gross = '';
  351. // Get the SKUs from this product.
  352. $models = uc_reports_product_get_skus($product['nid']);
  353. // Add the product breakdown rows
  354. foreach ($models as $model) {
  355. $sold = db_query("SELECT SUM(qty) FROM {uc_order_products} p LEFT JOIN {uc_orders} o ON p.order_id = o.order_id WHERE o.order_status IN (:statuses) AND p.model = :model AND p.nid = :nid AND o.created >= :start AND o.created <= :end", array(':statuses' => $args['status'], ':start' => $args['start_date'], ':end' => $args['end_date'], ':model' => $model, ':nid' => $product['nid']))->fetchField();
  356. $sold = empty($sold) ? 0 : $sold;
  357. $revenue = db_query("SELECT SUM(p.price * p.qty) FROM {uc_order_products} p LEFT JOIN {uc_orders} o ON p.order_id = o.order_id WHERE o.order_status IN (:statuses) AND p.model = :model AND p.nid = :nid AND o.created >= :start AND o.created <= :end", array(':statuses' => $args['status'], ':start' => $args['start_date'], ':end' => $args['end_date'], ':model' => $model, ':nid' => $product['nid']))->fetchField();
  358. $revenue = empty($revenue) ? 0 : $revenue;
  359. $gross = db_query("SELECT (SUM(p.price * p.qty) - SUM(p.cost * p.qty)) FROM {uc_order_products} p LEFT JOIN {uc_orders} o ON p.order_id = o.order_id WHERE o.order_status IN (:statuses) AND p.model = :model AND p.nid = :nid AND o.created >= :start AND o.created <= :end", array(':statuses' => $args['status'], ':start' => $args['start_date'], ':end' => $args['end_date'], ':model' => $model, ':nid' => $product['nid']))->fetchField();
  360. $gross = empty($gross) ? 0 : $gross;
  361. $breakdown_product .= "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$model";
  362. $product_csv .= "\n $model";
  363. $breakdown_sold .= "<br />" . $sold;
  364. $sold_csv .= "\n " . $sold;
  365. $breakdown_revenue .= "<br />" . uc_currency_format($revenue);
  366. $revenue_csv .= "\n " . $revenue;
  367. $breakdown_gross .= "<br />" . uc_currency_format($gross);
  368. $gross_csv .= "\n " . $gross;
  369. }
  370. $product_cell = $product_cell . $breakdown_product;
  371. $sold_cell = '<strong>' . $sold_cell . '</strong>' . $breakdown_sold;
  372. $revenue_cell = '<strong>' . $revenue_cell . '</strong>' . $breakdown_revenue;
  373. $gross_cell = '<strong>' . $gross_cell . '</strong>' . $breakdown_gross;
  374. }
  375. if ($views_column) {
  376. $views = empty($product['totalcount']) ? 0 : $product['totalcount'];
  377. $rows[] = array(
  378. array('data' => $row_cell),
  379. array('data' => $product_cell),
  380. array('data' => $sold_cell),
  381. array('data' => $revenue_cell),
  382. array('data' => $gross_cell),
  383. array('data' => $views),
  384. );
  385. $csv_rows[] = array($row_cell, $product_csv, $sold_csv, $revenue_csv, $gross_csv, $views);
  386. }
  387. else {
  388. $rows[] = array(
  389. array('data' => $row_cell),
  390. array('data' => $product_cell),
  391. array('data' => $sold_cell),
  392. array('data' => $revenue_cell),
  393. array('data' => $gross_cell),
  394. );
  395. $csv_rows[] = array($row_cell, $product_csv, $sold_csv, $revenue_csv, $gross_csv);
  396. }
  397. }
  398. $csv_data = uc_reports_store_csv('uc_products', $csv_rows);
  399. // Build the page output holding the form, table, and CSV export link.
  400. $build['form'] = drupal_get_form('uc_reports_products_custom_form', $args);
  401. $build['report'] = array(
  402. '#theme' => 'table',
  403. '#header' => $header,
  404. '#rows' => $rows,
  405. '#attributes' => array('width' => '100%', 'class' => array('uc-sales-table')),
  406. '#empty' => t('No products found'),
  407. );
  408. $build['pager'] = array(
  409. '#theme' => 'pager',
  410. );
  411. $build['links'] = array(
  412. '#prefix' => '<div class="uc-reports-links">',
  413. '#suffix' => '</div>',
  414. );
  415. $build['links']['export_csv'] = array(
  416. '#markup' => l(t('Export to CSV file.'), 'admin/store/reports/getcsv/' . $csv_data['report'] . '/' . $csv_data['user']),
  417. '#suffix' => '&nbsp;&nbsp;&nbsp;',
  418. );
  419. $filters = str_replace('admin/store/reports/products/custom', '', current_path());
  420. if (isset($_GET['nopage'])) {
  421. $build['links']['toggle_pager'] = array(
  422. '#markup' => l(t('Show paged records'), 'admin/store/reports/products/custom' . $filters),
  423. );
  424. }
  425. else {
  426. $build['links']['toggle_pager'] = array(
  427. '#markup' => l(t('Show all records'), 'admin/store/reports/products/custom' . $filters, array('query' => array('nopage' => '1'))),
  428. );
  429. }
  430. $build['instructions'] = array('#markup' => '<small>*' . t('Make sure %setting_name is set to %state in the <a href="!url">access log settings page</a> to enable views column.', array('%setting_name' => 'count content views', '%state' => 'enabled', '!url' => url('admin/config/system/statistics', array('query' => array('destination' => 'admin/store/reports/products/custom'))))) . '</small>');
  431. return $build;
  432. }
  433. /**
  434. * Form builder for the custom product report.
  435. *
  436. * @see uc_reports_products_custom_form_validate()
  437. * @see uc_reports_products_custom_form_submit()
  438. * @ingroup forms
  439. */
  440. function uc_reports_products_custom_form($form, &$form_state, $values) {
  441. $form['search'] = array(
  442. '#type' => 'fieldset',
  443. '#title' => t('Customize product report parameters'),
  444. '#description' => t('Adjust these values and update the report to build your custom product report. Once submitted, the report may be bookmarked for easy reference in the future.'),
  445. '#collapsible' => TRUE,
  446. '#collapsed' => TRUE,
  447. );
  448. $form['search']['start_date'] = array(
  449. '#type' => 'date',
  450. '#title' => t('Start date'),
  451. '#default_value' => array(
  452. 'month' => format_date($values['start_date'], 'custom', 'n'),
  453. 'day' => format_date($values['start_date'], 'custom', 'j'),
  454. 'year' => format_date($values['start_date'], 'custom', 'Y'),
  455. ),
  456. );
  457. $form['search']['end_date'] = array(
  458. '#type' => 'date',
  459. '#title' => t('End date'),
  460. '#default_value' => array(
  461. 'month' => format_date($values['end_date'], 'custom', 'n'),
  462. 'day' => format_date($values['end_date'], 'custom', 'j'),
  463. 'year' => format_date($values['end_date'], 'custom', 'Y'),
  464. ),
  465. );
  466. $options = array();
  467. foreach (uc_order_status_list() as $status) {
  468. $options[$status['id']] = $status['title'];
  469. }
  470. $form['search']['status'] = array(
  471. '#type' => 'checkboxes',
  472. '#title' => t('Order statuses'),
  473. '#description' => t('Only orders with selected statuses will be included in the report.'),
  474. '#options' => $options,
  475. '#default_value' => $values['status'],
  476. );
  477. $form['search']['actions'] = array('#type' => 'actions');
  478. $form['search']['actions']['submit'] = array(
  479. '#type' => 'submit',
  480. '#value' => t('Update report'),
  481. );
  482. return $form;
  483. }
  484. /**
  485. * Validation handler for the custom product report.
  486. *
  487. * @see uc_reports_products_custom_form()
  488. * @see uc_reports_products_custom_form_submit()
  489. */
  490. function uc_reports_products_custom_form_validate($form, &$form_state) {
  491. if (empty($form_state['values']['status'])) {
  492. form_set_error('status', t('You must select at least one order status.'));
  493. }
  494. }
  495. /**
  496. * Submission handler for the custom product report.
  497. *
  498. * @see uc_reports_products_custom_form()
  499. * @see uc_reports_products_custom_form_submit()
  500. */
  501. function uc_reports_products_custom_form_submit($form, &$form_state) {
  502. $start_date = mktime(0, 0, 0, $form_state['values']['start_date']['month'], $form_state['values']['start_date']['day'], $form_state['values']['start_date']['year']);
  503. $end_date = mktime(23, 59, 59, $form_state['values']['end_date']['month'], $form_state['values']['end_date']['day'], $form_state['values']['end_date']['year']);
  504. $args = array(
  505. $start_date,
  506. $end_date,
  507. implode(',', array_keys(array_filter($form_state['values']['status']))),
  508. );
  509. $form_state['redirect'] = array('admin/store/reports/products/custom/' . implode('/', $args));
  510. }
  511. /**
  512. * Return a themed table for product reports.
  513. *
  514. * Straight duplication of theme_table, but our row handling is different.
  515. *
  516. * @see theme_table()
  517. * @ingroup themeable
  518. */
  519. function theme_uc_reports_product_table($variables) {
  520. $header = $variables['header'];
  521. $rows = $variables['rows'];
  522. $attributes = $variables['attributes'];
  523. $caption = $variables['caption'];
  524. $colgroups = $variables['colgroups'];
  525. $sticky = $variables['sticky'];
  526. $empty = $variables['empty'];
  527. // Add sticky headers, if applicable.
  528. if (count($header) && $sticky) {
  529. drupal_add_js('misc/tableheader.js');
  530. // Add 'sticky-enabled' class to the table to identify it for JS.
  531. // This is needed to target tables constructed by this function.
  532. $attributes['class'][] = 'sticky-enabled';
  533. }
  534. $output = '<table' . drupal_attributes($attributes) . ">\n";
  535. if (isset($caption)) {
  536. $output .= '<caption>' . $caption . "</caption>\n";
  537. }
  538. // Format the table columns:
  539. if (count($colgroups)) {
  540. foreach ($colgroups as $number => $colgroup) {
  541. $attributes = array();
  542. // Check if we're dealing with a simple or complex column
  543. if (isset($colgroup['data'])) {
  544. foreach ($colgroup as $key => $value) {
  545. if ($key == 'data') {
  546. $cols = $value;
  547. }
  548. else {
  549. $attributes[$key] = $value;
  550. }
  551. }
  552. }
  553. else {
  554. $cols = $colgroup;
  555. }
  556. // Build colgroup
  557. if (is_array($cols) && count($cols)) {
  558. $output .= ' <colgroup' . drupal_attributes($attributes) . '>';
  559. $i = 0;
  560. foreach ($cols as $col) {
  561. $output .= ' <col' . drupal_attributes($col) . ' />';
  562. }
  563. $output .= " </colgroup>\n";
  564. }
  565. else {
  566. $output .= ' <colgroup' . drupal_attributes($attributes) . " />\n";
  567. }
  568. }
  569. }
  570. // Add the 'empty' row message if available.
  571. if (!count($rows) && $empty) {
  572. $header_count = 0;
  573. foreach ($header as $header_cell) {
  574. if (is_array($header_cell)) {
  575. $header_count += isset($header_cell['colspan']) ? $header_cell['colspan'] : 1;
  576. }
  577. else {
  578. $header_count++;
  579. }
  580. }
  581. $rows[] = array(array('data' => $empty, 'colspan' => $header_count, 'class' => array('empty', 'message')));
  582. }
  583. // Format the table header:
  584. if (count($header)) {
  585. $ts = tablesort_init($header);
  586. // HTML requires that the thead tag has tr tags in it follwed by tbody
  587. // tags. Using ternary operator to check and see if we have any rows.
  588. $output .= (count($rows) ? ' <thead><tr>' : ' <tr>');
  589. foreach ($header as $cell) {
  590. $cell = tablesort_header($cell, $header, $ts);
  591. $output .= _theme_table_cell($cell, TRUE);
  592. }
  593. // Using ternary operator to close the tags based on whether or not there are rows
  594. $output .= (count($rows) ? " </tr></thead>\n" : "</tr>\n");
  595. }
  596. else {
  597. $ts = array();
  598. }
  599. // Format the table rows:
  600. if (count($rows)) {
  601. $output .= "<tbody>\n";
  602. $flip = array('even' => 'odd', 'odd' => 'even');
  603. $class = 'even';
  604. foreach ($rows as $number => $row) {
  605. $attributes = array();
  606. // Check if we're dealing with a simple or complex row
  607. if (isset($row['data'])) {
  608. foreach ($row as $key => $value) {
  609. if ($key == 'data') {
  610. $cells = $value;
  611. }
  612. // The following elseif clause is where we differ from theme_table()
  613. elseif ($key == 'primary') {
  614. $class = $flip[$class];
  615. }
  616. else {
  617. $attributes[$key] = $value;
  618. }
  619. }
  620. }
  621. else {
  622. $cells = $row;
  623. }
  624. if (count($cells)) {
  625. // Add odd/even class
  626. // We don't flip here like theme_table(), because we did that above.
  627. $attributes['class'][] = $class;
  628. // Build row
  629. $output .= ' <tr' . drupal_attributes($attributes) . '>';
  630. $i = 0;
  631. foreach ($cells as $cell) {
  632. $cell = tablesort_cell($cell, $header, $ts, $i++);
  633. $output .= _theme_table_cell($cell);
  634. }
  635. $output .= " </tr>\n";
  636. }
  637. }
  638. $output .= "</tbody>\n";
  639. }
  640. $output .= "</table>\n";
  641. return $output;
  642. }
  643. /**
  644. * Displays the sales summary report.
  645. */
  646. function uc_reports_sales_summary() {
  647. $order_statuses = uc_reports_order_statuses();
  648. $date_day_of_month = date('j');
  649. $date_month = date('n');
  650. $month_start = mktime(0, 0, 0, $date_month, 1);
  651. $month_end = mktime(0, 0, 0, $date_month + 1, 1) - 1;
  652. $today_start = mktime(0, 0, 0);
  653. $today_end = mktime(23, 59, 59);
  654. // Build the report table header.
  655. $header = array(t('Sales data'), t('Number of orders'), t('Total revenue'), t('Average order'));
  656. // Calculate and add today's sales summary to the report table.
  657. $today = uc_reports_get_sales($today_start);
  658. $rows[] = array(
  659. l(t('Today, !date', array('!date' => format_date($today_start, 'uc_store'))), 'admin/store/orders/search/results/0/0/0/0/0/0/' . $today_start . '/' . $today_end),
  660. $today['total'],
  661. array('data' => array('#theme' => 'uc_price', '#price' => $today['income'])),
  662. array('data' => array('#theme' => 'uc_price', '#price' => $today['average'])),
  663. );
  664. // Calculate and add yesterday's sales summary to the report table.
  665. $yesterday = uc_reports_get_sales($today_start - 86400);
  666. $rows[] = array(
  667. l(t('Yesterday, !date', array('!date' => format_date($today_start - 86400, 'uc_store'))), 'admin/store/orders/search/results/0/0/0/0/0/0/' . ($today_start - 86400) . '/' . ($today_end - 86400)),
  668. $yesterday['total'],
  669. array('data' => array('#theme' => 'uc_price', '#price' => $yesterday['income'])),
  670. array('data' => array('#theme' => 'uc_price', '#price' => $yesterday['average'])),
  671. );
  672. // Get the sales report for the month.
  673. $month = uc_reports_get_sales($month_start, 'month');
  674. $month_title = format_date($month_start, 'custom', 'M Y');
  675. // Add the month-to-date details to the report table.
  676. $rows[] = array(
  677. l(t('Month-to-date, @month', array('@month' => $month_title)), 'admin/store/orders/search/results/0/0/0/0/0/0/' . $month_start . '/' . $month_end),
  678. $month['total'],
  679. array('data' => array('#theme' => 'uc_price', '#price' => $month['income'])),
  680. array('data' => array('#theme' => 'uc_price', '#price' => $month['average'])),
  681. );
  682. // Calculate the daily averages for the month.
  683. $daily_orders = round($month['total'] / $date_day_of_month, 2);
  684. $daily_revenue = round($month['income'] / $date_day_of_month, 2);
  685. if ($daily_orders > 0) {
  686. $daily_average = round($daily_revenue / $daily_orders, 2);
  687. }
  688. else {
  689. $daily_average = 0;
  690. }
  691. // Add the daily averages for the month to the report table.
  692. $rows[] = array(
  693. t('Daily average for @month', array('@month' => $month_title)),
  694. $daily_orders,
  695. array('data' => array('#theme' => 'uc_price', '#price' => $daily_revenue)),
  696. '',
  697. );
  698. // Store the number of days remaining in the month.
  699. $remaining_days = date('t') - $date_day_of_month;
  700. // Add the projected totals for the month to the report table.
  701. $rows[] = array(
  702. t('Projected totals for @date', array('@date' => $month_title)),
  703. round($month['total'] + ($daily_orders * $remaining_days), 2),
  704. array('data' => array('#theme' => 'uc_price', '#price' => round($month['income'] + ($daily_revenue * $remaining_days), 2))),
  705. '',
  706. );
  707. // Add the sales data report table to the output.
  708. $build['sales'] = array(
  709. '#theme' => 'table',
  710. '#header' => $header,
  711. '#rows' => $rows,
  712. '#attributes' => array('class' => array('uc-sales-table')),
  713. );
  714. // Build the header statistics table header.
  715. $header = array(array('data' => t('Statistics'), 'width' => '50%'), '');
  716. $rows = array(
  717. array(array('data' => t('Grand total sales')), array('data' => array('#theme' => 'uc_price', '#price' => db_query("SELECT SUM(order_total) FROM {uc_orders} WHERE order_status IN (:statuses)", array(':statuses' => $order_statuses))->fetchField()))),
  718. array(array('data' => t('Customers total')), array('data' => db_query("SELECT COUNT(DISTINCT uid) FROM {uc_orders} WHERE order_status IN (:statuses)", array(':statuses' => $order_statuses))->fetchField())),
  719. array(array('data' => t('New customers today')), array('data' => db_query("SELECT COUNT(DISTINCT uid) FROM {uc_orders} WHERE order_status IN (:statuses) AND :start <= created AND created <= :end", array(':statuses' => $order_statuses, ':start' => $today_start, ':end' => $today_end))->fetchField())),
  720. array(array('data' => t('Online customers')), array('data' => db_query("SELECT COUNT(DISTINCT s.uid) FROM {sessions} s LEFT JOIN {uc_orders} o ON s.uid = o.uid WHERE s.uid > 0 AND o.order_status IN (:statuses)", array(':statuses' => $order_statuses))->fetchField())),
  721. );
  722. // Add the statistics table to the output.
  723. $build['statistics'] = array(
  724. '#theme' => 'table',
  725. '#header' => $header,
  726. '#rows' => $rows,
  727. '#attributes' => array('width' => '100%', 'class' => array('uc-sales-table')),
  728. );
  729. // Build the total orders by status table header.
  730. $header = array(array('data' => t('Total orders by status'), 'width' => '50%'), '');
  731. $rows = array();
  732. $unknown = 0;
  733. // Loop through the order statuses with their total number of orders.
  734. $result = db_query("SELECT s.order_status_id, order_status, s.title, s.weight, COUNT(o.order_status) as order_count FROM {uc_orders} o LEFT JOIN {uc_order_statuses} s ON s.order_status_id = o.order_status GROUP BY s.order_status_id, order_status, s.title, s.weight ORDER BY s.weight DESC");
  735. while ($status = $result->fetchAssoc()) {
  736. if (!empty($status['title'])) {
  737. // Add the total number of orders with this status to the table.
  738. $rows[] = array(
  739. l($status['title'], 'admin/store/orders/view', array('query' => array('order_status' => $status['order_status_id']))),
  740. $status['order_count'],
  741. );
  742. }
  743. else {
  744. // Keep track of the count of orders with an unknown status.
  745. $unknown += $status['order_count'];
  746. }
  747. }
  748. // Add the unknown status count to the table.
  749. if ($unknown > 0) {
  750. $rows[] = array(
  751. t('Unknown status'),
  752. $unknown,
  753. );
  754. }
  755. // Add the total orders by status table to the output.
  756. $build['orders'] = array(
  757. '#theme' => 'table',
  758. '#header' => $header,
  759. '#rows' => $rows,
  760. '#attributes' => array('class' => array('uc-sales-table')),
  761. );
  762. return $build;
  763. }
  764. /**
  765. * Displays the yearly sales report form and table.
  766. */
  767. function uc_reports_sales_year() {
  768. $order_statuses = uc_reports_order_statuses();
  769. // Get the year for the report from the URL.
  770. if (intval(arg(5)) == 0) {
  771. $year = date('Y');
  772. }
  773. else {
  774. $year = arg(5);
  775. }
  776. // Build the header for the report table.
  777. $header = array(t('Month'), t('Number of orders'), t('Total revenue'), t('Average order'));
  778. // Build the header to the CSV export.
  779. $csv_rows = array(array(t('Month'), t('Number of orders'), t('Total revenue'), t('Average order')));
  780. // For each month of the year...
  781. for ($i = 1; $i <= 12; $i++) {
  782. // Calculate the start and end timestamps for the month in local time.
  783. $month_start = mktime(0, 0, 0, $i, 1, $year);
  784. $month_end = mktime(23, 59, 59, $i + 1, 0, $year);
  785. // Get the sales report for the month.
  786. $month_sales = uc_reports_get_sales($month_start, 'month');
  787. // Calculate the average order total for the month.
  788. if ($month_sales['total'] != 0) {
  789. $month_average = round($month_sales['income'] / $month_sales['total'], 2);
  790. }
  791. else {
  792. $month_average = 0;
  793. }
  794. // Add the month's row to the report table.
  795. $rows[] = array(
  796. l(date('M Y', $month_start), 'admin/store/orders/search/results/0/0/0/0/0/0/' . $month_start . '/' . $month_end),
  797. $month_sales['total'],
  798. uc_currency_format($month_sales['income']),
  799. uc_currency_format($month_average),
  800. );
  801. // Add the data to the CSV export.
  802. $csv_rows[] = array(
  803. date('M Y', $month_start),
  804. $month_sales['total'],
  805. $month_sales['income'],
  806. $month_average,
  807. );
  808. }
  809. // Calculate the start and end timestamps for the year in local time.
  810. $year_start = mktime(0, 0, 0, 1, 1, $year);
  811. $year_end = mktime(23, 59, 59, 1, 0, $year + 1);
  812. // Get the sales report for the year.
  813. $year_sales = uc_reports_get_sales($year_start, 'year');
  814. // Calculate the average order total for the year.
  815. if ($year_sales['total'] != 0) {
  816. $year_average = round($year_sales['income'] / $year_sales['total'], 2);
  817. }
  818. else {
  819. $year_average = 0;
  820. }
  821. // Add the total row to the report table.
  822. $rows[] = array(
  823. l(t('Total @year', array('@year' => $year)), 'admin/store/orders/search/results/0/0/0/0/0/0/' . $year_start . '/' . $year_end),
  824. $year_sales['total'],
  825. uc_currency_format($year_sales['income']),
  826. uc_currency_format($year_average),
  827. );
  828. // Add the total data to the CSV export.
  829. $csv_rows[] = array(
  830. t('Total @year', array('@year' => $year)),
  831. $year_sales['total'],
  832. $year_sales['income'],
  833. $year_average,
  834. );
  835. // Cache the CSV export.
  836. $csv_data = uc_reports_store_csv('uc_sales_yearly', $csv_rows);
  837. // Build the page output holding the form, table, and CSV export link.
  838. $build['form'] = drupal_get_form('uc_reports_sales_year_form', $year);
  839. $build['report'] = array(
  840. '#theme' => 'table',
  841. '#header' => $header,
  842. '#rows' => $rows,
  843. '#attributes' => array('width' => '100%', 'class' => array('uc-sales-table')),
  844. );
  845. $build['links'] = array(
  846. '#prefix' => '<div class="uc-reports-links">',
  847. '#suffix' => '</div>',
  848. );
  849. $build['links']['export_csv'] = array(
  850. '#markup' => l(t('Export to CSV file.'), 'admin/store/reports/getcsv/' . $csv_data['report'] . '/' . $csv_data['user']),
  851. );
  852. return $build;
  853. }
  854. /**
  855. * Form to specify a year for the yearly sales report.
  856. *
  857. * @see uc_reports_sales_year_form_submit()
  858. * @ingroup forms
  859. */
  860. function uc_reports_sales_year_form($form, &$form_state, $year) {
  861. $form['year'] = array(
  862. '#type' => 'textfield',
  863. '#title' => t('Sales year'),
  864. '#default_value' => $year,
  865. '#maxlength' => 4,
  866. '#size' => 4,
  867. '#prefix' => '<div class="sales-year">',
  868. '#suffix' => '</div>',
  869. );
  870. $form['actions'] = array('#type' => 'actions');
  871. $form['actions']['submit'] = array(
  872. '#type' => 'submit',
  873. '#value' => t('View'),
  874. '#prefix' => '<div class="sales-year">',
  875. '#suffix' => '</div>',
  876. );
  877. return $form;
  878. }
  879. /**
  880. * Submit handler for uc_reports_sales_year_form().
  881. *
  882. * @see uc_reports_sales_year_form()
  883. */
  884. function uc_reports_sales_year_form_submit($form, &$form_state) {
  885. $form_state['redirect'] = 'admin/store/reports/sales/year/' . $form_state['values']['year'];
  886. }
  887. /**
  888. * Displays the custom sales report form and table.
  889. */
  890. function uc_reports_sales_custom() {
  891. // Use default report parameters if we don't detect values in the URL.
  892. if (arg(5) == '') {
  893. $args = array(
  894. 'start_date' => mktime(0, 0, 0, date('n'), 1, date('Y') - 1),
  895. 'end_date' => REQUEST_TIME,
  896. 'length' => 'month',
  897. 'status' => uc_reports_order_statuses(),
  898. 'detail' => FALSE,
  899. );
  900. }
  901. else {
  902. $args = array(
  903. 'start_date' => arg(5),
  904. 'end_date' => arg(6),
  905. 'length' => arg(7),
  906. 'status' => explode(',', arg(8)),
  907. 'detail' => arg(9),
  908. );
  909. }
  910. // Build the header for the report table.
  911. $header = array(t('Date'), t('Number of orders'), t('Products sold'), t('Total revenue'));
  912. // Build the header to the CSV export.
  913. $csv_rows = array(array(t('Date'), t('Number of orders'), t('Products sold'), t('Total revenue')));
  914. // Grab the subreports based on the date range and the report breakdown.
  915. $subreports = uc_reports_subreport_intervals($args['start_date'], $args['end_date'], $args['length']);
  916. // Loop through the subreports and build the report table.
  917. foreach ($subreports as $subreport) {
  918. $product_data = '';
  919. $product_csv = '';
  920. $order_data = '';
  921. $order_csv = '';
  922. // Create the date title for the subreport.
  923. if ($args['length'] == 'day') {
  924. $date = format_date($subreport['start'], 'custom', variable_get('date_format_uc_store', 'm/d/Y') . ' - D');
  925. }
  926. else {
  927. $date = format_date($subreport['start'], 'uc_store') . ' - ' . format_date($subreport['end'], 'uc_store');
  928. }
  929. // Build the order data for the subreport.
  930. $result = db_query("SELECT COUNT(*) as count, title FROM {uc_orders} LEFT JOIN {uc_order_statuses} ON order_status_id = order_status WHERE :start <= created AND created <= :end AND order_status IN (:statuses) GROUP BY order_status, {uc_order_statuses}.title, {uc_order_statuses}.weight ORDER BY weight ASC", array(':statuses' => $args['status'], ':start' => $subreport['start'], ':end' => $subreport['end']));
  931. $statuses = array();
  932. // Put the order counts into an array by status.
  933. foreach ($result as $status) {
  934. $statuses[] = t('!count - @title', array('!count' => $status->count, '@title' => $status->title));
  935. }
  936. $order_data = implode('<br />', $statuses);
  937. $order_csv = implode("\n", $statuses);
  938. // Build the product data for the subreport.
  939. if ($args['detail']) {
  940. // Grab the detailed product breakdown if selected.
  941. $result = db_query("SELECT SUM(op.qty) as count, n.title, n.nid FROM {uc_order_products} op LEFT JOIN {uc_orders} o ON o.order_id = op.order_id LEFT JOIN {node} n ON n.nid = op.nid WHERE :start <= o.created AND o.created <= :end AND o.order_status IN (:statuses) GROUP BY n.nid ORDER BY count DESC, n.title ASC", array(':statuses' => $args['status'], ':start' => $subreport['start'], ':end' => $subreport['end']));
  942. foreach ($result as $product_breakdown) {
  943. $product_data .= $product_breakdown->count . ' x ' . l($product_breakdown->title, 'node/' . $product_breakdown->nid) . "<br />\n";
  944. $product_csv .= $product_breakdown->count . ' x ' . $product_breakdown->title . "\n";
  945. }
  946. }
  947. else {
  948. // Otherwise just display the total number of products sold.
  949. $product_data = db_query("SELECT SUM(qty) FROM {uc_orders} o LEFT JOIN {uc_order_products} op ON o.order_id = op.order_id WHERE :start <= created AND created <= :end AND order_status IN (:statuses)", array(':statuses' => $args['status'], ':start' => $subreport['start'], ':end' => $subreport['end']))->fetchField();
  950. $product_csv = $product_data;
  951. }
  952. // Tally up the revenue from the orders.
  953. $revenue_count = db_query("SELECT SUM(order_total) FROM {uc_orders} WHERE :start <= created AND created <= :end AND order_status IN (:statuses)", array(':statuses' => $args['status'], ':start' => $subreport['start'], ':end' => $subreport['end']))->fetchField();
  954. // Add the subreport's row to the report table.
  955. $rows[] = array(
  956. $date,
  957. empty($order_data) ? '0' : $order_data,
  958. empty($product_data) ? '0' : $product_data,
  959. uc_currency_format($revenue_count),
  960. );
  961. // Add the data to the CSV export.
  962. $csv_rows[] = array(
  963. $date,
  964. empty($order_csv) ? '0' : $order_csv,
  965. empty($product_csv) ? '0' : $product_csv,
  966. $revenue_count,
  967. );
  968. }
  969. // Calculate the totals for the report.
  970. $order_total = db_query("SELECT COUNT(*) FROM {uc_orders} WHERE :start <= created AND created <= :end AND order_status IN (:statuses)", array(':statuses' => $args['status'], ':start' => $args['start_date'], ':end' => $args['end_date']))->fetchField();
  971. $product_total = db_query("SELECT SUM(qty) FROM {uc_orders} o LEFT JOIN {uc_order_products} op ON o.order_id = op.order_id WHERE :start <= created AND created <= :end AND order_status IN (:statuses)", array(':statuses' => $args['status'], ':start' => $args['start_date'], ':end' => $args['end_date']))->fetchField();
  972. $revenue_total = db_query("SELECT SUM(order_total) FROM {uc_orders} WHERE :start <= created AND created <= :end AND order_status IN (:statuses)", array(':statuses' => $args['status'], ':start' => $args['start_date'], ':end' => $args['end_date']))->fetchField();
  973. // Add the total row to the report table.
  974. $rows[] = array(
  975. t('Total'),
  976. $order_total,
  977. $product_total,
  978. uc_currency_format($revenue_total),
  979. );
  980. // Add the total data to the CSV export.
  981. $csv_rows[] = array(
  982. t('Total'),
  983. $order_total,
  984. $product_total,
  985. $revenue_total,
  986. );
  987. // Cache the CSV export.
  988. $csv_data = uc_reports_store_csv('uc_sales_custom', $csv_rows);
  989. // Build the page output holding the form, table, and CSV export link.
  990. $build['form'] = drupal_get_form('uc_reports_sales_custom_form', $args, $args['status']);
  991. $build['report'] = array(
  992. '#theme' => 'table',
  993. '#header' => $header,
  994. '#rows' => $rows,
  995. '#attributes' => array('width' => '100%', 'class' => array('uc-sales-table')),
  996. );
  997. $build['links'] = array(
  998. '#prefix' => '<div class="uc-reports-links">',
  999. '#suffix' => '</div>',
  1000. );
  1001. $build['links']['export_csv'] = array(
  1002. '#markup' => l(t('Export to CSV file.'), 'admin/store/reports/getcsv/' . $csv_data['report'] . '/' . $csv_data['user']),
  1003. );
  1004. return $build;
  1005. }
  1006. /**
  1007. * Form builder for the custom sales report.
  1008. *
  1009. * @see uc_reports_sales_custom_form_validate()
  1010. * @see uc_reports_sales_custom_form_submit()
  1011. * @ingroup forms
  1012. */
  1013. function uc_reports_sales_custom_form($form, &$form_state, $values, $statuses) {
  1014. $form['search'] = array(
  1015. '#type' => 'fieldset',
  1016. '#title' => t('Customize sales report parameters'),
  1017. '#description' => t('Adjust these values and update the report to build your custom sales summary. Once submitted, the report may be bookmarked for easy reference in the future.'),
  1018. '#collapsible' => TRUE,
  1019. '#collapsed' => TRUE,
  1020. );
  1021. $form['search']['start_date'] = array(
  1022. '#type' => 'date',
  1023. '#title' => t('Start date'),
  1024. '#default_value' => array(
  1025. 'month' => format_date($values['start_date'], 'custom', 'n'),
  1026. 'day' => format_date($values['start_date'], 'custom', 'j'),
  1027. 'year' => format_date($values['start_date'], 'custom', 'Y'),
  1028. ),
  1029. );
  1030. $form['search']['end_date'] = array(
  1031. '#type' => 'date',
  1032. '#title' => t('End date'),
  1033. '#default_value' => array(
  1034. 'month' => format_date($values['end_date'], 'custom', 'n'),
  1035. 'day' => format_date($values['end_date'], 'custom', 'j'),
  1036. 'year' => format_date($values['end_date'], 'custom', 'Y'),
  1037. ),
  1038. );
  1039. $form['search']['length'] = array(
  1040. '#type' => 'select',
  1041. '#title' => t('Results breakdown'),
  1042. '#description' => t('Large daily reports may take a long time to display.'),
  1043. '#options' => array(
  1044. 'day' => t('daily'),
  1045. 'week' => t('weekly'),
  1046. 'month' => t('monthly'),
  1047. 'year' => t('yearly'),
  1048. ),
  1049. '#default_value' => $values['length'],
  1050. );
  1051. $options = array();
  1052. foreach (uc_order_status_list() as $status) {
  1053. $options[$status['id']] = $status['title'];
  1054. }
  1055. if ($statuses === FALSE) {
  1056. $statuses = uc_reports_order_statuses();
  1057. }
  1058. $form['search']['status'] = array(
  1059. '#type' => 'checkboxes',
  1060. '#title' => t('Order statuses'),
  1061. '#description' => t('Only orders with selected statuses will be included in the report.'),
  1062. '#options' => $options,
  1063. '#default_value' => $statuses,
  1064. );
  1065. $form['search']['detail'] = array(
  1066. '#type' => 'checkbox',
  1067. '#title' => t('Show a detailed list of products ordered.'),
  1068. '#default_value' => $values['detail'],
  1069. );
  1070. $form['search']['actions'] = array('#type' => 'actions');
  1071. $form['search']['actions']['submit'] = array(
  1072. '#type' => 'submit',
  1073. '#value' => t('Update report'),
  1074. );
  1075. return $form;
  1076. }
  1077. /**
  1078. * Ensure an order status was selected.
  1079. *
  1080. * @see uc_reports_sales_custom_form()
  1081. * @see uc_reports_sales_custom_form_submit()
  1082. */
  1083. function uc_reports_sales_custom_form_validate($form, &$form_state) {
  1084. if (empty($form_state['values']['status'])) {
  1085. form_set_error('status', t('You must select at least one order status.'));
  1086. }
  1087. }
  1088. /**
  1089. * Submission handler for uc_reports_sales_custom_form().
  1090. *
  1091. * @see uc_reports_sales_custom_form()
  1092. * @see uc_reports_sales_custom_form_validate()
  1093. */
  1094. function uc_reports_sales_custom_form_submit($form, &$form_state) {
  1095. // Build the start and end dates from the form.
  1096. $start_date = mktime(0, 0, 0, $form_state['values']['start_date']['month'], $form_state['values']['start_date']['day'], $form_state['values']['start_date']['year']);
  1097. $end_date = mktime(23, 59, 59, $form_state['values']['end_date']['month'], $form_state['values']['end_date']['day'], $form_state['values']['end_date']['year']);
  1098. $args = array(
  1099. $start_date,
  1100. $end_date,
  1101. $form_state['values']['length'],
  1102. implode(',', array_keys(array_filter($form_state['values']['status']))),
  1103. $form_state['values']['detail'],
  1104. );
  1105. $form_state['redirect'] = 'admin/store/reports/sales/custom/' . implode('/', $args);
  1106. }
  1107. /**
  1108. * Stores a CSV file for a report in Drupal's cache to be retrieved later.
  1109. *
  1110. * @param $report_id
  1111. * A unique string that identifies the report of the CSV file.
  1112. * @param $rows
  1113. * The rows (table header included) that make CSV file.
  1114. *
  1115. * @return
  1116. * An array containing the values need to build URL that return the CSV file
  1117. * of the report and the CSV data itself.
  1118. */
  1119. function uc_reports_store_csv($report_id, $rows) {
  1120. global $user;
  1121. $csv_output = '';
  1122. $user_id = empty($user->uid) ? session_id() : $user->uid;
  1123. foreach ($rows as $row) {
  1124. foreach ($row as $index => $column) {
  1125. $row[$index] = '"' . str_replace('"', '""', $column) . '"';
  1126. }
  1127. $csv_output .= implode(',', $row) . "\n";
  1128. }
  1129. cache_set('uc_reports_' . $report_id . '_' . $user_id, $csv_output, 'cache', REQUEST_TIME + 86400);
  1130. return array('user' => $user_id, 'report' => $report_id, 'csv' => $csv_output);
  1131. }
  1132. /**
  1133. * Retrieves a cached CSV report & send its data.
  1134. *
  1135. * @param $report_id
  1136. * A unique string that identifies the specific report CSV to retrieve.
  1137. * @param $user_id
  1138. * The user id to who's retrieving the report:
  1139. * - uid: Equals uid for authenticated users.
  1140. * - sid: Equals session_id for anonymous users.
  1141. */
  1142. function uc_reports_get_csv($report_id, $user_id) {
  1143. global $user;
  1144. $user_check = empty($user->uid) ? session_id() : $user->uid;
  1145. $csv_data = cache_get('uc_reports_' . $report_id . '_' . $user_id, 'cache');
  1146. if (!$csv_data || $user_id != $user_check) {
  1147. drupal_set_message(t("The CSV data could not be retrieved. It's possible the data might have expired. Refresh the report page and try to retrieve the CSV file again."), 'error');
  1148. drupal_not_found();
  1149. exit();
  1150. }
  1151. else {
  1152. ob_end_clean();
  1153. $http_headers = array(
  1154. 'Pragma' => 'private',
  1155. 'Expires' => '0',
  1156. 'Cache-Control' => 'private, must-revalidate',
  1157. 'Content-Transfer-Encoding' => 'binary',
  1158. 'Content-Length' => strlen($csv_data->data),
  1159. 'Content-Disposition' => 'attachment; filename="' . $report_id . '.csv"',
  1160. 'Content-Type' => 'text/csv'
  1161. );
  1162. foreach ($http_headers as $header => $value) {
  1163. $value = preg_replace('/\r?\n(?!\t| )/', '', $value);
  1164. drupal_add_http_header($header, $value);
  1165. }
  1166. print $csv_data->data;
  1167. exit();
  1168. }
  1169. }
  1170. /**
  1171. * Returns sales that occurred in a given time period.
  1172. *
  1173. * @param $time
  1174. * A UNIX timestamp representing the time in which to get sales data.
  1175. * @param $interval
  1176. * The amount of time over which to count sales (e.g. [1] day, month, year).
  1177. *
  1178. * @return
  1179. * An associative array containing information about sales:
  1180. * - date: A string representing the day counting was started.
  1181. * - income: The total revenue that occurred during the time period.
  1182. * - total: The total number of orders completed during the time period.
  1183. * - average: The average revenue produced for each order.
  1184. */
  1185. function uc_reports_get_sales($start, $interval = 'day') {
  1186. // Add one to the granularity chosen, and use it to calc the new time.
  1187. $end = strtotime('+1 ' . $interval, $start) - 1;
  1188. // Set up the default SQL for getting orders with the proper status
  1189. // within this period.
  1190. $order_statuses = uc_reports_order_statuses();
  1191. // Get the total value of the orders.
  1192. $output = array('income' => 0);
  1193. $orders = db_query("SELECT o.order_total FROM {uc_orders} o WHERE o.order_status IN (:statuses) AND :start <= created AND created <= :end", array(':statuses' => $order_statuses, ':start' => $start, ':end' => $end));
  1194. while ($order = $orders->fetchObject()) {
  1195. $output['income'] += $order->order_total;
  1196. }
  1197. // Get the total amount of orders.
  1198. $count = db_query("SELECT COUNT(o.order_total) FROM {uc_orders} o WHERE o.order_status IN (:statuses) AND :start <= created AND created <= :end", array(':statuses' => $order_statuses, ':start' => $start, ':end' => $end))->fetchField();
  1199. $output['total'] = $count;
  1200. // Average for this period.
  1201. $output['average'] = ($count != 0) ? round($output['income'] / $count, 2) : 0;
  1202. return $output;
  1203. }
  1204. /**
  1205. * Returns a list of timespans for subreports over that report's time span.
  1206. *
  1207. * To be used with a given time span for a report and specified interval for
  1208. * subreports.
  1209. *
  1210. * @param $start
  1211. * A UNIX timestamp representing the time to start the report.
  1212. * @param $end
  1213. * A UNIX timestamp representing the time to end the report.
  1214. * @param $interval
  1215. * Text representing the time span of the subreport (e.g. 'day', 'week').
  1216. *
  1217. * @return
  1218. * An array of keyed arrays with the following values:
  1219. * - start: The starting point of the sub report.
  1220. * - end: The ending point of the sub report.
  1221. */
  1222. function uc_reports_subreport_intervals($start, $report_end, $interval) {
  1223. $subreports = array();
  1224. while ($start < $report_end) {
  1225. $end = strtotime('+1 ' . $interval, $start) - 1;
  1226. $subreports[] = array(
  1227. 'start' => $start,
  1228. 'end' => min($end, $report_end),
  1229. );
  1230. $start = $end + 1;
  1231. }
  1232. return $subreports;
  1233. }