summaryrefslogtreecommitdiff
path: root/FS/FS/cust_bill.pm
blob: 79a17b3191969a7a85e4f40dcf083a2c32a1e683 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
package FS::cust_bill;
use base qw( FS::cust_bill::Search FS::Template_Mixin
             FS::cust_main_Mixin FS::Record
           );

use strict;
use vars qw( $DEBUG $me );
             # but NOT $conf
use Carp;
use Fcntl qw(:flock); #for spool_csv
use Cwd;
use List::Util qw(min max sum);
use Date::Format;
use DateTime;
use File::Temp 0.14;
use HTML::Entities;
use Storable qw( freeze thaw );
use GD::Barcode;
use FS::UID qw( datasrc );
use FS::Misc qw( send_fax do_print );
use FS::Record qw( qsearch qsearchs dbh );
use FS::cust_statement;
use FS::cust_bill_pkg;
use FS::cust_bill_pkg_display;
use FS::cust_bill_pkg_detail;
use FS::cust_credit;
use FS::cust_pay;
use FS::cust_pkg;
use FS::cust_credit_bill;
use FS::pay_batch;
use FS::cust_event;
use FS::part_pkg;
use FS::cust_bill_pay;
use FS::payby;
use FS::bill_batch;
use FS::cust_bill_batch;
use FS::cust_bill_pay_pkg;
use FS::cust_credit_bill_pkg;
use FS::discount_plan;
use FS::cust_bill_void;
use FS::reason;
use FS::reason_type;
use FS::L10N;
use FS::Misc::Savepoint;

$DEBUG = 0;
$me = '[FS::cust_bill]';

=head1 NAME

FS::cust_bill - Object methods for cust_bill records

=head1 SYNOPSIS

  use FS::cust_bill;

  $record = new FS::cust_bill \%hash;
  $record = new FS::cust_bill { 'column' => 'value' };

  $error = $record->insert;

  $error = $new_record->replace($old_record);

  $error = $record->delete;

  $error = $record->check;

  ( $total_previous_balance, @previous_cust_bill ) = $record->previous;

  @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;

  ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;

  @cust_pay_objects = $cust_bill->cust_pay;

  $tax_amount = $record->tax;

  @lines = $cust_bill->print_text;
  @lines = $cust_bill->print_text('time' => $time);

=head1 DESCRIPTION

An FS::cust_bill object represents an invoice; a declaration that a customer
owes you money.  The specific charges are itemized as B<cust_bill_pkg> records
(see L<FS::cust_bill_pkg>).  FS::cust_bill inherits from FS::Record.  The
following fields are currently supported:

Regular fields

=over 4

=item invnum - primary key (assigned automatically for new invoices)

=item custnum - customer (see L<FS::cust_main>)

=item _date - specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
L<Time::Local> and L<Date::Parse> for conversion functions.

=item charged - amount of this invoice

=item invoice_terms - optional terms override for this specific invoice

=back

Deprecated fields

=over 4

=item billing_balance - the customer's balance immediately before generating
this invoice.  DEPRECATED.  Use the L<FS::cust_main/balance_date> method 
to determine the customer's balance at a specific time.

=item previous_balance - the customer's balance immediately after generating
the invoice before this one.  DEPRECATED.

=item printed - formerly used to track the number of times an invoice had 
been printed; no longer used.

=back

Specific use cases

=over 4

=item closed - books closed flag, empty or `Y'

=item statementnum - invoice aggregation (see L<FS::cust_statement>)

=item agent_invid - legacy invoice number

=item promised_date - customer promised payment date, for collection

=item pending - invoice is still being generated, empty or 'Y'

=back

=head1 METHODS

=over 4

=item new HASHREF

Creates a new invoice.  To add the invoice to the database, see L<"insert">.
Invoices are normally created by calling the bill method of a customer object
(see L<FS::cust_main>).

=cut

sub table { 'cust_bill'; }
sub template_conf { 'invoice_'; }

# should be the ONLY occurrence of "Invoice" in invoice rendering code.
# (except email_subject and invnum_date_pretty)
sub notice_name {
  my $self = shift;
  $self->conf->config('notice_name') || 'Invoice'
}

sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum } 
sub cust_unlinked_msg {
  my $self = shift;
  "WARNING: can't find cust_main.custnum ". $self->custnum.
  ' (cust_bill.invnum '. $self->invnum. ')';
}

=item insert

Adds this invoice to the database ("Posts" the invoice).  If there is an error,
returns the error, otherwise returns false.

=cut

sub insert {
  my $self = shift;
  warn "$me insert called\n" if $DEBUG;

  local $SIG{HUP} = 'IGNORE';
  local $SIG{INT} = 'IGNORE';
  local $SIG{QUIT} = 'IGNORE';
  local $SIG{TERM} = 'IGNORE';
  local $SIG{TSTP} = 'IGNORE';
  local $SIG{PIPE} = 'IGNORE';

  my $oldAutoCommit = $FS::UID::AutoCommit;
  local $FS::UID::AutoCommit = 0;
  my $dbh = dbh;

  my $error = $self->SUPER::insert;
  if ( $error ) {
    $dbh->rollback if $oldAutoCommit;
    return $error;
  }

  if ( $self->get('cust_bill_pkg') ) {
    foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
      $cust_bill_pkg->invnum($self->invnum);
      my $error = $cust_bill_pkg->insert;
      if ( $error ) {
        $dbh->rollback if $oldAutoCommit;
        return "can't create invoice line item: $error";
      }
    }
  }

  $dbh->commit or die $dbh->errstr if $oldAutoCommit;
  '';

}

=item void [ REASON [ , REPROCESS_CDRS ] ]

Voids this invoice: deletes the invoice and adds a record of the voided invoice
to the FS::cust_bill_void table (and related tables starting from
FS::cust_bill_pkg_void).

=cut

sub void {
  my $self = shift;
  my $reason = scalar(@_) ? shift : '';
  my $reprocess_cdrs = scalar(@_) ? shift : '';

  unless (ref($reason) || !$reason) {
    $reason = FS::reason->new_or_existing(
      'class'  => 'I',
      'type'   => 'Invoice void',
      'reason' => $reason
    );
  }

  local $SIG{HUP} = 'IGNORE';
  local $SIG{INT} = 'IGNORE';
  local $SIG{QUIT} = 'IGNORE';
  local $SIG{TERM} = 'IGNORE';
  local $SIG{TSTP} = 'IGNORE';
  local $SIG{PIPE} = 'IGNORE';

  my $oldAutoCommit = $FS::UID::AutoCommit;
  local $FS::UID::AutoCommit = 0;
  my $dbh = dbh;

  my $cust_bill_void = new FS::cust_bill_void ( {
    map { $_ => $self->get($_) } $self->fields
  } );
  $cust_bill_void->reasonnum($reason->reasonnum) if $reason;
  my $error = $cust_bill_void->insert;
  if ( $error ) {
    $dbh->rollback if $oldAutoCommit;
    return $error;
  }

  foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
    my $error = $cust_bill_pkg->void($reason, $reprocess_cdrs);
    if ( $error ) {
      $dbh->rollback if $oldAutoCommit;
      return $error;
    }
  }

  $error = $self->delete;
  if ( $error ) {
    $dbh->rollback if $oldAutoCommit;
    return $error;
  }

  $dbh->commit or die $dbh->errstr if $oldAutoCommit;

  '';

}

=item delete

DO NOT USE THIS METHOD.  Instead, apply a credit against the invoice, or use
the B<void> method.

This is only for internal use by V<void>, which is what you should be using.

DO NOT USE THIS METHOD.  Whatever reason you think you have is almost certainly
wrong.  Use B<void>, that's what it is for.  Really.  This means you.

=cut

sub delete {
  my $self = shift;
  return "Can't delete closed invoice" if $self->closed =~ /^Y/i;

  local $SIG{HUP} = 'IGNORE';
  local $SIG{INT} = 'IGNORE';
  local $SIG{QUIT} = 'IGNORE';
  local $SIG{TERM} = 'IGNORE';
  local $SIG{TSTP} = 'IGNORE';
  local $SIG{PIPE} = 'IGNORE';

  my $oldAutoCommit = $FS::UID::AutoCommit;
  local $FS::UID::AutoCommit = 0;
  my $dbh = dbh;

  foreach my $table (qw(
    cust_credit_bill
    cust_bill_pay_batch
    cust_bill_pay
    cust_bill_batch
    cust_bill_pkg
  )) {
    #cust_event # problematic
    #cust_pay_batch # unnecessary

    foreach my $linked ( $self->$table() ) {
      my $error = $linked->delete;
      if ( $error ) {
        $dbh->rollback if $oldAutoCommit;
        return $error;
      }
    }

  }

  my $error = $self->SUPER::delete(@_);
  if ( $error ) {
    $dbh->rollback if $oldAutoCommit;
    return $error;
  }

  $dbh->commit or die $dbh->errstr if $oldAutoCommit;

  '';

}

=item replace [ OLD_RECORD ]

You can, but probably shouldn't modify invoices...

Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
supplied, replaces this record.  If there is an error, returns the error,
otherwise returns false.

=cut

#replace can be inherited from Record.pm

# replace_check is now the preferred way to #implement replace data checks
# (so $object->replace() works without an argument)

sub replace_check {
  my( $new, $old ) = ( shift, shift );
  return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
  #return "Can't change _date!" unless $old->_date eq $new->_date;
  return "Can't change _date" unless $old->_date == $new->_date;
  return "Can't change charged" unless $old->charged == $new->charged
                                    || $old->pending eq 'Y'
                                    || $old->charged == 0
				    || $new->{'Hash'}{'cc_surcharge_replace_hack'};

  '';
}


=item add_cc_surcharge

Giant hack

=cut

sub add_cc_surcharge {
    my ($self, $pkgnum, $amount) = (shift, shift, shift);

    my $error;
    my $cust_bill_pkg = new FS::cust_bill_pkg({
				    'invnum' => $self->invnum,
				    'pkgnum' => $pkgnum,
				    'setup' => $amount,
			});
    $error = $cust_bill_pkg->insert;
    return $error if $error;

    $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
    $self->charged($self->charged+$amount);
    $error = $self->replace;
    return $error if $error;

    $self->apply_payments_and_credits;
}


=item check

Checks all fields to make sure this is a valid invoice.  If there is an error,
returns the error, otherwise returns false.  Called by the insert and replace
methods.

=cut

sub check {
  my $self = shift;

  my $error =
    $self->ut_numbern('invnum')
    || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
    || $self->ut_numbern('_date')
    || $self->ut_money('charged')
    || $self->ut_numbern('printed')
    || $self->ut_enum('closed', [ '', 'Y' ])
    || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
    || $self->ut_numbern('agent_invid') #varchar?
    || $self->ut_flag('pending')
  ;
  return $error if $error;

  $self->_date(time) unless $self->_date;

  $self->printed(0) if $self->printed eq '';

  $self->SUPER::check;
}

=item display_invnum

Returns the displayed invoice number for this invoice: agent_invid if
cust_bill-default_agent_invid is set and it has a value, invnum otherwise.

=cut

sub display_invnum {
  my $self = shift;
  if ( $self->agent_invid
         && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
    return $self->agent_invid;
  } else {
    return $self->invnum;
  }
}

=item previous_bill

Returns the customer's last invoice before this one.

=cut

sub previous_bill {
  my $self = shift;
  if ( !$self->get('previous_bill') ) {
    $self->set('previous_bill', qsearchs({
          'table'     => 'cust_bill',
          'hashref'   => { 'custnum'  => $self->custnum,
                           '_date'    => { op=>'<', value=>$self->_date } },
          'order_by'  => 'ORDER BY _date DESC LIMIT 1',
    }) );
  }
  $self->get('previous_bill');
}

=item following_bill

Returns the customer's invoice that follows this one

=cut

sub following_bill {
  my $self = shift;
  if (!$self->get('following_bill')) {
    $self->set('following_bill', qsearchs({
      table   => 'cust_bill',
      hashref => {
        custnum => $self->custnum,
        invnum  => { op => '>', value => $self->invnum },
      },
      order_by => 'ORDER BY invnum ASC LIMIT 1',
    }));
  }
  $self->get('following_bill');
}

=item previous

Returns a list consisting of the total previous balance for this customer, 
followed by the previous outstanding invoices (as FS::cust_bill objects also).

=cut

sub previous {
  my $self = shift;
  # simple memoize; we use this a lot
  if (!$self->get('previous')) {
    my $total = 0;
    my @cust_bill = sort { $a->_date <=> $b->_date }
      grep { $_->owed != 0 }
        qsearch( 'cust_bill', { 'custnum' => $self->custnum,
                                #'_date'   => { op=>'<', value=>$self->_date },
                                'invnum'   => { op=>'<', value=>$self->invnum },
                              } ) 
    ;
    foreach ( @cust_bill ) { $total += $_->owed; }
    $self->set('previous', [$total, @cust_bill]);
  }
  return @{ $self->get('previous') };
}

=item enable_previous

Whether to show the 'Previous Charges' section when printing this invoice.
The negation of the 'disable_previous_balance' config setting.

=cut

sub enable_previous {
  my $self = shift;
  my $agentnum = $self->cust_main->agentnum;
  !$self->conf->exists('disable_previous_balance', $agentnum);
}

=item cust_bill_pkg

Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.

=cut

sub cust_bill_pkg {
  my $self = shift;
  qsearch(
    { 
      'select'    => 'cust_bill_pkg.*, pkg_category.categoryname',
      'table'    => 'cust_bill_pkg',
      'addl_from' => ' LEFT JOIN cust_pkg     USING ( pkgnum ) '.
                     ' LEFT JOIN part_pkg     USING ( pkgpart ) '.
                     ' LEFT JOIN pkg_class    USING ( classnum ) '.
                     ' LEFT JOIN pkg_category USING ( categorynum ) ',
      'hashref'  => { 'invnum' => $self->invnum },
      'order_by' => 'ORDER BY billpkgnum', #important?  otherwise we could use
                                           # the AUTLOADED FK search.  or should
                                           # that default to ORDER by the pkey?
    }
  );
}

=item cust_bill_pkg_pkgnum PKGNUM

Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
specified pkgnum.

=cut

sub cust_bill_pkg_pkgnum {
  my( $self, $pkgnum ) = @_;
  qsearch(
    { 'table'    => 'cust_bill_pkg',
      'hashref'  => { 'invnum' => $self->invnum,
                      'pkgnum' => $pkgnum,
                    },
      'order_by' => 'ORDER BY billpkgnum',
    }
  );
}

=item cust_pkg

Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
this invoice.

=cut

sub cust_pkg {
  my $self = shift;
  my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
                     $self->cust_bill_pkg;
  my %saw = ();
  grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
}

=item no_auto

Returns true if any of the packages (or their definitions) corresponding to the
line items for this invoice have the no_auto flag set.

=cut

sub no_auto {
  my $self = shift;
  grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
}

=item open_cust_bill_pkg

Returns the open line items for this invoice.

Note that cust_bill_pkg with both setup and recur fees are returned as two
separate line items, each with only one fee.

=cut

# modeled after cust_main::open_cust_bill
sub open_cust_bill_pkg {
  my $self = shift;

  # grep { $_->owed > 0 } $self->cust_bill_pkg

  my %other = ( 'recur' => 'setup',
                'setup' => 'recur', );
  my @open = ();
  foreach my $field ( qw( recur setup )) {
    push @open, map  { $_->set( $other{$field}, 0 ); $_; }
                grep { $_->owed($field) > 0 }
                $self->cust_bill_pkg;
  }

  @open;
}

=item cust_event

Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.

=cut

#false laziness w/cust_pkg.pm
sub cust_event {
  my $self = shift;
  qsearch({
    'table'     => 'cust_event',
    'addl_from' => 'JOIN part_event USING ( eventpart )',
    'hashref'   => { 'tablenum' => $self->invnum },
    'extra_sql' => " AND eventtable = 'cust_bill' ",
  });
}

=item num_cust_event

Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.

=cut

#false laziness w/cust_pkg.pm
sub num_cust_event {
  my $self = shift;
  my $sql =
    "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
    "  WHERE tablenum = ? AND eventtable = 'cust_bill'";
  my $sth = dbh->prepare($sql) or die  dbh->errstr. " preparing $sql"; 
  $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
  $sth->fetchrow_arrayref->[0];
}

=item cust_main

Returns the customer (see L<FS::cust_main>) for this invoice.

=item suspend

Suspends all unsuspended packages (see L<FS::cust_pkg>) for this invoice

Returns a list: an empty list on success or a list of errors.

=cut

sub suspend {
  my $self = shift;

  grep { $_->suspend(@_) } 
  grep {! $_->getfield('cancel') } 
  $self->cust_pkg;

}

=item cust_suspend_if_balance_over AMOUNT

Suspends the customer associated with this invoice if the total amount owed on
this invoice and all older invoices is greater than the specified amount.

Returns a list: an empty list on success or a list of errors.

=cut

sub cust_suspend_if_balance_over {
  my( $self, $amount ) = ( shift, shift );
  my $cust_main = $self->cust_main;
  if ( $cust_main->total_owed_date($self->_date) < $amount ) {
    return ();
  } else {
    $cust_main->suspend(@_);
  }
}

=item cancel

Cancel the packages on this invoice. Largely similar to the cust_main version, but does not bother yet with banned payment options

=cut

sub cancel {
  my( $self, %opt ) = @_;

  warn "$me cancel called on cust_bill ". $self->invnum . " with options ".
       join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
    if $DEBUG;

  return ( 'Access denied' )
    unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');

  my @pkgs = $self->cust_pkg;

  if ( !$opt{nobill} && $self->conf->exists('bill_usage_on_cancel') ) {
    $opt{nobill} = 1;
    my $error = $self->cust_main->bill( pkg_list => [ @pkgs ], cancel => 1 );
    warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
      if $error;
  }

  grep { $_ }
    map { $_->cancel(%opt) }
      grep { ! $_->getfield('cancel') } 
        @pkgs;
}

=item cust_bill_pay

Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.

=cut

sub cust_bill_pay {
  my $self = shift;
  map { $_ } #return $self->num_cust_bill_pay unless wantarray;
  sort { $a->_date <=> $b->_date }
    qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
}

=item cust_credited

=item cust_credit_bill

Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.

=cut

sub cust_credited {
  my $self = shift;
  map { $_ } #return $self->num_cust_credit_bill unless wantarray;
  sort { $a->_date <=> $b->_date }
    qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
  ;
}

sub cust_credit_bill {
  shift->cust_credited(@_);
}

#=item cust_bill_pay_pkgnum PKGNUM
#
#Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
#with matching pkgnum.
#
#=cut
#
#sub cust_bill_pay_pkgnum {
#  my( $self, $pkgnum ) = @_;
#  map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
#  sort { $a->_date <=> $b->_date }
#    qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
#                                'pkgnum' => $pkgnum,
#                              }
#           );
#}

=item cust_bill_pay_pkg PKGNUM

Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
applied against the matching pkgnum.

=cut

sub cust_bill_pay_pkg {
  my( $self, $pkgnum ) = @_;

  qsearch({
    'select'    => 'cust_bill_pay_pkg.*',
    'table'     => 'cust_bill_pay_pkg',
    'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
                   ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
    'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
                   "   AND cust_bill_pkg.pkgnum = $pkgnum",
  });

}

#=item cust_credited_pkgnum PKGNUM
#
#=item cust_credit_bill_pkgnum PKGNUM
#
#Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
#with matching pkgnum.
#
#=cut
#
#sub cust_credited_pkgnum {
#  my( $self, $pkgnum ) = @_;
#  map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
#  sort { $a->_date <=> $b->_date }
#    qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
#                                   'pkgnum' => $pkgnum,
#                                 }
#           );
#}
#
#sub cust_credit_bill_pkgnum {
#  shift->cust_credited_pkgnum(@_);
#}

=item cust_credit_bill_pkg PKGNUM

Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
applied against the matching pkgnum.

=cut

sub cust_credit_bill_pkg {
  my( $self, $pkgnum ) = @_;

  qsearch({
    'select'    => 'cust_credit_bill_pkg.*',
    'table'     => 'cust_credit_bill_pkg',
    'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
                   ' LEFT JOIN cust_bill_pkg    USING ( billpkgnum    ) ',
    'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
                   "   AND cust_bill_pkg.pkgnum = $pkgnum",
  });

}

=item cust_bill_batch

Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.

=cut

sub cust_bill_batch {
  my $self = shift;
  qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
}

=item discount_plans

Returns all discount plans (L<FS::discount_plan>) for this invoice, as a 
hash keyed by term length.

=cut

sub discount_plans {
  my $self = shift;
  FS::discount_plan->all($self);
}

=item tax

Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.

=cut

sub tax {
  my $self = shift;
  my $total = 0;
  my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
                                             'pkgnum' => 0 } );
  foreach (@taxlines) { $total += $_->setup; }
  $total;
}

=item owed

Returns the amount owed (still outstanding) on this invoice, which is charged
minus all payment applications (see L<FS::cust_bill_pay>) and credit
applications (see L<FS::cust_credit_bill>).

=cut

sub owed {
  my $self = shift;
  my $balance = $self->charged;
  $balance -= $_->amount foreach ( $self->cust_bill_pay );
  $balance -= $_->amount foreach ( $self->cust_credited );
  $balance = sprintf( "%.2f", $balance);
  $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
  $balance;
}

=item owed_on_invoice

Returns the amount to be displayed as the "Balance Due" on this
invoice.  Amount returned depends on conf flags for invoicing

See L<FS::cust_bill/owed> for the true amount currently owed

=cut

sub owed_on_invoice {
  my $self = shift;

  #return $self->owed()
  #  unless $self->conf->exists('previous_balance-payments_since')

  # Add charges from this invoice
  my $owed = $self->charged();

  # Add carried balances from previous invoices
  #   If previous items aren't to be displayed on the invoice,
  #   _items_previous() is aware of this and responds appropriately.
  $owed += $_->{amount} for $self->_items_previous();

  # Subtract payments and credits displayed on this invoice
  $owed -= $_->{amount} for $self->_items_payments(), $self->_items_credits();

  return $owed;
}

sub owed_pkgnum {
  my( $self, $pkgnum ) = @_;

  #my $balance = $self->charged;
  my $balance = 0;
  $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);

  $balance -= $_->amount            for $self->cust_bill_pay_pkg($pkgnum);
  $balance -= $_->amount            for $self->cust_credit_bill_pkg($pkgnum);

  $balance = sprintf( "%.2f", $balance);
  $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
  $balance;
}

=item hide

Returns true if this invoice should be hidden.  See the
selfservice-hide_invoices-taxclass configuraiton setting.

=cut

sub hide {
  my $self = shift;
  my $conf = $self->conf;
  my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
    or return '';
  my @cust_bill_pkg = $self->cust_bill_pkg;
  my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
  ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
}

=item apply_payments_and_credits [ OPTION => VALUE ... ]

Applies unapplied payments and credits to this invoice.
Payments with the no_auto_apply flag set will not be applied.

A hash of optional arguments may be passed.  Currently "manual" is supported.
If true, a payment receipt is sent instead of a statement when
'payment_receipt_email' configuration option is set.

If there is an error, returns the error, otherwise returns false.

=cut

sub apply_payments_and_credits {
  my( $self, %options ) = @_;
  my $conf = $self->conf;

  local $SIG{HUP} = 'IGNORE';
  local $SIG{INT} = 'IGNORE';
  local $SIG{QUIT} = 'IGNORE';
  local $SIG{TERM} = 'IGNORE';
  local $SIG{TSTP} = 'IGNORE';
  local $SIG{PIPE} = 'IGNORE';

  my $oldAutoCommit = $FS::UID::AutoCommit;
  local $FS::UID::AutoCommit = 0;
  my $dbh = dbh;

  my $savepoint_label = 'cust_bill__apply_payments_and_credits';
  savepoint_create( $savepoint_label );

  $self->select_for_update; #mutex

  my @payments = grep { $_->unapplied > 0 } 
                   grep { !$_->no_auto_apply }
                     $self->cust_main->cust_pay;
  my @credits  = grep { $_->credited > 0 } $self->cust_main->cust_credit;

  if ( $conf->exists('pkg-balances') ) {
    # limit @payments & @credits to those w/ a pkgnum grepped from $self
    my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
    @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
    @credits  = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
  }

  while ( $self->owed > 0 and ( @payments || @credits ) ) {

    my $app = '';
    if ( @payments && @credits ) {

      #decide which goes first by weight of top (unapplied) line item

      my @open_lineitems = $self->open_cust_bill_pkg;

      my $max_pay_weight =
        max( map  { $_->part_pkg->pay_weight || 0 }
             grep { $_ }
             map  { $_->cust_pkg }
	          @open_lineitems
	   );
      my $max_credit_weight =
        max( map  { $_->part_pkg->credit_weight || 0 }
	     grep { $_ } 
             map  { $_->cust_pkg }
                  @open_lineitems
           );

      #if both are the same... payments first?  it has to be something
      if ( $max_pay_weight >= $max_credit_weight ) {
        $app = 'pay';
      } else {
        $app = 'credit';
      }
    
    } elsif ( @payments ) {
      $app = 'pay';
    } elsif ( @credits ) {
      $app = 'credit';
    } else {
      die "guru meditation #12 and 35";
    }

    my $unapp_amount;
    if ( $app eq 'pay' ) {

      my $payment = shift @payments;
      $unapp_amount = $payment->unapplied;
      $app = new FS::cust_bill_pay { 'paynum'  => $payment->paynum };
      $app->pkgnum( $payment->pkgnum )
        if $conf->exists('pkg-balances') && $payment->pkgnum;

    } elsif ( $app eq 'credit' ) {

      my $credit = shift @credits;
      $unapp_amount = $credit->credited;
      $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
      $app->pkgnum( $credit->pkgnum )
        if $conf->exists('pkg-balances') && $credit->pkgnum;

    } else {
      die "guru meditation #12 and 35";
    }

    my $owed;
    if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
      warn "owed_pkgnum ". $app->pkgnum;
      $owed = $self->owed_pkgnum($app->pkgnum);
    } else {
      $owed = $self->owed;
    }
    next unless $owed > 0;

    warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
    $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );

    $app->invnum( $self->invnum );

    my $error = $app->insert(%options);
    if ( $error ) {
      savepoint_rollback_and_release( $savepoint_label );
      $dbh->rollback if $oldAutoCommit;
      return "Error inserting ". $app->table. " record: $error";
    }
    die $error if $error;

  }

  savepoint_release( $savepoint_label );
  $dbh->commit or die $dbh->errstr if $oldAutoCommit;
  ''; #no error

}

=item send HASHREF

Sends this invoice to the destinations configured for this customer: sends
email, prints and/or faxes.  See L<FS::cust_main_invoice>.

Options can be passed as a hashref.  Positional parameters are no longer
allowed.

I<template>: a suffix for alternate invoices

I<agentnum>: obsolete, now does nothing.

I<from> overrides the default email invoice From: address.

I<amount>: obsolete, does nothing

I<notice_name> overrides "Invoice" as the name of the sent document 
(templates from 10/2009 or newer required).

I<lpr> overrides the system 'lpr' option as the command to print a document
from standard input.

=cut

sub send {
  my $self = shift;
  my $opt = ref($_[0]) ? $_[0] : +{ @_ };
  my $conf = $self->conf;

  my $cust_main = $self->cust_main;

  my @invoicing_list = $cust_main->invoicing_list;

  $self->email($opt)
    if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
    && ! $cust_main->invoice_noemail;

  $self->print($opt)
    if grep { $_ eq 'POST' } @invoicing_list; #postal

  #this has never been used post-$ORIGINAL_ISP afaik
  $self->fax_invoice($opt)
    if grep { $_ eq 'FAX' } @invoicing_list; #fax

  '';

}

sub email {
  my $self = shift;
  my $opt = shift || {};
  if ($opt and !ref($opt)) {
    die ref($self). '->email called with positional parameters';
  }

  my $conf = $self->conf;

  my $from = delete $opt->{from};

  # this is where we set the From: address
  $from ||= $self->_agent_invoice_from ||    #XXX should go away
            $conf->invoice_from_full( $self->cust_main->agentnum );

  my @invoicing_list = $self->cust_main->invoicing_list_emailonly;

  if ( ! @invoicing_list ) { #no recipients
    if ( $conf->exists('cust_bill-no_recipients-error') ) {
      die 'No recipients for customer #'. $self->custnum;
    } else {
      #default: better to notify this person than silence
      @invoicing_list = ($from);
    }
  }

  $self->SUPER::email( {
    'from' => $from,
    'to'   => \@invoicing_list,
    %$opt,
  });

}

#this stays here for now because its explicitly used as
# FS::cust_bill::queueable_email
sub queueable_email {
  my %opt = @_;

  my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
    or die "invalid invoice number: " . $opt{invnum};

  $self->set('mode', $opt{mode})
    if $opt{mode};

  my %args = map {$_ => $opt{$_}} 
             grep { $opt{$_} }
              qw( from notice_name no_coupon template );

  my $error = $self->email( \%args );
  die $error if $error;

}

sub email_subject {
  my $self = shift;
  my $conf = $self->conf;

  #my $template = scalar(@_) ? shift : '';
  #per-template?

  my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
                || 'Invoice';

  my $cust_main = $self->cust_main;
  my $name = $cust_main->name;
  my $name_short = $cust_main->name_short;
  my $invoice_number = $self->invnum;
  my $invoice_date = $self->_date_pretty;

  eval qq("$subject");
}

sub pdf_filename {
  my $self = shift;
  'Invoice-'. $self->invnum. '.pdf';
}

=item lpr_data HASHREF

Returns the postscript or plaintext for this invoice as an arrayref.

Options must be passed as a hashref.  Positional parameters are no longer 
allowed.

I<template>, if specified, is the name of a suffix for alternate invoices.

I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)

=cut

sub lpr_data {
  my $self = shift;
  my $conf = $self->conf;
  my $opt = shift || {};
  if ($opt and !ref($opt)) {
    # nobody does this anyway
    die "FS::cust_bill::lpr_data called with positional parameters";
  }

  my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
  [ $self->$method( $opt ) ];
}

=item print HASHREF

Prints this invoice.

Options must be passed as a hashref.

I<template>, if specified, is the name of a suffix for alternate invoices.

I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)

=cut

sub print {
  my $self = shift;
  return if $self->hide;
  my $conf = $self->conf;
  my $opt = shift || {};
  if ($opt and !ref($opt)) {
    die "FS::cust_bill::print called with positional parameters";
  }

  my $lpr = delete $opt->{lpr};
  if($conf->exists('invoice_print_pdf')) {
    # Add the invoice to the current batch.
    $self->batch_invoice($opt);
  }
  else {
    do_print(
      $self->lpr_data($opt),
      'agentnum' => $self->cust_main->agentnum,
      'lpr'      => $lpr,
    );
  }
}

=item fax_invoice HASHREF

Faxes this invoice.

Options must be passed as a hashref.

I<template>, if specified, is the name of a suffix for alternate invoices.

I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)

=cut

sub fax_invoice {
  my $self = shift;
  return if $self->hide;
  my $conf = $self->conf;
  my $opt = shift || {};
  if ($opt and !ref($opt)) {
    die "FS::cust_bill::fax_invoice called with positional parameters";
  }

  die 'FAX invoice destination not (yet?) supported with plain text invoices.'
    unless $conf->exists('invoice_latex');

  my $dialstring = $self->cust_main->getfield('fax');
  #Check $dialstring?

  my $error = send_fax( 'docdata'    => $self->lpr_data($opt),
                        'dialstring' => $dialstring,
                      );
  die $error if $error;

}

=item batch_invoice [ HASHREF ]

Place this invoice into the open batch (see C<FS::bill_batch>).  If there 
isn't an open batch, one will be created.

HASHREF may contain any options to be passed to C<print_pdf>.

=cut

sub batch_invoice {
  my ($self, $opt) = @_;
  my $bill_batch = $self->get_open_bill_batch;
  my $cust_bill_batch = FS::cust_bill_batch->new({
      batchnum => $bill_batch->batchnum,
      invnum   => $self->invnum,
  });
  if ( $self->mode ) {
    $opt->{mode} ||= $self->mode;
    $opt->{mode} = $opt->{mode}->modenum if ref $opt->{mode};
  }
  return $cust_bill_batch->insert($opt);
}

=item get_open_batch

Returns the currently open batch as an FS::bill_batch object, creating a new
one if necessary.  (A per-agent batch if invoice_print_pdf-spoolagent is
enabled)

=cut

sub get_open_bill_batch {
  my $self = shift;
  my $conf = $self->conf;
  my $hashref = { status => 'O' };
  $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
                             ? $self->cust_main->agentnum
                             : '';
  my $batch = qsearchs('bill_batch', $hashref);
  return $batch if $batch;
  $batch = FS::bill_batch->new($hashref);
  my $error = $batch->insert;
  die $error if $error;
  return $batch;
}

=item ftp_invoice [ TEMPLATENAME ] 

Sends this invoice data via FTP.

TEMPLATENAME is unused?

=cut

sub ftp_invoice {
  my $self = shift;
  my $conf = $self->conf;
  my $template = scalar(@_) ? shift : '';

  $self->send_csv(
    'protocol'   => 'ftp',
    'server'     => $conf->config('cust_bill-ftpserver'),
    'username'   => $conf->config('cust_bill-ftpusername'),
    'password'   => $conf->config('cust_bill-ftppassword'),
    'dir'        => $conf->config('cust_bill-ftpdir'),
    'format'     => $conf->config('cust_bill-ftpformat'),
  );
}

=item spool_invoice [ TEMPLATENAME ] 

Spools this invoice data (see L<FS::cust_bill/spool_csv>)

TEMPLATENAME is unused?

=cut

sub spool_invoice {
  my $self = shift;
  my $conf = $self->conf;
  my $template = scalar(@_) ? shift : '';

  $self->spool_csv(
    'format'       => $conf->config('cust_bill-spoolformat'),
    'agent_spools' => $conf->exists('cust_bill-spoolagent'),
  );
}

=item send_csv OPTION => VALUE, ...

Sends invoice as a CSV data-file to a remote host with the specified protocol.

Options are:

protocol - currently only "ftp"
server
username
password
dir

The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
and YYMMDDHHMMSS is a timestamp.

See L</print_csv> for a description of the output format.

=cut

sub send_csv {
  my($self, %opt) = @_;

  if ( $FS::Misc::DISABLE_ALL_NOTICES ) {
    warn 'send_csv() disabled by $FS::Misc::DISABLE_ALL_NOTICES' if $DEBUG;
    return;
  }

  #create file(s)

  my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
  mkdir $spooldir, 0700 unless -d $spooldir;

  # don't localize dates here, they're a defined format
  my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
  my $file = "$spooldir/$tracctnum.csv";
  
  my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );

  open(CSV, ">$file") or die "can't open $file: $!";
  print CSV $header;

  print CSV $detail;

  close CSV;

  my $net;
  if ( $opt{protocol} eq 'ftp' ) {
    eval "use Net::FTP;";
    die $@ if $@;
    $net = Net::FTP->new($opt{server}) or die @$;
  } else {
    die "unknown protocol: $opt{protocol}";
  }

  $net->login( $opt{username}, $opt{password} )
    or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";

  $net->binary or die "can't set binary mode";

  $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";

  $net->put($file) or die "can't put $file: $!";

  $net->quit;

  unlink $file;

}

=item spool_csv

Spools CSV invoice data.

Options are:

=over 4

=item format - any of FS::Misc::::Invoicing::spool_formats

=item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
customer has the corresponding invoice destinations set (see
L<FS::cust_main_invoice>).

=item agent_spools - if set to a true value, will spool to per-agent files
rather than a single global file

=item upload_targetnum - if set to a target (see L<FS::upload_target>), will
append to that spool.  L<FS::Cron::upload> will then send the spool file to
that destination.

=item balanceover - if set, only spools the invoice if the total amount owed on
this invoice and all older invoices is greater than the specified amount.

=item time - the "current time".  Controls the printing of past due messages
in the ICS format.

=back

=cut

sub spool_csv {
  my($self, %opt) = @_;

  if ( $FS::Misc::DISABLE_ALL_NOTICES ) {
    warn 'spool_csv() disabled by $FS::Misc::DISABLE_ALL_NOTICES' if $DEBUG;
    return;
  }

  my $time = $opt{'time'} || time;
  my $cust_main = $self->cust_main;

  if ( $opt{'dest'} ) {
    my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
                             $cust_main->invoicing_list;
    return 'N/A' unless $invoicing_list{$opt{'dest'}}
                     || ! keys %invoicing_list;
  }

  if ( $opt{'balanceover'} ) {
    return 'N/A'
      if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
  }

  my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
  mkdir $spooldir, 0700 unless -d $spooldir;

  my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);

  my $file;
  if ( $opt{'agent_spools'} ) {
    $file = 'agentnum'.$cust_main->agentnum;
  } else {
    $file = 'spool';
  }

  if ( $opt{'upload_targetnum'} ) {
    $spooldir .= '/target'.$opt{'upload_targetnum'};
    mkdir $spooldir, 0700 unless -d $spooldir;
  } # otherwise it just goes into export.xxx/cust_bill

  if ( lc($opt{'format'}) eq 'billco' ) {
    $file .= '-header';
  }

  $file = "$spooldir/$file.csv";
  
  my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);

  open(CSV, ">>$file") or die "can't open $file: $!";
  flock(CSV, LOCK_EX);
  seek(CSV, 0, 2);

  print CSV $header;

  if ( lc($opt{'format'}) eq 'billco' ) {

    flock(CSV, LOCK_UN);
    close CSV;

    $file =~ s/-header.csv$/-detail.csv/;

    open(CSV,">>$file") or die "can't open $file: $!";
    flock(CSV, LOCK_EX);
    seek(CSV, 0, 2);
  }

  print CSV $detail if defined($detail);

  flock(CSV, LOCK_UN);
  close CSV;

  return '';

}

=item print_csv OPTION => VALUE, ...

Returns CSV data for this invoice.

Options are:

format - 'default', 'billco', 'oneline', 'bridgestone'

Returns a list consisting of two scalars.  The first is a single line of CSV
header information for this invoice.  The second is one or more lines of CSV
detail information for this invoice.

If I<format> is not specified or "default", the fields of the CSV file are as
follows:

record_type, invnum, custnum, _date, charged, first, last, company, address1, 
address2, city, state, zip, country, pkg, setup, recur, sdate, edate

=over 4

=item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>

B<record_type> is C<cust_bill> for the initial header line only.  The
last five fields (B<pkg> through B<edate>) are irrelevant, and all other
fields are filled in.

B<record_type> is C<cust_bill_pkg> for detail lines.  Only the first two fields
(B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
are filled in.

=item invnum - invoice number

=item custnum - customer number

=item _date - invoice date

=item charged - total invoice amount

=item first - customer first name

=item last - customer first name

=item company - company name

=item address1 - address line 1

=item address2 - address line 1

=item city

=item state

=item zip

=item country

=item pkg - line item description

=item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)

=item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)

=item sdate - start date for recurring fee

=item edate - end date for recurring fee

=back

If I<format> is "billco", the fields of the header CSV file are as follows:

  +-------------------------------------------------------------------+
  |                        FORMAT HEADER FILE                         |
  |-------------------------------------------------------------------|
  | Field | Description                   | Name       | Type | Width |
  | 1     | N/A-Leave Empty               | RC         | CHAR |     2 |
  | 2     | N/A-Leave Empty               | CUSTID     | CHAR |    15 |
  | 3     | Transaction Account No        | TRACCTNUM  | CHAR |    15 |
  | 4     | Transaction Invoice No        | TRINVOICE  | CHAR |    15 |
  | 5     | Transaction Zip Code          | TRZIP      | CHAR |     5 |
  | 6     | Transaction Company Bill To   | TRCOMPANY  | CHAR |    30 |
  | 7     | Transaction Contact Bill To   | TRNAME     | CHAR |    30 |
  | 8     | Additional Address Unit Info  | TRADDR1    | CHAR |    30 |
  | 9     | Bill To Street Address        | TRADDR2    | CHAR |    30 |
  | 10    | Ancillary Billing Information | TRADDR3    | CHAR |    30 |
  | 11    | Transaction City Bill To      | TRCITY     | CHAR |    20 |
  | 12    | Transaction State Bill To     | TRSTATE    | CHAR |     2 |
  | 13    | Bill Cycle Close Date         | CLOSEDATE  | CHAR |    10 |
  | 14    | Bill Due Date                 | DUEDATE    | CHAR |    10 |
  | 15    | Previous Balance              | BALFWD     | NUM* |     9 |
  | 16    | Pmt/CR Applied                | CREDAPPLY  | NUM* |     9 |
  | 17    | Total Current Charges         | CURRENTCHG | NUM* |     9 |
  | 18    | Total Amt Due                 | TOTALDUE   | NUM* |     9 |
  | 19    | Total Amt Due                 | AMTDUE     | NUM* |     9 |
  | 20    | 30 Day Aging                  | AMT30      | NUM* |     9 |
  | 21    | 60 Day Aging                  | AMT60      | NUM* |     9 |
  | 22    | 90 Day Aging                  | AMT90      | NUM* |     9 |
  | 23    | Y/N                           | AGESWITCH  | CHAR |     1 |
  | 24    | Remittance automation         | SCANLINE   | CHAR |   100 |
  | 25    | Total Taxes & Fees            | TAXTOT     | NUM* |     9 |
  | 26    | Customer Reference Number     | CUSTREF    | CHAR |    15 |
  | 27    | Federal Tax***                | FEDTAX     | NUM* |     9 |
  | 28    | State Tax***                  | STATETAX   | NUM* |     9 |
  | 29    | Other Taxes & Fees***         | OTHERTAX   | NUM* |     9 |
  +-------+-------------------------------+------------+------+-------+

If I<format> is "billco", the fields of the detail CSV file are as follows:

                                  FORMAT FOR DETAIL FILE
        |                            |           |      |
  Field | Description                | Name      | Type | Width
  1     | N/A-Leave Empty            | RC        | CHAR |     2
  2     | N/A-Leave Empty            | CUSTID    | CHAR |    15
  3     | Account Number             | TRACCTNUM | CHAR |    15
  4     | Invoice Number             | TRINVOICE | CHAR |    15
  5     | Line Sequence (sort order) | LINESEQ   | NUM  |     6
  6     | Transaction Detail         | DETAILS   | CHAR |   100
  7     | Amount                     | AMT       | NUM* |     9
  8     | Line Format Control**      | LNCTRL    | CHAR |     2
  9     | Grouping Code              | GROUP     | CHAR |     2
  10    | User Defined               | ACCT CODE | CHAR |    15

If format is 'oneline', there is no detail file.  Each invoice has a 
header line only, with the fields:

Agent number, agent name, customer number, first name, last name, address
line 1, address line 2, city, state, zip, invoice date, invoice number,
amount charged, amount due, previous balance, due date.

and then, for each line item, three columns containing the package number,
description, and amount.

If format is 'bridgestone', there is no detail file.  Each invoice has a 
header line with the following fields in a fixed-width format:

Customer number (in display format), date, name (first last), company,
address 1, address 2, city, state, zip.

This is a mailing list format, and has no per-invoice fields.  To avoid
sending redundant notices, the spooling event should have a "once" or 
"once_percust_every" condition.

=cut

sub print_csv {
  my($self, %opt) = @_;
  
  eval "use Text::CSV_XS";
  die $@ if $@;

  my $cust_main = $self->cust_main;

  my $csv = Text::CSV_XS->new({'always_quote'=>1});
  my $format = lc($opt{'format'});

  my $time = $opt{'time'} || time;

  $self->set('_template', $opt{template})
    if exists $opt{template};

  my $tracctnum = ''; #leaking out from billco-specific sections :/
  if ( $format eq 'billco' ) {

    my $account_num =
      $self->conf->config('billco-account_num', $cust_main->agentnum);

    $tracctnum = $account_num eq 'display_custnum'
                   ? $cust_main->display_custnum
                   : $opt{'tracctnum'};

    my $taxtotal = 0;
    $taxtotal += $_->{'amount'} foreach $self->_items_tax;

    my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format

    my( $previous_balance, @unused ) = $self->previous; #previous balance

    my $pmt_cr_applied = 0;
    $pmt_cr_applied += $_->{'amount'}
      foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;

    my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);

    $csv->combine(
      '',                         #  1 | N/A-Leave Empty               CHAR   2
      '',                         #  2 | N/A-Leave Empty               CHAR  15
      $tracctnum,                 #  3 | Transaction Account No        CHAR  15
      $self->invnum,              #  4 | Transaction Invoice No        CHAR  15
      $cust_main->zip,            #  5 | Transaction Zip Code          CHAR   5
      $cust_main->company,        #  6 | Transaction Company Bill To   CHAR  30
      #$cust_main->payname,        #  7 | Transaction Contact Bill To   CHAR  30
      $cust_main->contact,        #  7 | Transaction Contact Bill To   CHAR  30
      $cust_main->address2,       #  8 | Additional Address Unit Info  CHAR  30
      $cust_main->address1,       #  9 | Bill To Street Address        CHAR  30
      '',                         # 10 | Ancillary Billing Information CHAR  30
      $cust_main->city,           # 11 | Transaction City Bill To      CHAR  20
      $cust_main->state,          # 12 | Transaction State Bill To     CHAR   2

      # XXX ?
      time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR  10

      # XXX ?
      $duedate,                   # 14 | Bill Due Date                 CHAR  10

      $previous_balance,          # 15 | Previous Balance              NUM*   9
      $pmt_cr_applied,            # 16 | Pmt/CR Applied                NUM*   9
      sprintf("%.2f", $self->charged), # 17 | Total Current Charges    NUM*   9
      $totaldue,                  # 18 | Total Amt Due                 NUM*   9
      $totaldue,                  # 19 | Total Amt Due                 NUM*   9
      '',                         # 20 | 30 Day Aging                  NUM*   9
      '',                         # 21 | 60 Day Aging                  NUM*   9
      '',                         # 22 | 90 Day Aging                  NUM*   9
      'N',                        # 23 | Y/N                           CHAR   1
      '',                         # 24 | Remittance automation         CHAR 100
      $taxtotal,                  # 25 | Total Taxes & Fees            NUM*   9
      $self->custnum,             # 26 | Customer Reference Number     CHAR  15
      '0',                        # 27 | Federal Tax***                NUM*   9
      sprintf("%.2f", $taxtotal), # 28 | State Tax***                  NUM*   9
      '0',                        # 29 | Other Taxes & Fees***         NUM*   9
    );

  } elsif ( $format eq 'oneline' ) { #name
  
    my ($previous_balance) = $self->previous; 
    $previous_balance = sprintf('%.2f', $previous_balance);
    my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
    my @items = map {
                      $_->{pkgnum},
                      $_->{description},
                      $_->{amount}
                    }
                  $self->_items_pkg, #_items_nontax?  no sections or anything
                                     # with this format
                  $self->_items_tax;

    $csv->combine(
      $cust_main->agentnum,
      $cust_main->agent->agent,
      $self->custnum,
      $cust_main->first,
      $cust_main->last,
      $cust_main->company,
      $cust_main->address1,
      $cust_main->address2,
      $cust_main->city,
      $cust_main->state,
      $cust_main->zip,

      # invoice fields
      time2str("%x", $self->_date),
      $self->invnum,
      $self->charged,
      $totaldue,
      $previous_balance,
      $self->due_date2str("%x"),

      @items,
    );

  } elsif ( $format eq 'bridgestone' ) {

    # bypass the CSV stuff and just return this
    my $longdate = time2str('%B %d, %Y', $time); #current time, right?
    my $zip = $cust_main->zip;
    $zip =~ s/\D//;
    my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
      || '';
    return (
      sprintf(
        "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
        $prefix,
        $cust_main->display_custnum,
        $longdate,
        uc(substr($cust_main->contact_firstlast,0,30)),
        uc(substr($cust_main->company          ,0,30)),
        uc(substr($cust_main->address1         ,0,30)),
        uc(substr($cust_main->address2         ,0,30)),
        uc(substr($cust_main->city             ,0,20)),
        uc($cust_main->state),
        $zip
      ),
      '' #detail
      );

  } elsif ( $format eq 'ics' ) {

    my $bill = $cust_main->bill_location;
    my $zip = $bill->zip;
    my $zip4 = '';

    $zip =~ s/\D//;
    if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
      $zip = $1;
      $zip4 = $2;
    }

    # minor false laziness with print_generic
    my ($previous_balance) = $self->previous;
    my $balance_due = $self->owed + $previous_balance;
    my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
    my $credit_total  = sum(0, map { $_->{'amount'} } $self->_items_credits);

    my $past_due = '';
    if ( $self->due_date and $time >= $self->due_date ) {
      $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
    }

    # again, bypass CSV
    my $header = sprintf(
      '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
      $cust_main->display_custnum, #BID
      uc($cust_main->first), #FNAME
      uc($cust_main->last), #LNAME
      '00', #BATCH, should this ever be anything else?
      uc($cust_main->company), #COMP
      uc($bill->address1), #STREET1
      uc($bill->address2), #STREET2
      uc($bill->city), #CITY
      uc($bill->state), #STATE
      $zip,
      $zip4,
      time2str('%Y%m%d', $self->_date), #BILL_DATE
      $self->due_date2str('%Y%m%d'), #DUE_DATE,
      ( map {sprintf('%0.2f', $_)}
        $balance_due, #AMNT_DUE
        $previous_balance, #PREV_BAL
        $payment_total, #PYMT_RCVD
        $credit_total, #CREDITS
        $previous_balance, #BEG_BAL--is this correct?
        $self->charged, #NEW_CHRG
      ),
      'img01', #MRKT_MSG?
      $past_due, #PAST_MSG
    );

    my @details;
    my %svc_class = ('' => ''); # maybe cache this more persistently?

    foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {

      my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
      my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;

      if ( $cust_pkg ) {

        my @dates = ( $self->_date, undef );
        if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
          $dates[1] = $prev->sdate; #questionable
        }

        # generate an 01 detail for each service
        my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
        foreach my $cust_svc ( @svcs ) {
          $show_pkgnum = ''; # hide it if we're showing svcnums

          my $svcpart = $cust_svc->svcpart;
          if (!exists($svc_class{$svcpart})) {
            my $classnum = $cust_svc->part_svc->classnum;
            my $part_svc_class = FS::part_svc_class->by_key($classnum)
              if $classnum;
            $svc_class{$svcpart} = $part_svc_class ? 
                                   $part_svc_class->classname :
                                   '';
          }

          my @h_label = $cust_svc->label(@dates, 'I');
          push @details, sprintf('01%-9s%-20s%-47s',
            $cust_svc->svcnum,
            $svc_class{$svcpart},
            $h_label[1],
          );
        } #foreach $cust_svc
      } #if $cust_pkg

      my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
      if ($cust_bill_pkg->recur > 0) {
        $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
                     time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
      }
      push @details, sprintf('02%-6s%-60s%-10s',
        $show_pkgnum,
        $desc,
        sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
      );
    } #foreach $cust_bill_pkg

    # Tag this row so that we know whether this is one page (1), two pages
    # (2), # or "big" (B).  The tag will be stripped off before uploading.
    if ( scalar(@details) < 12 ) {
      push @details, '1';
    } elsif ( scalar(@details) < 58 ) {
      push @details, '2';
    } else {
      push @details, 'B';
    }

    return join('', $header, @details, "\n");

  } else { # default
  
    $csv->combine(
      'cust_bill',
      $self->invnum,
      $self->custnum,
      time2str("%x", $self->_date),
      sprintf("%.2f", $self->charged),
      ( map { $cust_main->getfield($_) }
          qw( first last company address1 address2 city state zip country ) ),
      map { '' } (1..5),
    ) or die "can't create csv";
  }

  my $header = $csv->string. "\n";

  my $detail = '';
  if ( lc($opt{'format'}) eq 'billco' ) {

    my $lineseq = 0;
    my %items_opt = ( format => 'template',
                      escape_function => sub { shift } );
    # I don't know what characters billco actually tolerates in spool entries.
    # Text::CSV will take care of delimiters, though.

    my @items = ( $self->_items_pkg(%items_opt),
                  $self->_items_fee(%items_opt) );
    foreach my $item (@items) {

      my $description = $item->{'description'};
      if ( $item->{'_is_discount'} and exists($item->{ext_description}[0]) ) {
        $description .= ': ' . $item->{ext_description}[0];
      }

      $csv->combine(
        '',                     #  1 | N/A-Leave Empty            CHAR   2
        '',                     #  2 | N/A-Leave Empty            CHAR  15
        $tracctnum,             #  3 | Account Number             CHAR  15
        $self->invnum,          #  4 | Invoice Number             CHAR  15
        $lineseq++,             #  5 | Line Sequence (sort order) NUM    6
        $description,           #  6 | Transaction Detail         CHAR 100
        $item->{'amount'},      #  7 | Amount                     NUM*   9
        '',                     #  8 | Line Format Control**      CHAR   2
        '',                     #  9 | Grouping Code              CHAR   2
        '',                     # 10 | User Defined               CHAR  15
      );

      $detail .= $csv->string. "\n";

    }

  } elsif ( lc($opt{'format'}) eq 'oneline' ) {

    #do nothing

  } else {

    foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {

      my($pkg, $setup, $recur, $sdate, $edate);
      if ( $cust_bill_pkg->pkgnum ) {
      
        ($pkg, $setup, $recur, $sdate, $edate) = (
          $cust_bill_pkg->part_pkg->pkg,
          ( $cust_bill_pkg->setup != 0
            ? sprintf("%.2f", $cust_bill_pkg->setup )
            : '' ),
          ( $cust_bill_pkg->recur != 0
            ? sprintf("%.2f", $cust_bill_pkg->recur )
            : '' ),
          ( $cust_bill_pkg->sdate 
            ? time2str("%x", $cust_bill_pkg->sdate)
            : '' ),
          ($cust_bill_pkg->edate 
            ? time2str("%x", $cust_bill_pkg->edate)
            : '' ),
        );
  
      } else { #pkgnum tax
        next unless $cust_bill_pkg->setup != 0;
        $pkg = $cust_bill_pkg->desc;
        $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
        ( $sdate, $edate ) = ( '', '' );
      }
  
      $csv->combine(
        'cust_bill_pkg',
        $self->invnum,
        ( map { '' } (1..11) ),
        ($pkg, $setup, $recur, $sdate, $edate)
      ) or die "can't create csv";

      $detail .= $csv->string. "\n";

    }

  }

  ( $header, $detail );

}

sub comp {
  croak 'cust_bill->comp is deprecated (COMP payments are deprecated)';
}

=item realtime_card

Attempts to pay this invoice with a credit card payment via a
Business::OnlinePayment realtime gateway.  See
http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
for supported processors.

=cut

sub realtime_card {
  my $self = shift;
  $self->realtime_bop( 'CC', @_ );
}

=item realtime_ach

Attempts to pay this invoice with an electronic check (ACH) payment via a
Business::OnlinePayment realtime gateway.  See
http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
for supported processors.

=cut

sub realtime_ach {
  my $self = shift;
  $self->realtime_bop( 'ECHECK', @_ );
}

=item realtime_lec

Attempts to pay this invoice with phone bill (LEC) payment via a
Business::OnlinePayment realtime gateway.  See
http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
for supported processors.

=cut

sub realtime_lec {
  my $self = shift;
  $self->realtime_bop( 'LEC', @_ );
}

sub realtime_bop {
  my( $self, $method ) = (shift,shift);
  my $conf = $self->conf;
  my %opt = @_;

  my $cust_main = $self->cust_main;
  my $balance = $cust_main->balance;
  my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
  $amount = sprintf("%.2f", $amount);
  return "not run (balance $balance)" unless $amount > 0;

  my $description = 'Internet Services';
  if ( $conf->exists('business-onlinepayment-description') ) {
    my $dtempl = $conf->config('business-onlinepayment-description');

    my $agent_obj = $cust_main->agent
      or die "can't retreive agent for $cust_main (agentnum ".
             $cust_main->agentnum. ")";
    my $agent = $agent_obj->agent;
    my $pkgs = join(', ',
      map { $_->part_pkg->pkg }
        grep { $_->pkgnum } $self->cust_bill_pkg
    );
    $description = eval qq("$dtempl");
  }

  $cust_main->realtime_bop($method, $amount,
    'description' => $description,
    'invnum'      => $self->invnum,
#this didn't do what we want, it just calls apply_payments_and_credits
#    'apply'       => 1,
    'apply_to_invoice' => 1,
    %opt,
 #what we want:
 #this changes application behavior: auto payments
                        #triggered against a specific invoice are now applied
                        #to that invoice instead of oldest open.
                        #seem okay to me...
  );

}

=item batch_card OPTION => VALUE...

Adds a payment for this invoice to the pending credit card batch (see
L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
runs the payment using a realtime gateway.

=cut

sub batch_card {
  my ($self, %options) = @_;
  my $cust_main = $self->cust_main;

  $options{invnum} = $self->invnum;
  
  $cust_main->batch_card(%options);
}

sub _agent_template {
  my $self = shift;
  $self->cust_main->agent_template;
}

sub _agent_invoice_from {
  my $self = shift;
  $self->cust_main->agent_invoice_from;
}

=item invoice_barcode DIR_OR_FALSE

Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
it is taken as the temp directory where the PNG file will be generated and the
PNG file name is returned. Otherwise, the PNG image itself is returned.

=cut

sub invoice_barcode {
    my ($self, $dir) = (shift,shift);
    
    my $gdbar = new GD::Barcode('Code39',$self->invnum);
	die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
    my $gd = $gdbar->plot(Height => 30);

    if($dir) {
	my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
			   DIR      => $dir,
			   SUFFIX   => '.png',
			   UNLINK   => 0,
			 ) or die "can't open temp file: $!\n";
	print $bh $gd->png or die "cannot write barcode to file: $!\n";
	my $png_file = $bh->filename;
	close $bh;
	return $png_file;
    }
    return $gd->png;
}

=item invnum_date_pretty

Returns a string with the invoice number and date, for example:
"Invoice #54 (3/20/2008)".

Intended for back-end context, with regard to translation and date formatting.

=cut

#note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
# for backend use (and also does the wrong thing, localizing for end customer
# instead of backoffice configured date format)
sub invnum_date_pretty {
  my $self = shift;
  #$self->mt('Invoice #').
  'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
    $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
}

#sub _items_extra_usage_sections {
#  my $self = shift;
#  my $escape = shift;
#
#  my %sections = ();
#
#  my %usage_class =  map{ $_->classname, $_ } qsearch('usage_class', {});
#  foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
#  {
#    next unless $cust_bill_pkg->pkgnum > 0;
#
#    foreach my $section ( keys %usage_class ) {
#
#      my $usage = $cust_bill_pkg->usage($section);
#
#      next unless $usage && $usage > 0;
#
#      $sections{$section} ||= 0;
#      $sections{$section} += $usage;
#
#    }
#
#  }
#
#  map { { 'description' => &{$escape}($_),
#          'subtotal'    => $sections{$_},
#          'summarized'  => '',
#          'tax_section' => '',
#        }
#      }
#    sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
#
#}

sub _items_extra_usage_sections {
  my $self = shift;
  my $conf = $self->conf;
  my $escape = shift;
  my $format = shift;

  my %sections = ();
  my %classnums = ();
  my %lines = ();

  my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;

  my %usage_class =  map { $_->classnum => $_ } qsearch( 'usage_class', {} );
  foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
    next unless $cust_bill_pkg->pkgnum > 0;

    foreach my $classnum ( keys %usage_class ) {
      my $section = $usage_class{$classnum}->classname;
      $classnums{$section} = $classnum;

      foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
        my $amount = $detail->amount;
        next unless $amount && $amount > 0;
 
        $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
        $sections{$section}{amount} += $amount;  #subtotal
        $sections{$section}{calls}++;
        $sections{$section}{duration} += $detail->duration;

        my $desc = $detail->regionname; 
        my $description = $desc;
        $description = substr($desc, 0, $maxlength). '...'
          if $format eq 'latex' && length($desc) > $maxlength;

        $lines{$section}{$desc} ||= {
          description     => &{$escape}($description),
          #pkgpart         => $part_pkg->pkgpart,
          pkgnum          => $cust_bill_pkg->pkgnum,
          ref             => '',
          amount          => 0,
          calls           => 0,
          duration        => 0,
          #unit_amount     => $cust_bill_pkg->unitrecur,
          quantity        => $cust_bill_pkg->quantity,
          product_code    => 'N/A',
          ext_description => [],
        };

        $lines{$section}{$desc}{amount} += $amount;
        $lines{$section}{$desc}{calls}++;
        $lines{$section}{$desc}{duration} += $detail->duration;

      }
    }
  }

  my %sectionmap = ();
  foreach (keys %sections) {
    my $usage_class = $usage_class{$classnums{$_}};
    $sectionmap{$_} = { 'description' => &{$escape}($_),
                        'amount'    => $sections{$_}{amount},    #subtotal
                        'calls'       => $sections{$_}{calls},
                        'duration'    => $sections{$_}{duration},
                        'summarized'  => '',
                        'tax_section' => '',
                        'sort_weight' => $usage_class->weight,
                        ( $usage_class->format
                          ? ( map { $_ => $usage_class->$_($format) }
                              qw( description_generator header_generator total_generator total_line_generator )
                            )
                          : ()
                        ), 
                      };
  }

  my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
                 values %sectionmap;

  my @lines = ();
  foreach my $section ( keys %lines ) {
    foreach my $line ( keys %{$lines{$section}} ) {
      my $l = $lines{$section}{$line};
      $l->{section}     = $sectionmap{$section};
      $l->{amount}      = sprintf( "%.2f", $l->{amount} );
      #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
      push @lines, $l;
    }
  }

  return(\@sections, \@lines);

}

sub _did_summary {
    my $self = shift;
    my $end = $self->_date;

    # start at date of previous invoice + 1 second or 0 if no previous invoice
    my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
    $start = 0 if !$start;
    $start++;

    my $cust_main = $self->cust_main;
    my @pkgs = $cust_main->all_pkgs;
    my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
	= (0,0,0,0,0);
    my @seen = ();
    foreach my $pkg ( @pkgs ) {
	my @h_cust_svc = $pkg->h_cust_svc($end);
	foreach my $h_cust_svc ( @h_cust_svc ) {
	    next if grep {$_ eq $h_cust_svc->svcnum} @seen;
	    next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';

	    my $inserted = $h_cust_svc->date_inserted;
	    my $deleted = $h_cust_svc->date_deleted;
	    my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
	    my $phone_deleted;
	    $phone_deleted =  $h_cust_svc->h_svc_x($deleted) if $deleted;
	    
# DID either activated or ported in; cannot be both for same DID simultaneously
	    if ($inserted >= $start && $inserted <= $end && $phone_inserted
		&& (!$phone_inserted->lnp_status 
		    || $phone_inserted->lnp_status eq ''
		    || $phone_inserted->lnp_status eq 'native')) {
		$num_activated++;
	    }
	    else { # this one not so clean, should probably move to (h_)svc_phone
                 local($FS::Record::qsearch_qualify_columns) = 0;
		 my $phone_portedin = qsearchs( 'h_svc_phone',
		      { 'svcnum' => $h_cust_svc->svcnum, 
			'lnp_status' => 'portedin' },  
		      FS::h_svc_phone->sql_h_searchs($end),  
		    );
		 $num_portedin++ if $phone_portedin;
	    }

# DID either deactivated or ported out;	cannot be both for same DID simultaneously
	    if($deleted >= $start && $deleted <= $end && $phone_deleted
		&& (!$phone_deleted->lnp_status 
		    || $phone_deleted->lnp_status ne 'portingout')) {
		$num_deactivated++;
	    } 
	    elsif($deleted >= $start && $deleted <= $end && $phone_deleted 
		&& $phone_deleted->lnp_status 
		&& $phone_deleted->lnp_status eq 'portingout') {
		$num_portedout++;
	    }

	    # increment usage minutes
        if ( $phone_inserted ) {
            my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
            $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
        }
        else {
            warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
        }

	    # don't look at this service again
	    push @seen, $h_cust_svc->svcnum;
	}
    }

    $minutes = sprintf("%d", $minutes);
    ("Activated: $num_activated  Ported-In: $num_portedin  Deactivated: "
	. "$num_deactivated  Ported-Out: $num_portedout ",
	    "Total Minutes: $minutes");
}

sub _items_accountcode_cdr {
    my $self = shift;
    my $escape = shift;
    my $format = shift;

    my $section = { 'amount'        => 0,
                    'calls'         => 0,
                    'duration'      => 0,
                    'sort_weight'   => '',
                    'phonenum'      => '',
                    'description'   => 'Usage by Account Code',
                    'post_total'    => '',
                    'summarized'    => '',
                    'header'        => '',
                  };
    my @lines;
    my %accountcodes = ();

    foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
        next unless $cust_bill_pkg->pkgnum > 0;

        my @header = $cust_bill_pkg->details_header;
        next unless scalar(@header);
        $section->{'header'} = join(',',@header);

        foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {

            $section->{'header'} = $detail->formatted('format' => $format)
                if($detail->detail eq $section->{'header'}); 
      
            my $accountcode = $detail->accountcode;
            next unless $accountcode;

            my $amount = $detail->amount;
            next unless $amount && $amount > 0;

            $accountcodes{$accountcode} ||= {
                    description => $accountcode,
                    pkgnum      => '',
                    ref         => '',
                    amount      => 0,
                    calls       => 0,
                    duration    => 0,
                    quantity    => '',
                    product_code => 'N/A',
                    section     => $section,
                    ext_description => [ $section->{'header'} ],
                    detail_temp => [],
            };

            $section->{'amount'} += $amount;
            $accountcodes{$accountcode}{'amount'} += $amount;
            $accountcodes{$accountcode}{calls}++;
            $accountcodes{$accountcode}{duration} += $detail->duration;
            push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
        }
    }

    foreach my $l ( values %accountcodes ) {
        $l->{amount} = sprintf( "%.2f", $l->{amount} );
        my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
        foreach my $sorted_detail ( @sorted_detail ) {
            push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
        }
        delete $l->{detail_temp};
        push @lines, $l;
    }

    my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;

    return ($section,\@sorted_lines);
}

sub _items_svc_phone_sections {
  my $self = shift;
  my $conf = $self->conf;
  my $escape = shift;
  my $format = shift;

  my %sections = ();
  my %classnums = ();
  my %lines = ();

  my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;

  my %usage_class =  map { $_->classnum => $_ } qsearch( 'usage_class', {} );
  $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };

  foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
    next unless $cust_bill_pkg->pkgnum > 0;

    my @header = $cust_bill_pkg->details_header;
    next unless scalar(@header);

    foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {

      my $phonenum = $detail->phonenum;
      next unless $phonenum;

      my $amount = $detail->amount;
      next unless $amount && $amount > 0;

      $sections{$phonenum} ||= { 'amount'      => 0,
                                 'calls'       => 0,
                                 'duration'    => 0,
                                 'sort_weight' => -1,
                                 'phonenum'    => $phonenum,
                                };
      $sections{$phonenum}{amount} += $amount;  #subtotal
      $sections{$phonenum}{calls}++;
      $sections{$phonenum}{duration} += $detail->duration;

      my $desc = $detail->regionname; 
      my $description = $desc;
      $description = substr($desc, 0, $maxlength). '...'
        if $format eq 'latex' && length($desc) > $maxlength;

      $lines{$phonenum}{$desc} ||= {
        description     => &{$escape}($description),
        #pkgpart         => $part_pkg->pkgpart,
        pkgnum          => '',
        ref             => '',
        amount          => 0,
        calls           => 0,
        duration        => 0,
        #unit_amount     => '',
        quantity        => '',
        product_code    => 'N/A',
        ext_description => [],
      };

      $lines{$phonenum}{$desc}{amount} += $amount;
      $lines{$phonenum}{$desc}{calls}++;
      $lines{$phonenum}{$desc}{duration} += $detail->duration;

      my $line = $usage_class{$detail->classnum}->classname;
      $sections{"$phonenum $line"} ||=
        { 'amount' => 0,
          'calls' => 0,
          'duration' => 0,
          'sort_weight' => $usage_class{$detail->classnum}->weight,
          'phonenum' => $phonenum,
          'header'  => [ @header ],
        };
      $sections{"$phonenum $line"}{amount} += $amount;  #subtotal
      $sections{"$phonenum $line"}{calls}++;
      $sections{"$phonenum $line"}{duration} += $detail->duration;

      $lines{"$phonenum $line"}{$desc} ||= {
        description     => &{$escape}($description),
        #pkgpart         => $part_pkg->pkgpart,
        pkgnum          => '',
        ref             => '',
        amount          => 0,
        calls           => 0,
        duration        => 0,
        #unit_amount     => '',
        quantity        => '',
        product_code    => 'N/A',
        ext_description => [],
      };

      $lines{"$phonenum $line"}{$desc}{amount} += $amount;
      $lines{"$phonenum $line"}{$desc}{calls}++;
      $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
      push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
           $detail->formatted('format' => $format);

    }
  }

  my %sectionmap = ();
  my $simple = new FS::usage_class { format => 'simple' }; #bleh
  foreach ( keys %sections ) {
    my @header = @{ $sections{$_}{header} || [] };
    my $usage_simple =
      new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
    my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
    my $usage_class = $summary ? $simple : $usage_simple;
    my $ending = $summary ? ' usage charges' : '';
    my %gen_opt = ();
    unless ($summary) {
      $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
    }
    $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
                        'amount'    => $sections{$_}{amount},    #subtotal
                        'calls'       => $sections{$_}{calls},
                        'duration'    => $sections{$_}{duration},
                        'summarized'  => '',
                        'tax_section' => '',
                        'phonenum'    => $sections{$_}{phonenum},
                        'sort_weight' => $sections{$_}{sort_weight},
                        'post_total'  => $summary, #inspire pagebreak
                        (
                          ( map { $_ => $usage_class->$_($format, %gen_opt) }
                            qw( description_generator
                                header_generator
                                total_generator
                                total_line_generator
                              )
                          )
                        ), 
                      };
  }

  my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
                        $a->{sort_weight} <=> $b->{sort_weight}
                      }
                 values %sectionmap;

  my @lines = ();
  foreach my $section ( keys %lines ) {
    foreach my $line ( keys %{$lines{$section}} ) {
      my $l = $lines{$section}{$line};
      $l->{section}     = $sectionmap{$section};
      $l->{amount}      = sprintf( "%.2f", $l->{amount} );
      #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
      push @lines, $l;
    }
  }
  
  if($conf->exists('phone_usage_class_summary')) { 
      # this only works with Latex
      my @newlines;
      my @newsections;

      # after this, we'll have only two sections per DID:
      # Calls Summary and Calls Detail
      foreach my $section ( @sections ) {
	if($section->{'post_total'}) {
	    $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
	    $section->{'total_line_generator'} = sub { '' };
	    $section->{'total_generator'} = sub { '' };
	    $section->{'header_generator'} = sub { '' };
	    $section->{'description_generator'} = '';
	    push @newsections, $section;
	    my %calls_detail = %$section;
	    $calls_detail{'post_total'} = '';
	    $calls_detail{'sort_weight'} = '';
	    $calls_detail{'description_generator'} = sub { '' };
	    $calls_detail{'header_generator'} = sub {
		return ' & Date/Time & Called Number & Duration & Price'
		    if $format eq 'latex';
		'';
	    };
	    $calls_detail{'description'} = 'Calls Detail: '
						    . $section->{'phonenum'};
	    push @newsections, \%calls_detail;	
	}
      }

      # after this, each usage class is collapsed/summarized into a single
      # line under the Calls Summary section
      foreach my $newsection ( @newsections ) {
	if($newsection->{'post_total'}) { # this means Calls Summary
	    foreach my $section ( @sections ) {
		next unless ($section->{'phonenum'} eq $newsection->{'phonenum'} 
				&& !$section->{'post_total'});
		my $newdesc = $section->{'description'};
		my $tn = $section->{'phonenum'};
		$newdesc =~ s/$tn//g;
		my $line = {  ext_description => [],
			      pkgnum => '',
			      ref => '',
			      quantity => '',
			      calls => $section->{'calls'},
			      section => $newsection,
			      duration => $section->{'duration'},
			      description => $newdesc,
			      amount => sprintf("%.2f",$section->{'amount'}),
			      product_code => 'N/A',
			    };
		push @newlines, $line;
	    }
	}
      }

      # after this, Calls Details is populated with all CDRs
      foreach my $newsection ( @newsections ) {
	if(!$newsection->{'post_total'}) { # this means Calls Details
	    foreach my $line ( @lines ) {
		next unless (scalar(@{$line->{'ext_description'}}) &&
			$line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
			    );
		my @extdesc = @{$line->{'ext_description'}};
		my @newextdesc;
		foreach my $extdesc ( @extdesc ) {
		    $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
		    push @newextdesc, $extdesc;
		}
		$line->{'ext_description'} = \@newextdesc;
		$line->{'section'} = $newsection;
		push @newlines, $line;
	    }
	}
      }

      return(\@newsections, \@newlines);
  }

  return(\@sections, \@lines);

}

=item _items_usage_class_summary OPTIONS

Returns a list of detail items summarizing the usage charges on this 
invoice.  Each one will have 'amount', 'description' (the usage charge name),
and 'usage_classnum'.

OPTIONS can include 'escape' (a function to escape the descriptions).

=cut

sub _items_usage_class_summary {
  my $self = shift;
  my %opt = @_;

  my $escape = $opt{escape} || sub { $_[0] };
  my $money_char = $opt{money_char};
  my $invnum = $self->invnum;
  my @classes = qsearch({
      'table'     => 'usage_class',
      'select'    => 'classnum, classname, SUM(amount) AS amount,'.
                     ' COUNT(*) AS calls, SUM(duration) AS duration',
      'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
                     ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
      'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
                     ' GROUP BY classnum, classname, weight'.
                     ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
                     ' ORDER BY weight ASC',
  });
  my @l;
  my $section = {
    description   => &{$escape}($self->mt('Usage Summary')),
    usage_section => 1,
    subtotal      => 0,
  };
  foreach my $class (@classes) {
    $section->{subtotal} += $class->get('amount');
    push @l, {
      'description'     => &{$escape}($class->classname),
      'amount'          => $money_char.sprintf('%.2f', $class->get('amount')),
      'quantity'        => $class->get('calls'),
      'duration'        => $class->get('duration'),
      'usage_classnum'  => $class->classnum,
      'section'         => $section,
    };
  }
  $section->{subtotal} = $money_char.sprintf('%.2f', $section->{subtotal});
  return @l;
}

=item _items_previous()

  Returns an array of hashrefs, each hashref representing a line-item on
  the current bill for previous unpaid invoices.

  keys for each previous_item:
  - amount (see notes)
  - pkgnum
  - description
  - invnum
  - _date

  Payments and credits shown on this invoice may vary based on configuraiton.

  when conf flag previous_balance-payments_since is set:
    This method works backwards to rebuild the invoice as a snapshot in time.
    The invoice displayed will have the balances owed, and payments made,
    reflecting the state of the account at the time of invoice generation.

=cut

sub _items_previous {

  my $self = shift;

  # simple memoize
  if ($self->get('_items_previous')) {
    return sort { $a->{_date} <=> $b->{_date} }
         values %{ $self->get('_items_previous') };
  }

  # Gets the customer's current balance and outstanding invoices.
  my ($prev_balance, @open_invoices) = $self->previous;

  my %invoices = map {
    $_->invnum => $self->__items_previous_map_invoice($_)
  } @open_invoices;

  # Which credits and payments displayed on the bill will vary based on
  # conf flag previous_balance-payments_since.
  my @credits  = $self->_items_credits();
  my @payments = $self->_items_payments();


  if ($self->conf->exists('previous_balance-payments_since')) {
    # For each credit or payment, determine which invoices it was applied to.
    # Manipulate data displayed so the invoice displayed appears as a
    # snapshot in time... with previous balances and balance owed displayed
    # as they were at the time of invoice creation.

    my @credits_postbill = $self->_items_credits_postbill();
    my @payments_postbill = $self->_items_payments_postbill();

    my %pmnt_dupechk;
    my %cred_dupechk;

    # Each section below follows this pattern on a payment/credit
    #
    # - Dupe check, avoid adjusting for the same item twice
    # - If invoice being adjusted for isn't in our list, add it
    # - Adjust the invoice balance to refelct balnace without the
    #   credit or payment applied
    #

    # Working with payments displayed on this bill
    for my $pmt_hash (@payments) {
      my $pmt_obj = qsearchs('cust_pay', {paynum => $pmt_hash->{paynum}});
      for my $cust_bill_pay ($pmt_obj->cust_bill_pay) {
        next if exists $pmnt_dupechk{$cust_bill_pay->billpaynum};
        $pmnt_dupechk{$cust_bill_pay->billpaynum} = 1;

        my $invnum = $cust_bill_pay->invnum;

        $invoices{$invnum} = $self->__items_previous_get_invoice($invnum)
          unless exists $invoices{$invnum};

        $invoices{$invnum}->{amount} += $cust_bill_pay->amount;
      }
    }

    # Working with credits displayed on this bill
    for my $cred_hash (@credits) {
      my $cred_obj = qsearchs('cust_credit', {crednum => $cred_hash->{crednum}});
      for my $cust_credit_bill ($cred_obj->cust_credit_bill) {
        next if exists $cred_dupechk{$cust_credit_bill->creditbillnum};
        $cred_dupechk{$cust_credit_bill->creditbillnum} = 1;

        my $invnum = $cust_credit_bill->invnum;

        $invoices{$invnum} = $self->__items_previous_get_invoice($invnum)
          unless exists $invoices{$invnum};

        $invoices{$invnum}->{amount} += $cust_credit_bill->amount;
      }
    }

    # Working with both credits and payments which are not displayed
    # on this bill, but which have affected this bill's balances
    for my $postbill (@payments_postbill, @credits_postbill) {

      if ($postbill->{billpaynum}) {
        next if exists $pmnt_dupechk{$postbill->{billpaynum}};
        $pmnt_dupechk{$postbill->{billpaynum}} = 1;
      } elsif ($postbill->{creditbillnum}) {
        next if exists $cred_dupechk{$postbill->{creditbillnum}};
        $cred_dupechk{$postbill->{creditbillnum}} = 1;
      } else {
        die "Missing creditbillnum or billpaynum";
      }

      my $invnum = $postbill->{invnum};

      $invoices{$invnum} = $self->__items_previous_get_invoice($invnum)
        unless exists $invoices{$invnum};

      $invoices{$invnum}->{amount} += $postbill->{amount};
    }

    # Make sure current invoice doesn't appear in previous items
    delete $invoices{$self->invnum}
      if exists $invoices{$self->invnum};

  }

  # Make sure amount is formatted as a dollar string
  # (Formatting should happen on the template side, but is not?)
  $invoices{$_}->{amount} = sprintf('%.2f',$invoices{$_}->{amount})
    for keys %invoices;

  $self->set('_items_previous', \%invoices);
  return sort { $a->{_date} <=> $b->{_date} } values %invoices;

}

=item _items_previous_total

  Return sum of amounts from all items returned by _items_previous
  Results will vary based on invoicing conf flags

=cut

sub _items_previous_total {
  my $self = shift;
  my $tot = 0;
  $tot += $_->{amount} for $self->_items_previous();
  return $tot;
}

sub __items_previous_get_invoice {
  # Helper function for _items_previous
  #
  # Read a record from cust_bill, return a hash of it's information
  my ($self, $invnum) = @_;
  die "Incorrect usage of __items_previous_get_invoice()" unless $invnum;

  my $cust_bill = qsearchs('cust_bill', {invnum => $invnum});
  return $self->__items_previous_map_invoice($cust_bill);
}

sub __items_previous_map_invoice {
  # Helper function for _items_previous
  #
  # Transform a cust_bill object into a simple hash reference of the type
  # required by _items_previous
  my ($self, $cust_bill) = @_;
  die "Incorrect usage of __items_previous_map_invoice" unless ref $cust_bill;

  my $date = $self->conf->exists('invoice_show_prior_due_date')
           ? 'due '.$cust_bill->due_date2str('short')
           : $self->time2str_local('short', $cust_bill->_date);

  return {
    invnum => $cust_bill->invnum,
    amount => $cust_bill->owed,
    pkgnum => 'N/A',
    _date  => $cust_bill->_date,
    description => join(' ',
      $self->mt('Previous Balance, Invoice #'),
      $cust_bill->invnum,
      "($date)"
    ),
  }
}

=item _items_credits()

  Return array of hashrefs containing credits to be shown as line-items
  when rendering this bill.

  keys for each credit item:
  - crednum: id of payment
  - amount: payment amount
  - description: line item to be displayed on the bill

  This method has three ways it selects which credits to display on
  this bill:

  1) Default Case: No Conf flag for 'previous_balance-payments_since'

     Returns credits that have been applied to this bill only

  2) Case:
       Conf flag set for 'previous_balance-payments_since'

     List all credits that have been recorded during the time period
     between the timestamps of the last invoice and this invoice

  3) Case:
        Conf flag set for 'previous_balance-payments_since'
        $opt{'template'} eq 'statement'

    List all payments that have been recorded between the timestamps
    of the previous invoice and the following invoice.

     This is used to give the customer a receipt for a payment
     in the form of their last bill with the payment amended.

     I am concerned with this implementation, but leaving in place as is
     If this option is selected, while viewing an older bill, the old bill
     will show ALL future credits for future bills, but no charges for
     future bills.  Somebody could be misled into believing they have a
     large account credit when they don't.  Also, interrupts the chain of
     invoices as an account history... the customer could have two invoices
     in their fileing cabinet, for two different dates, both with a line item
     for the same duplicate credit.  The accounting is technically accurate,
     but somebody could easily become confused and think two credits were
     made, when really those two line items on two different bills represent
     only a single credit

=cut

sub _items_credits {

  my $self= shift;

  # Simple memoize
  return @{$self->get('_items_credits')} if $self->get('_items_credits');

  my %opt = @_;
  my $template = $opt{template} || $self->get('_template');
  my $trim_len = $opt{template} || $self->get('trim_len') || 40;

  my @return;
  my @cust_credit_objs;

  if ( $self->conf->exists('previous_balance-payments_since') ) {
    if ($template eq 'statement') {
      # Case 3 (see above)
      # Return credits timestamped between the previous and following bills

      my $previous_bill  = $self->previous_bill;
      my $following_bill = $self->following_bill;

      my $date_start = ref $previous_bill  ? $previous_bill->_date  : 0;
      my $date_end   = ref $following_bill ? $following_bill->_date : undef;

      my %query = (
        table => 'cust_credit',
        hashref => {
          custnum => $self->custnum,
          _date => { op => '>=', value => $date_start },
        },
      );
      $query{extra_sql} = " AND _date <= $date_end " if $date_end;

      @cust_credit_objs = qsearch(\%query);

    } else {
      # Case 2 (see above)
      # Return credits timestamps between this and the previous bills

      my $date_start = 0;
      my $date_end = $self->_date;

      my $previous_bill = $self->previous_bill;
      if (ref $previous_bill) {
        $date_start = $previous_bill->_date;
      }

      @cust_credit_objs = qsearch({
        table => 'cust_credit',
        hashref => {
          custnum => $self->custnum,
          _date => {op => '>=', value => $date_start},
        },
        extra_sql => " AND _date <= $date_end ",
      });
    }

  } else {
    # Case 1 (see above)
    # Return only credits that have been applied to this bill

    @cust_credit_objs = $self->cust_credited;

  }

  # Translate objects into hashrefs
  foreach my $obj ( @cust_credit_objs ) {
    my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
    my %r_obj = (
      amount       => sprintf('%.2f',$cust_credit->amount),
      crednum      => $cust_credit->crednum,
      _date        => $cust_credit->_date,
      creditreason => $cust_credit->reason,
    );

    my $reason = substr($cust_credit->reason, 0, $trim_len);
    $reason .= '...' if length($reason) < length($cust_credit->reason);
    $reason = " ($reason) " if $reason;

    $r_obj{description} = join(' ',
      $self->mt('Credit applied'),
      $self->time2str_local('short', $cust_credit->_date),
      $reason,
    );

    push @return, \%r_obj;
  }
  $self->set('_items_credits',\@return);
  @return;
  }

=item _items_credits_total

  Return the total of al items from _items_credits
  Will vary based on invoice display conf flag

=cut

sub _items_credits_total {
  my $self = shift;
  my $tot = 0;
  $tot += $_->{amount} for $self->_items_credits();
  return $tot;
}



=item _items_credits_postbill()

  Returns an array of hashrefs for credits where
  - Credit issued after this invoice
  - Credit applied to an invoice before this invoice

  Returned hashrefs are of the format returned by _items_credits()

=cut

sub _items_credits_postbill {
  my $self = shift;

  my @cust_credit_bill = qsearch({
    table   => 'cust_credit_bill',
    select  => join(', ',qw(
      cust_credit_bill.creditbillnum
      cust_credit_bill._date
      cust_credit_bill.invnum
      cust_credit_bill.amount
    )),
    addl_from => ' LEFT JOIN cust_credit'.
                 ' ON (cust_credit_bill.crednum = cust_credit.crednum) ',
    extra_sql => ' WHERE cust_credit.custnum     = '.$self->custnum.
                 ' AND   cust_credit_bill._date  > '.$self->_date.
                 ' AND   cust_credit_bill.invnum < '.$self->invnum.' ',
#! did not investigate why hashref doesn't work for this join query
#    hashref => {
#      'cust_credit.custnum'     => {op => '=', value => $self->custnum},
#      'cust_credit_bill._date'  => {op => '>', value => $self->_date},
#      'cust_credit_bill.invnum' => {op => '<', value => $self->invnum},
#    },
  });

  return map {{
    _date         => $_->_date,
    invnum        => $_->invnum,
    amount        => $_->amount,
    creditbillnum => $_->creditbillnum,
  }} @cust_credit_bill;
}

=item _items_payments_postbill()

  Returns an array of hashrefs for payments where
  - Payment occured after this invoice
  - Payment applied to an invoice before this invoice

  Returned hashrefs are of the format returned by _items_payments()

=cut

sub _items_payments_postbill {
  my $self = shift;

  my @cust_bill_pay = qsearch({
    table    => 'cust_bill_pay',
    select => join(', ',qw(
      cust_bill_pay.billpaynum
      cust_bill_pay._date
      cust_bill_pay.invnum
      cust_bill_pay.amount
    )),
    addl_from => ' LEFT JOIN cust_bill'.
                 ' ON (cust_bill_pay.invnum = cust_bill.invnum) ',
    extra_sql => ' WHERE cust_bill.custnum     = '.$self->custnum.
                 ' AND   cust_bill_pay._date   > '.$self->_date.
                 ' AND   cust_bill_pay.invnum  < '.$self->invnum.' ',
  });

  return map {{
    _date      => $_->_date,
    invnum     => $_->invnum,
    amount     => $_->amount,
    billpaynum => $_->billpaynum,
  }} @cust_bill_pay;
}

=item _items_payments()

  Return array of hashrefs containing payments to be shown as line-items
  when rendering this bill.

  keys for each payment item:
  - paynum: id of payment
  - amount: payment amount
  - description: line item to be displayed on the bill

  This method has three ways it selects which payments to display on
  this bill:

  1) Default Case: No Conf flag for 'previous_balance-payments_since'

     Returns payments that have been applied to this bill only

  2) Case:
       Conf flag set for 'previous_balance-payments_since'

     List all payments that have been recorded between the timestamps
     of the previous invoice and this invoice

  3) Case:
        Conf flag set for 'previous_balance-payments_since'
        $opt{'template'} eq 'statement'

     List all payments that have been recorded between the timestamps
     of the previous invoice and the following invoice.

     I am concerned with this implementation, but leaving in place as is
     If this option is selected, while viewing an older bill, the old bill
     will show ALL future payments for future bills, but no charges for
     future bills.  Somebody could be misled into believing they have a
     large account credit when they don't.  Also, interrupts the chain of
     invoices as an account history... the customer could have two invoices
     in their fileing cabinet, for two different dates, both with a line item
     for the same duplicate payment.  The accounting is technically accurate,
     but somebody could easily become confused and think two payments were
     made, when really those two line items on two different bills represent
     only a single payment.

=cut

sub _items_payments {

  my $self = shift;

  # Simple memoize
  return @{$self->get('_items_payments')} if $self->get('_items_payments');

  my %opt = @_;
  my $template = $opt{template} || $self->get('_template');

  my @return;
  my @cust_pay_objs;

  my $c_invoice_payment_details = $self->conf->exists('invoice_payment_details');

  if ( $self->conf->exists('previous_balance-payments_since') ) {
    if ($template eq 'statement') {
      # Case 3 (see above)
      # Return payments timestamped between the previous and following bills

      my $previous_bill  = $self->previous_bill;
      my $following_bill = $self->following_bill;

      my $date_start = ref $previous_bill  ? $previous_bill->_date  : 0;
      my $date_end   = ref $following_bill ? $following_bill->_date : undef;

      my %query = (
        table => 'cust_pay',
        hashref => {
          custnum => $self->custnum,
          _date => { op => '>=', value => $date_start },
        },
      );
      $query{extra_sql} = " AND _date <= $date_end " if $date_end;

      @cust_pay_objs = qsearch(\%query);

    } else {
      # Case 2 (see above)
      # Return payments timestamped between this and the previous bill

      my $date_start = 0;
      my $date_end = $self->_date;

      my $previous_bill = $self->previous_bill;
      if (ref $previous_bill) {
        $date_start = $previous_bill->_date;
      }

      @cust_pay_objs = qsearch({
        table => 'cust_pay',
        hashref => {
          custnum => $self->custnum,
          _date => {op => '>=', value => $date_start},
        },
        extra_sql => " AND _date <= $date_end ",
      });
    }

  } else {
    # Case 1 (see above)
    # Return payments applied only to this bill

    @cust_pay_objs = $self->cust_bill_pay;

  }

  $self->set(
    '_items_payments',
    [ $self->__items_payments_make_hashref(@cust_pay_objs) ]
  );
  return @{ $self->get('_items_payments') };
  }

=item _items_payments_total

  Return a total of all records returned by _items_payments
  Results vary based on invoicing conf flags

=cut

sub _items_payments_total {
  my $self = shift;
  my $tot = 0;
  $tot += $_->{amount} for $self->_items_payments();
  return $tot;
}

sub __items_payments_make_hashref {
  # Transform a FS::cust_pay object into a simple hashref for invoice
  my ($self, @cust_pay_objs) = @_;
  my $c_invoice_payment_details = $self->conf->exists('invoice_payment_details');
  my @return;

  for my $obj (@cust_pay_objs) {

    # In case we're passed FS::cust_bill_pay (or something else?)
    # Below, we use $obj to render amount rather than $cust_apy.
    #   If we were passed cust_bill_pay objs, then:
    #   $obj->amount represents the amount applied to THIS invoice
    #   $cust_pay->amount represents the total payment, which may have
    #       been applied accross several invoices.
    # If we were passed cust_bill_pay objects, then the conf flag
    # previous_balance-payments_since is NOT set, so we should not
    # present any payments not applied to this invoice.
    my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;

    my %r_obj = (
      _date   => $cust_pay->_date,
      amount  => sprintf("%.2f", $obj->amount),
      paynum  => $cust_pay->paynum,
      payinfo => $cust_pay->payby_payinfo_pretty(),
      description => join(' ',
        $self->mt('Payment received'),
        $self->time2str_local('short', $cust_pay->_date),
      ),
    );

    if ($c_invoice_payment_details) {
      $r_obj{description} = join(' ',
        $r_obj{description},
        $self->mt('via'),
        $cust_pay->payby_payinfo_pretty($self->cust_main->locale),
    );
    }

    push @return, \%r_obj;
    }
  return @return;
  }

=item _items_total()

  Generate the line-items to be shown on the bill in the "Totals" section

  Returns a list of hashrefs, each with the keys:
  - total_item: description field
  - total_amount: dollar-formatted number amount

  Information presented by this method varies based on Conf

  Conf previous_balance-payments_due
  - default, flag not set
      Only transactions that were applied to this bill bill be
      displayed and calculated intothe total.  If items exist in
      the past-due section, those items will disappear from this
      invoice if they have been paid off.

  - previous_balance-payments_due flag is set
      Transactions occuring after the timestsamp of this
      invoice are not reflected on invoice line items

      Only payments/credits applied between the previous invoice
      and this one are displayed and calculated into the total

  - previous_balance-payments_due && $opt{template} eq 'statement'
      Same as above, except payments/credits occuring before the date
      of the following invoice are also displayed and calculated into
      the total

  Conf previous_balance-exclude_from_total
  - default, flag not set
      The "Totals" section contains a single line item.
      The dollar amount of this line items is a sum of old and new charges
  - previous_balance-exclude_from_total flag is set
      The "Totals" section contains two line items.
      One for previous balance, one for new charges
  !NOTE: Avent virtualization flag 'disable_previous_balance' can
      override the global conf flag previous_balance-exclude_from_total

  Conf invoice_show_prior_due_date
  - default, flag not set
    Total line item in the "Totals" section does not mention due date
  - invoice_show_prior_due_date flag is set
    Total line item in the "Totals" section includes either the due
    date of the invoice, or the specified invoice terms
    ? Not sure why this is called "Prior" due date, since we seem to be
      displaying THIS due date...
=cut

sub _items_total {
  my $self = shift;
  my $conf = $self->conf;

  my $c_multi_line_total = 0;
  $c_multi_line_total    = 1
    if $conf->exists('previous_balance-exclude_from_total')
    && $self->enable_previous();

  my @line_items;
  my $invoice_charges  = $self->charged();

  # _items_previous() is aware of conf flags
  my $previous_balance = 0;
  $previous_balance += $_->{amount} for $self->_items_previous();

  my $total_charges;
  my $total_descr;

  if ( $previous_balance && $c_multi_line_total ) {
    # previous balance, new charges on separate lines

    push @line_items, {
      total_amount => sprintf('%.2f',$previous_balance),
      total_item   => $self->mt(
        $conf->config('previous_balance-text') || 'Previous Balance'
      ),
    };

    $total_charges = $invoice_charges;
    $total_descr   = $self->mt(
      $conf->config('previous_balance-text-total_new_charges')
       || 'Total New Charges'
    );

    } else {
    # previous balance and new charges combined into a single total line
    $total_charges = $invoice_charges + $previous_balance;
    $total_descr = $self->mt('Total Charges');
  }

  if ( $conf->exists('invoice_show_prior_due_date') && !$conf->exists('invoice_omit_due_date') ) {
    # then the due date should be shown with Total New Charges,
    # and should NOT be shown with the Balance Due message.

    if ( $self->due_date ) {
      $total_descr .= $self->invoice_pay_by_msg;
    } elsif ( $self->terms ) {
      $total_descr = join(' ',
        $total_descr,
        '-',
        $self->mt($self->terms)
      );
    }
  }

  push @line_items, {
    total_amount => sprintf('%.2f', $total_charges),
    total_item   => $total_descr,
    };

  return @line_items;
}

=item _items_aging_balances

  Returns an array of aged balance amounts from a given epoch timestamp.

  The time of day is ignored for this calculation, so that slight differences
  on the generation time of an invoice doesn't determine which column an
  aged balance falls into.

  Will not include any balances dated after the given timestamp in
  the calculated totals

  usage:
  @aged_balances = $b->_items_aging_balances( $b->_date )

  @aged_balances = (
    under30d,
    30d-60d,
    60d-90d,
    over90d
  )

=cut

sub _items_aging_balances {
  my ($self, $basetime) = @_;
  die "Incorrect usage of _items_aging_balances()" unless ref $self;

  $basetime = $self->_date unless $basetime;
  my @aging_balances = (0, 0, 0, 0);
  my @open_invoices = $self->_items_previous();
  my $d30 = 2592000; # 60 * 60 * 24 * 30,
  my $d60 = 5184000; # 60 * 60 * 24 * 60,
  my $d90 = 7776000; # 60 * 60 * 24 * 90

  # Move the clock back on our given day to 12:00:01 AM
  my $dt_basetime = DateTime->from_epoch(epoch => $basetime);
  my $dt_12am = DateTime->new(
    year   => $dt_basetime->year,
    month  => $dt_basetime->month,
    day    => $dt_basetime->day,
    hour   => 0,
    minute => 0,
    second => 1,
  )->epoch();

  # set our epoch breakpoints
  $_ = $dt_12am - $_ for $d30, $d60, $d90;

  # grep the aged balances
  for my $oinv (@open_invoices) {
    if ($oinv->{_date} <= $basetime && $oinv->{_date} > $d30) {
      # If post invoice dated less than 30days ago
      $aging_balances[0] += $oinv->{amount};
    } elsif ($oinv->{_date} <= $d30 && $oinv->{_date} > $d60) {
      # If past invoice dated between 30-60 days ago
      $aging_balances[1] += $oinv->{amount};
    } elsif ($oinv->{_date} <= $d60 && $oinv->{_date} > $d90) {
      # If past invoice dated between 60-90 days ago
      $aging_balances[2] += $oinv->{amount};
    } else {
      # If past invoice dated 90+ days ago
      $aging_balances[3] += $oinv->{amount};
    }
  }

  return map{ sprintf('%.2f',$_) } @aging_balances;
}

=item has_call_details

Returns true if this invoice has call details.

=cut

sub has_call_details {
  my $self = shift;
  $self->scalar_sql("
    SELECT 1 FROM cust_bill_pkg_detail
             LEFT JOIN cust_bill_pkg USING (billpkgnum)
      WHERE cust_bill_pkg_detail.format = 'C'
        AND cust_bill_pkg.invnum = ?
      LIMIT 1
  ", $self->invnum);
}

=item call_details [ OPTION => VALUE ... ]

Returns an array of CSV strings representing the call details for this invoice
The only option available is the boolean prepend_billed_number

=cut

sub call_details {
  my ($self, %opt) = @_;

  my $format_function = sub { shift };

  if ($opt{prepend_billed_number}) {
    $format_function = sub {
      my $detail = shift;
      my $row = shift;

      $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
      
    };
  }

  my @details = map { $_->details( 'format_function' => $format_function,
                                   'escape_function' => sub{ return() },
                                 )
                    }
                  grep { $_->pkgnum }
                  $self->cust_bill_pkg;
  my $header = $details[0];
  ( $header, grep { $_ ne $header } @details );
}

=item cust_pay_batch

Returns all L<FS::cust_pay_batch> records linked to this invoice. Deprecated,
will be removed.

=cut

sub cust_pay_batch {
  carp "FS::cust_bill->cust_pay_batch is deprecated";
  my $self = shift;
  qsearch('cust_pay_batch', { 'invnum' => $self->invnum });
}

=back

=head1 SUBROUTINES

=over 4

=item process_reprint

=cut

sub process_reprint {
  process_re_X('print', @_);
}

=item process_reemail

=cut

sub process_reemail {
  process_re_X('email', @_);
}

=item process_refax

=cut

sub process_refax {
  process_re_X('fax', @_);
}

=item process_reftp

=cut

sub process_reftp {
  process_re_X('ftp', @_);
}

=item respool

=cut

sub process_respool {
  process_re_X('spool', @_);
}

use Data::Dumper;
sub process_re_X {
  my( $method, $job ) = ( shift, shift );
  warn "$me process_re_X $method for job $job\n" if $DEBUG;

  my $param = shift;
  warn Dumper($param) if $DEBUG;

  re_X(
    $method,
    $job,
    %$param,
  );

}

# this is called from search/cust_bill.html and given all its search 
# parameters, so it needs to perform the same search.

sub re_X {
  # spool_invoice ftp_invoice fax_invoice print_invoice
  my($method, $job, %param ) = @_;
  if ( $DEBUG ) {
    warn "re_X $method for job $job with param:\n".
         join( '', map { "  $_ => ". $param{$_}. "\n" } keys %param );
  }

  #some false laziness w/search/cust_bill.html
  $param{'order_by'} = 'cust_bill._date';

  my $query = FS::cust_bill->search(\%param);
  delete $query->{'count_query'};
  delete $query->{'count_addl'};

  $query->{debug} = 1; # was in here before, is obviously useful  

  my @cust_bill = qsearch( $query );

  $method .= '_invoice' unless $method eq 'email' || $method eq 'print';

  warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
    if $DEBUG;

  my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
  foreach my $cust_bill ( @cust_bill ) {
    $cust_bill->$method();

    if ( $job ) { #progressbar foo
      $num++;
      if ( time - $min_sec > $last ) {
        my $error = $job->update_statustext(
          int( 100 * $num / scalar(@cust_bill) )
        );
        die $error if $error;
        $last = time;
      }
    }

  }

}

sub API_getinfo {
  my $self = shift;
  +{ ( map { $_=>$self->$_ } $self->fields ),
     'owed' => $self->owed,
     #XXX last payment applied date
   };
}

=back

=head1 CLASS METHODS

=over 4

=item owed_sql

Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).

=cut

sub owed_sql {
  my ($class, $start, $end) = @_;
  'charged - '. 
    $class->paid_sql($start, $end). ' - '. 
    $class->credited_sql($start, $end);
}

=item net_sql

Returns an SQL fragment to retreive the net amount (charged minus credited).

=cut

sub net_sql {
  my ($class, $start, $end) = @_;
  'charged - '. $class->credited_sql($start, $end);
}

=item paid_sql

Returns an SQL fragment to retreive the amount paid against this invoice.

=cut

sub paid_sql {
  my ($class, $start, $end) = @_;
  $start &&= "AND cust_bill_pay._date <= $start";
  $end   &&= "AND cust_bill_pay._date > $end";
  $start = '' unless defined($start);
  $end   = '' unless defined($end);
  "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
       WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end  )";
}

=item credited_sql

Returns an SQL fragment to retreive the amount credited against this invoice.

=cut

sub credited_sql {
  my ($class, $start, $end) = @_;
  $start &&= "AND cust_credit_bill._date <= $start";
  $end   &&= "AND cust_credit_bill._date >  $end";
  $start = '' unless defined($start);
  $end   = '' unless defined($end);
  "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
       WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end  )";
}

=item due_date_sql

Returns an SQL fragment to retrieve the due date of an invoice.
Currently only supported on PostgreSQL.

=cut

sub due_date_sql {
  die "don't use: doesn't account for agent-specific invoice_default_terms";

  #we're passed a $conf but not a specific customer (that's in the query), so
  # to make this work we'd need an agentnum-aware "condition_sql_conf" like
  # "condition_sql_option" that retreives a conf value with SQL in an agent-
  # aware fashion

  my $conf = new FS::Conf;
'COALESCE(
  SUBSTRING(
    COALESCE(
      cust_bill.invoice_terms,
      cust_main.invoice_terms,
      \''.($conf->config('invoice_default_terms') || '').'\'
    ), E\'Net (\\\\d+)\'
  )::INTEGER, 0
) * 86400 + cust_bill._date'
}

=back

=head1 BUGS

The delete method.

=head1 SEE ALSO

L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
L<FS::cust_bill_pkg>, L<FS::cust_credit>, schema.html from the base
documentation.

=cut

1;