galaxy-central / lib / galaxy / web / controllers / nglims.py

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
"""Provide an interface for managing next generation sequencing samples.

The functionality of the LIMS is managed via a configuration file
defining available services, options, and sample states. See
tool-data/nglims.yaml for more details.

To enable this LIMS in the main menus, set 'use_nglims=True' in the main
universe_wsgi.ini configuration file.
"""
import operator
import collections
import itertools
import string
import re
import csv
import StringIO
from datetime import datetime, timedelta
import logging, os, string, re
from random import choice
import urlparse
import urllib
#from functools import wraps

import yaml
from mako.template import Template

from galaxy.web.framework.helpers import grids
from galaxy.web.base.controller import *
from galaxy.model.orm import *
from galaxy.web.form_builder import *
from galaxy import model, util

from galaxy.web.controllers import requests

log = logging.getLogger( __name__ )

WEB_NAME = "nglims"
LIMS_ORDER = ["services_to_samples", "samples_to_project", "list_projects"]

def require_sequencing(func):
    """Decorator requiring a user to be logged in with sequencing permissions.
    """
    def decorator( self, trans, *args, **kwargs ):
        if trans.user:
            roles = trans.user.all_roles()
        else:
            roles = []
        if "sequencing" in [r.name for r in roles]:
            return func( self, trans, *args, **kwargs )
        else:
            return trans.show_error_message(
                "You must be <a target='galaxy_main' href='%s'>logged in</a> "
                "with sequencing permissions</div>"
                % (url_for( controller='user', action='login')))
    return decorator

def pass_func_name(func):
    """Pass name of function as keyword argument _func_name.

    From: http://stackoverflow.com/questions/245304/how-do-i-get-the-name-of-
    a-function-or-method-from-within-a-python-function-or-me/245333#245333
    """
    # XXX would be nice to re-include when dropping python2.4 support
    #@wraps(func)
    def _pass_name(*args, **kwds):
        kwds['_func_name'] = func.func_name
        return func(*args, **kwds)
    return _pass_name

class _FormMixin:
    """Provide functionality related to dealing with forms and form data.
    """
    def _form_label(self, display_label):
        """Retrieve the form label based on this diplay label.
        """
        return "_".join(x.lower() for x in display_label.split())

    def _add_form_label(self, widget, params=None):
        """Given a ready to apply widget, adjust the label to be non-generic.

        Also applied any passed arguments as the default value.
        """
        form_label = self._form_label(widget['label'])
        widget['widget'].name = form_label
        if params is not None:
            pvalue = params.get(form_label, "")
            # add the selected value for pull down options like select fields
            if hasattr(widget['widget'], 'multiple'):
                for i, (option, val, _) in enumerate(widget['widget'].options):
                    if option == pvalue:
                        widget['widget'].options[i] = (option, val, True)
                        break
            elif pvalue:
                widget['widget'].value = pvalue

        widget['helptext'] = widget['helptext'].replace('(Optional)', '')
        return widget

    def _get_organism_choice_widget(self, widget):
        """Retrieve a widget with a select list of organism choices.
        """
        old_widget = widget['widget']
        cur_select = old_widget.value or util.dbnames.default_value
        select_widget = ComboboxField(old_widget.name)
        if hasattr(util, "nextgen_dbkeys"):
            nextgen_dbkeys = util.nextgen_dbkeys
        else:
            nextgen_dbkeys = []
        for build_val, build_name in util.dbnames:
            if len(nextgen_dbkeys) == 0 or build_val in nextgen_dbkeys:
                select_widget.options.append(build_name)
                if build_val == cur_select:
                    select_widget.value = build_name
        select_widget.options.sort()
        widget['widget'] = select_widget
        return widget

    def _get_name_widget(self, trans, widget, project_org):
        """Provide a short default name for a sample, based on current names.

        Implements a simple naming scheme that provides short names for samples.
        Samples are named as the first and last letter of the users name, plus
        letter for uniqueness, plus a sample number. So my (Brad Chapman)
        samples would be:

        BCa1, BCa2...

        Additional BC initial would be BCb1, BCc1 and so on.
        This isn't infinately scaleable, but works with up to 26 different users
        with the same initials, so should be fine for our purposes.
        """
        # if we don't have a current value, generate and add one
        name_pat = re.compile(r'[A-Z][A-Z][a-z]\d+')
        name_size = 3
        if not widget['widget'].value:
            name_prefix = self._get_name_prefix(trans, name_size, name_pat, project_org)
            sampleq = trans.app.model.Sample
            query = trans.sa_session.query(sampleq).filter(
                  func.substr(sampleq.table.c.name, 1, name_size) == name_prefix
                  ).order_by('id DESC')
            last_sample = query.first()
            if last_sample:
                last_num = int(last_sample.name.replace(name_prefix, ""))
            else:
                last_num = 0
            new_name = "%s%s" % (name_prefix, last_num + 1)
            widget['widget'].value = new_name
        widget['helptext'] = "Assigned sample name. " + \
                "Please label submissions using this name."
        widget['widget'].readonly = True
        return widget

    def _get_name_prefix(self, trans, name_size, name_pat, project_org):
        """Retrieve the naming prefix to use for sample names.
        """
        # check for previous samples in the requests table -- either as
        # projects (submitted) or next gen input data (not yet submitted)
        check_requests = [self._project_org.name, "%s %s" %
            (self._service_org.next_gen_name(), self._service_org.input_name())]
        for request in [r for r in trans.user.requests if
                r.type.name in check_requests]:
            for sample in itertools.chain(request.samples_by_map(),
                                          request.parent_samples_by_map()):
                example_name = sample.name
                if (example_name and len(example_name) > name_size and
                        name_pat.match(example_name)):
                    return example_name[:name_size]
        # did not find anything -- generate a new name
        return self._generate_new_name_prefix(trans, name_size)

    def _generate_new_name_prefix(self, trans, name_size):
        """Generate a new prefix to use for a users sample names.
        """
        username = trans.user.username
        if username is None or len(username.strip()) == 0:
            username = trans.user.email
        username = username.replace("-", " ")
        parts = [p.strip() for p in username.split() if p.strip()]
        if len(parts) > 1:
            first_part = parts[0][0] + parts[-1][0]
        else:
            first_part = parts[0][:2]
        first_part = first_part.upper()
        assert len(first_part) == name_size - 1
        sampleq = trans.app.model.Sample
        for add_letter in list(string.lowercase):
            possible_name = first_part + add_letter
            query = trans.sa_session.query(sampleq).filter(
               func.substr(sampleq.table.c.name, 1, name_size) == possible_name)
            if query.count() == 0:
                return possible_name
        raise ValueError("Did not find an available name for username: %s" %
                username)

    def form_value_dict_from_id(self, trans, form_value_id):
        form_val = trans.sa_session.query(
                trans.app.model.FormValues).get(form_value_id)
        return self.form_value_dict(form_val)

    def form_value_dict(self, form_values):
        """Return a dictionary of values keyed by ids from a form values object.
        """
        details = {}
        for i, field in enumerate(form_values.form_definition.fields):
            field_label = self._form_label(field['label'])
            try:
                value = form_values.content[field['name']]
            except KeyError:
                value = form_values.content.get(field['label'], "")
            details[field_label] = value
        return details

    def _get_form_values(self, trans, form, params):
        """Retrieve values from our submitted form in a Galaxy-ready object.
        """
        values = {}
        for field in form.fields:
            form_label = self._form_label(field['label'])
            cur_val = params.get(form_label, '')
            if isinstance(cur_val, str):
                cur_val = util.restore_text(cur_val)
            values[field['name']] = cur_val
        return trans.app.model.FormValues(form, values)

    def _get_payment(self, d):
        """Retrieve payment, which can change names, from a dictionary.
        """
        payment_keys = [k for k in d.keys() if k.startswith("payment")]
        assert len(payment_keys) == 1, d.keys()
        pkey = payment_keys[0]
        return d[pkey]

class _RequestMixin:
    """Provide reuseable functionality for adding and querying requests.
    """
    def _new_request(self, trans, request_type, form_values, params, state):
        for check_name in ["name", "project_name", "run_folder"]:
            name = params.get(check_name, "")
            if name:
                break
        cur_request = trans.app.model.Request(name, "", 
                request_type, trans.user, form_values)
        trans.sa_session.add(cur_request)
        request_event = trans.app.model.RequestEvent(cur_request, state)
        trans.sa_session.add(request_event)
        return cur_request

    def _get_request_type(self, trans, name):
        for rt in trans.sa_session.query(trans.app.model.RequestType
                ).filter_by(name=name):
            if not rt.deleted:
                return rt
        raise ValueError("Did not find a request type: %s" % name)

    def _filter_request_by_state(self, trans, query, state):
        """Build a SQL alchemy query that filters requests to a specific state.

        This handles multiple events for a request, but requires that 
        timestamps are stable -- the most recent ID should have the most recent
        timestamp which is the most recent event and state.
        """
        event_q = trans.app.model.RequestEvent
        return query.join(event_q).filter(event_q.state == state).filter(
                event_q.id.in_(select(columns=[func.max(event_q.table.c.id)],
                                      from_obj=event_q.table,
                                      group_by=event_q.table.c.request_id)))

    def _text_barcode_summary(self, barcodes):
        """Provide high level summary text of barcodes present in a sample.
        """
        bc_type = ""
        bc_ids = []
        all_numbers = True
        for bc in barcodes:
            bc_type = bc["barcode_type"]
            try:
                bc_id = int(bc["barcode_id"])
            except ValueError:
                bc_id = bc["barcode_id"]
                all_numbers = False
            bc_ids.append(bc_id)
        bc_ids.sort()
        # if these are numbers, collapse them to ranges
        if all_numbers:
            # group items together that are next to each other
            # http://stackoverflow.com/questions/3429510/pythonic-way-to-convert-
            # a-list-of-integers-into-a-string-of-comma-separated-range
            groups = (list(x) for (_, x) in itertools.groupby(enumerate(bc_ids),
                lambda (i,x):i-x))
            # create ranges from each group
            bc_ids = ("-".join(map(str, (g[0][1], g[-1][1])[:len(g)]))
                      for g in groups)
        id_str = ",".join(str(i) for i in bc_ids)
        return "%s %s" % (bc_type, id_str)

class _NGLimsResultsAnalysis:
    """Provide summary information related to the results of next-gen runs.
    """
    @web.expose
    @web.require_login("manage sequencing samples")
    def list_sqn_results(self, trans, **kwd):
        """Provide a list of statistics from sequencing runs.
        """
        # Save the current grid (referer URL) as CSV for download
        if kwd.get("operation", None) == "download":
            refer_kwd = self._normalized_kwds(trans.request.referer)
            trans.response.send_redirect(web.url_for(controller=WEB_NAME,
                    action="results_to_csv", **refer_kwd))
        else:
            grid = _ResultsGrid(self._project_org)
            kwd = self._handle_grid_kwds(trans, **kwd)
            return grid(trans, **kwd)

    def _normalized_kwds(self, url):
        kwds = {}
        for key, val in urlparse.parse_qs(urlparse.urlsplit(url).query
                ).iteritems():
            if len(val) == 1:
                val = val[0]
            kwds[key] = val
        return kwds

    @web.expose
    @web.require_login("manage sequencing samples")
    def results_to_csv(self, trans, **kwd):
        """Prepare sequencing results to a downloadable CSV format.
        """
        grid = _ResultsGrid(self._project_org, web_ready=False)
        kwd = self._handle_grid_kwds(trans, **kwd)
        results = grid.apply_query_filter(trans, None, **kwd)
        out_info = StringIO.StringIO()
        writer = csv.writer(out_info)
        writer.writerow(["Run", "Lane", "Researcher", "Name", "Description",
            "Genome", "Length", "Clusters", "Reads"])
        for result in results:
            writer.writerow([result.run, result.lane, result.researcher,
                result.name, result.description, result.genome_build,
                result.read_length, result.clusters, result.reads])
        researchers = list(set([r.researcher for r in results]))
        if kwd.has_key('search'):
            ext = kwd['search'].split("_")[0]
        elif len(researchers) == 1 and researchers[0]:
            ext = researchers[0].split(" ")[-1]
        else:
            ext = datetime.now().strftime("%m%d%Y")
        out_name = "seqresults_%s" % ext
        trans.response.set_content_type("text/csv")
        trans.response.headers['Content-disposition'] = \
                "attachment; filename=%s.csv" % out_name
        return out_info.getvalue()

class _NGLimsSequencingRuns:
    """Prepare galaxy request for next-generation sequencing runs.

    Web controller functionality to prepare a next-gen sequencing run as
    a request with linked samples, and display these in a grid based view.
    """
    @web.expose
    @require_sequencing
    def list_sqn_runs(self, trans, **kwd):
        """List all submitted projects that need to be processed.
        """
        kwd = self._handle_grid_kwds(trans, **kwd)
        request_grid = _SqnRunGrid(self._service_org)
        return request_grid(trans, **kwd)

    @web.expose
    def show_sqnrun_samples(self, trans, **kwd):
        kwd = self._handle_grid_kwds(trans, **kwd)
        kwd['_include_lane'] = True
        kwd['_include_state'] = True
        kwd['sort'] = 'lane'
        rid = kwd.get('ids', '')
        if rid:
            request = trans.sa_session.query(trans.app.model.Request).get(rid)
            if request:
                kwd['request_details'] = self.form_value_dict(request.values)
        grid = _SampleDetailsGrid(self._project_org, self._service_org)
        return grid(trans, **kwd)

    @web.expose
    @require_sequencing
    @pass_func_name
    def edit_sqnrun(self, trans, **kwd):
        buttons = dict(
            save = "Submit")
        kwd = self._handle_grid_kwds(trans, **kwd)
        params = util.Params(kwd)
        rid = params.get('ids', '')
        contents = []
        if rid:
            request = trans.sa_session.query(trans.app.model.Request).get(rid)
            contents = request.values.content
        is_submit = (params.get("create_request_button", None) == buttons['save'])
        cur_form = request.values.form_definition
        if is_submit:
            messages = self._check_submission([cur_form], params)
        else:
            messages = []
        widgets = []
        for widget in cur_form.get_widgets(trans.user, contents=contents):
            widget = self._add_form_label(widget, params)
            widgets.append(widget)
        # form values to pass through
        widgets.append(dict(label="", helptext="",
                    widget=HiddenField("ids", rid)))
        options = []
        if (is_submit and not messages):
            request.values = self._get_form_values(trans, cur_form, params)
            if not self._testing:
                trans.sa_session.flush()
            trans.response.send_redirect(web.url_for(controller=WEB_NAME,
                action="list_sqn_runs"))
        else:
            if messages:
                msg = messages[0]
                msg_type = 'error'
            else:
                msg = ""
                msg_type = None
            return trans.fill_template('/nglims/form_entry.mako',
                title="Edit run information",
                form_id=kwd['_func_name'],
                form_url=web.url_for(controller=WEB_NAME,
                    action=kwd['_func_name']),
                msg=msg,
                messagetype=msg_type,
                button_name=buttons['save'],
                widgets=widgets)
        return ""

    @web.expose
    @require_sequencing
    def download_sqnrun(self, trans, **kwd):
        """Download the details of a sequencing run as a CSV file.

        Calls our REST API to get the result as JSON, and then reformats the
        results into HTML.
        """
        rid = kwd.get('ids', '')
        if rid:
            request = trans.sa_session.query(trans.app.model.Request).get(rid)
        details = self._details_from_request(trans, request)
        out_info = StringIO.StringIO()
        writer = csv.writer(out_info)
        writer.writerow(["Run", "Lane", "Name", "Description", "Researcher",
            "Concentration", "Adapter", "InsertSize", "Quantitation", "Payment"])
        for run_lane in details:
            writer.writerow([request.name, run_lane["lane"], run_lane["name"],
                run_lane["description"], run_lane.get("researcher", ""),
                run_lane.get("concentration", ""),
                run_lane.get("adapter", ""),
                run_lane.get("insertsize", ""),
                run_lane.get("quantitation", ""),
                run_lane.get("payment", "")])
        trans.response.set_content_type("text/csv")
        trans.response.headers['Content-disposition'] = \
                "attachment; filename=%s.csv" % request.name
        return out_info.getvalue()

class _NGLimsPlotting:
    """Provide plots of sequencing statistics for process monitoring.
    """
    @web.expose
    def sqn_plots(self, trans, **kwd):
        return trans.fill_template('/nglims/plots.mako')

    @web.expose
    @web.json
    def sqn_plot_reads(self, trans, **kwd):
        """Get data on reads over time for plotting purposes.
        """
        #return util.json.from_json_string(urllib.urlopen(
        #    "http://galaga/galaxy/nglims/sqn_plot_reads").read())
        query = trans.sa_session.query(model.SqnRunResults)
        if trans.user:
            user_roles = [r.name for r in trans.user.all_roles()]
            if 'sequencing' not in user_roles:
                query = query.filter_by(user=trans.user)
        query = query.order_by(
              ["sqn_run_results.request_id ASC", "lane ASC", "sample_id DESC"])
        out = dict(reads=[], passing=[], lanes=dict())
        results_by_date = dict()
        for result in query:
            vals = self._project_org.form_value_dict(result.form_values)
            request_vals = self._project_org.form_value_dict(result.request.values)
            request_date_str = request_vals.get("run_folder", "").split("_")[0]
            try:
                request_date = datetime.strptime(request_date_str, "%y%m%d")
            except ValueError:
                request_date = result.request.create_time
            date = request_date.strftime("%Y/%m/%d")
            if not results_by_date.has_key(date):
                results_by_date[date] = []
            if result.user:
                if not out["lanes"].has_key(str(result.lane)):
                    out["lanes"][str(result.lane)] = []
                # reads are scaled to millions for ease of reading
                scale = float(1e6)
                if vals.get("reads", ""):
                    reads = vals["reads"]
                else:
                    reads = vals["clusters_passed"]
                reads = float(reads) / scale
                results_by_date[date].append(reads)
                out["lanes"][str(result.lane)].append([date, reads])
            clusters = None
            if vals["clusters"]:
                clusters = float(vals["clusters"]) / scale
            if clusters and clusters > reads:
                out["passing"].append([clusters, reads / clusters * 100.0,
                    date])
        for date, values in results_by_date.iteritems():
            out_values = [max(values), min(values), sum(values) / len(values)]
            out["reads"].append([date] + out_values)
        return out

class _NGLimsMultiplex:
    """Handle barcoded multiplex input samples.
    """
    @web.expose
    @pass_func_name
    def add_barcode(self, trans, **kwd):
        """Provide template to associate barcodes with samples.
        """
        parent_id = None
        ids = []
        if kwd.get("parent_id", ""):
            parent_id = trans.security.decode_id(kwd["parent_id"])
        elif kwd.get("ids", ""):
            (ids, _, _) = self._normalize_ids(**kwd)
        default_type = None
        str_samples = []
        editable_samples = []
        send_parent = ""
        if parent_id:
            # get parent details for display and processing
            parent = trans.sa_session.query(trans.app.model.Sample).get(
                    parent_id)
            (sid, sname, sdescr, _) = self._make_displayready(
                    self._get_sample_details([parent]))[0]
            sample_title = "Multiplex details for %s: %s" % (sname, sdescr)
            send_parent = trans.security.encode_id(parent_id)
            # retrieve existing barcode information
            (_, request_type) = self._service_org.get_detail_widgets(trans,
                    "Barcode")
            barcodes = []
            for request in parent.requests_by_map():
                if request.type == request_type:
                    request_info = self.form_value_dict(request.values)
                    barcodes = request_info.get("barcodes", [])
            for barcode in barcodes:
                default_type = barcode['barcode_type']
                editable_samples.append(barcode["name"])
        else:
            sample_title = "Multiplex details"
            # retrieve our samples, filtering any multiplexed samples
            all_samples = [trans.sa_session.query(trans.app.model.Sample
                    ).get(sid) for sid in ids]
            all_samples = [s for s in all_samples if not
                    self._service_org.get_barcode(s).get("barcodes", None)]
            for (sid, sname, sdescr, _) in self._make_displayready(
                    self._get_sample_details(all_samples)):
                display_name = "%s %s" % (sname, sdescr)
                str_samples.append((sid, display_name))
        barcodes = []
        for i, barcode in enumerate(self._config['barcodes']):
            if default_type is None and i == 0:
                default_type = barcode['name']
            barcodes.append(barcode['name'])
        if len(editable_samples) == 0 and len(str_samples) == 0:
            editable_samples.append("")
        return trans.fill_template('/nglims/barcodes.mako',
                barcode_details='/nglims/barcodes_by_type',
                assoc_barcodes='/nglims/assoc_barcodes',
                callback_url=trans.request.referrer,
                data_store_id=kwd.get("data_store_id", ""),
                default_barcode_type=default_type,
                sample_title=sample_title,
                parent_id=send_parent,
                editable_samples=editable_samples,
                samples=str_samples, barcodes=barcodes)

    @web.expose
    @web.json
    def barcodes_by_type(self, trans, **kwd):
        """Retrieve JSON string of barcodes available for a particular type.
        """
        cur_type = kwd.get("barcode_type", "")
        barcodes = {}
        for choice in self._config["barcodes"]:
            if choice["name"] == cur_type:
                barcodes["names"] = []
                for item in choice["data"]:
                    barcodes["names"].append("%s : %s" % (item.items()[0]))
        return barcodes

    @web.expose
    @web.json
    def assoc_barcodes(self, trans, **kwd):
        """Associate barcodes with samples, redirecting to the starting state.
        """
        data = util.json.from_json_string(kwd.get('data', '{}'))
        (_, request_type) = self._service_org.get_detail_widgets(trans,
                "Barcode")
        parent_data = []
        for sid, barcode_info in data['barcodes']:
            bid, bseq = barcode_info.split(" : ")
            params = dict(barcode_type=data["barcode_type"], barcode_id=bid,
                    sequence=bseq)
            new_prefix = "NEW^^"
            if sid.startswith(new_prefix):
                name = sid.replace(new_prefix, "")
                params["name"] = name
                parent_data.append(params)
            else:
                m = self._check_and_add_sample_data(trans, sid, [], request_type,
                        False, params)
                assert len(m) == 0, m
        parent_id = kwd.get("parent_id", data.get("parent_id", ""))
        if parent_id and parent_data:
            parent_id = trans.security.decode_id(parent_id)
            m = self._check_and_add_sample_data(trans, parent_id, [], request_type,
                    False, dict(barcodes=parent_data))
            assert len(m) == 0, m
        out = dict()
        return out

class _NGLimsSequencingQueue(_NGLimsSequencingRuns):
    """Functionality for displaying queues related to sequencing states.

    This compartmentalizes the web controller functionality for displaying the
    sequencing queue, which formalizes various states samples can be in while
    being processed. This provides a grid display of the samples, along with
    buttons to add information and move from state to state.
    """
    @web.expose
    @require_sequencing
    def list_queues(self, trans, **kwd):
        """List samples present in various active sequencing queues.
        """
        kwd = self._handle_grid_kwds(trans, **kwd)
        grid = _SampleDetailsGrid(self._project_org, self._service_org,
                default_sort='update_time')
        std_filters = []
        for state in self._service_org.get_states():
            std_filters.append(
                grids.GridColumnFilter(state, args=dict(
                    controller=WEB_NAME, action='list_queues',
                    state=state)))
        grid.standard_filters = std_filters
        if not kwd.has_key('state'):
            kwd['state'] = 'Sequencing'
        if kwd['state'] in ['Sequencing confirmation', 'Complete']:
            kwd['_include_sqn_run'] = True
        elif kwd['state'] not in self._service_org.pre_received_states():
            kwd["_include_date_received"] = True
        grid.operations = self._service_org.operations_by_state(kwd['state'])
        grid.title = "Sequencing queues"
        grid.show_filter = kwd['state']
        return grid(trans, **kwd)

    def _normalize_ids(self, **kwd):
        """Manage ID information submitted in queues, keeping form state.
        """
        # comma separate list
        if isinstance(kwd['ids'], basestring) and kwd['ids'].find(','):
            kwd['ids'] = kwd['ids'].split(",")
        if not isinstance(kwd['ids'], list):
            ids = [kwd['ids']]
        else:
            ids = kwd['ids']
        cur_id = kwd.get('cur_id', None)
        if cur_id is not None:
            cur_index = ids.index(cur_id)
            try:
                next_id = ids[cur_index + 1]
            except IndexError:
                next_id = None
        elif len(ids) > 0:
            next_id = ids[0]
        else:
            next_id = None
        return ids, cur_id, next_id

    def _add_info_and_transition(self, trans, **kwd):
        """Add details to samples and move them to the next processing state.

        This requires two stages:
        1. Entering information for each of the samples.
        2. Adding this information and moving to the next queue.
        """
        ids, cur_id, next_id = self._normalize_ids(**kwd)
        widgets, request_type = self._service_org.get_detail_widgets(trans,
                kwd["state"])
        add_together = kwd.get('_add_together', False)
        # if we have a current ID, add details from our form
        messages = []
        if cur_id:
            messages = self._check_and_add_sample_data(trans, cur_id,
                    ids, request_type, add_together, kwd)
            if add_together:
                next_id = None
        # if we are done submitting forms, move our samples and get to
        # the next queue
        if cur_id and next_id is None and len(messages) == 0:
            self._move_to_next_queue(trans, ids, kwd.get('_move_next', ''))
        # otherwise, generate our form details for submission
        else:
            return self._sample_submission_form(trans, ids, cur_id, next_id,
                    widgets, messages, request_type, add_together, kwd)

    def _move_to_next_queue(self, trans, ids, next_state=None):
        """Move a list of sample IDs to the next service queue.
        """
        all_states = collections.defaultdict(int)
        for sid in ids:
            sample = trans.sa_session.query(trans.app.model.Sample).get(sid)
            if next_state:
                new_state = self._service_org.move_sample_to_state(trans, sample,
                        next_state)
            else:
                new_state = self._service_org.move_to_next_state(trans, sample)
            all_states[new_state] += 1
        states = [(count, s) for (s, count) in all_states.items()]
        states.sort(reverse=True)
        trans.response.send_redirect(web.url_for(controller=WEB_NAME,
            action="list_queues", state=states[0][1]))

    def _check_and_add_sample_data(self, trans, cur_id, all_ids, request_type,
            add_together, params):
        """Read data from form submission and add to an associated sample.
        """
        if add_together:
            all_sample_ids = all_ids
        else:
            all_sample_ids = [cur_id]
        samples = []
        for sid in all_sample_ids:
            samples.append(trans.sa_session.query(trans.app.model.Sample
                ).get(sid))
        messages = self._check_submission([request_type.request_form], params)

        if len(messages) == 0:
            if add_together:
                messages = self._add_high_level_request_data(trans, samples,
                        request_type, all_ids, params)
            else:
                messages = []
                self._add_sub_request_data(trans, samples, request_type, params)
            # submit the information
            # Comment out to test
            if not self._testing and len(messages) == 0:
                trans.sa_session.flush()
        return messages

    def _add_high_level_request_data(self, trans, samples, request_type,
            all_ids, params):
        """Add request data where we generate a new high level request.

        This handles the case where our request is a top level request
        that has samples associated with it. This will be the case for
        sequencing runs, which are new requests that re-organize a group
        of existing samples in the system.
        """
        messages = []
        form_values = self._get_form_values(trans, request_type.request_form,
                params)
        cur_request = self._new_request(trans, request_type, form_values,
                params, trans.app.model.Request.states.NEW)
        order_info = util.json.from_json_string(params.get("sorted_samples"))
        all_ids = all_ids[:]
        for lane_info, sids in order_info.iteritems():
            # convert back into 0-based indexing for storage
            lane = int(lane_info.replace("lane", "")) - 1
            lane_bcs = {}
            for sid in sids:
                sample = trans.sa_session.query(trans.app.model.Sample
                        ).get(sid)
                assert sample is not None
                lane_bcs = self._update_lane_barcodes(sample, lane_bcs)
                sample_map = trans.app.model.SampleRequestMap(sample,
                        cur_request, lane, False)
                trans.sa_session.add(sample_map)
                # sanity check to be sure we add all IDs requested
                try:
                    del all_ids[all_ids.index(str(sid))]
                except ValueError:
                    pass
            messages = self._check_lane_barcodes(lane_bcs, lane, messages)
        if len(all_ids) > 0:
            messages.append("Need to add all samples to sequencing lanes")
        return messages

    def _check_lane_barcodes(self, lane_bcs, lane, messages):
        """Add messages about issues with barcodes in a lane.
        """
        for bc, val in lane_bcs.iteritems():
            if val > 1:
                if bc is None:
                    msg = "non-barcoded samples"
                else:
                    msg = "'%s' barcodes" % bc
                messages.append("Multiple %s present in lane %s." %
                                (msg, lane + 1))
        if len(lane_bcs) > 1 and lane_bcs.has_key(None):
            messages.append("Barcoded and non-barcoded samples in lane %s"
                            % (lane + 1))
        return messages

    def _update_lane_barcodes(self, sample, lane_bcs):
        """Update collected barcodes with details from this sample.
        """
        bc_list = self._service_org.get_barcode(sample)
        if len(bc_list.get("barcodes", [])) > 0:
            bc_list = bc_list["barcodes"]
        elif bc_list.get("barcode_id", ""):
            bc_list = [bc_list]
        if len(bc_list) == 0:
            bc_strs = [None]
        else:
            bc_strs = ["%s %s" % (b["barcode_type"], b["barcode_id"])
                       for b in bc_list]
        for bc in bc_strs:
            try:
                lane_bcs[bc] += 1
            except KeyError:
                lane_bcs[bc] = 1
        return lane_bcs

    def _add_sub_request_data(self, trans, samples, request_type, params):
        """Add the regular form data for most sequencing request items.

        This deals with the standard case where a sample has several
        sub-requests, and we are adding details about one of them.
        """
        for sample in samples:
            added_values = False
            cur_request_count = 0
            # if we can find the request associated with a sample, add it
            for request in sample.requests_by_map():
                cur_request_count += 1
                if not params.get("_make_new_request", False):
                    if request.type == request_type:
                        request.values = self._get_form_values(trans,
                                request_type.request_form, params)
                        added_values = True
                        break
            if (params.get("_make_new_request", None) is False and
                    not added_values):
                raise ValueError("Did not find request type: %s" % request_type)
            # otherwise, add a new request with the details to the sample.
            if not added_values:
                form_values = self._get_form_values(trans,
                        request_type.request_form, params)
                cur_request = self._new_request(trans, request_type, form_values,
                        params, trans.app.model.Request.states.NEW)
                sample_map = trans.app.model.SampleRequestMap(sample,
                        cur_request, cur_request_count + 1, True)

    def _sample_submission_form(self, trans, ids, cur_id, next_id,
            widgets, messages, request_type, add_together, kwd):
        """Provide a form for submitting sample details, maintaining state.
        """
        # if we have problems, need to re-submit the current form
        if messages:
            work_id = cur_id
        else:
            work_id = next_id
            if kwd.get("_default_sqn_info", None):
                kwd = self._prefilled_sqn_info(trans, kwd, work_id,
                        kwd["_default_sqn_info"])
        send_widgets = []
        if not add_together:
            sample = trans.sa_session.query(trans.app.model.Sample).get(work_id)
            sample_info = self.form_value_dict(sample.values)
            send_widgets.append(dict(label="", helptext="",
                widget=_SectionLabel("%s: %s" % (sample_info["name"],
                    sample_info["description"]))))
        for w in widgets:
            send_widgets.append(self._add_form_label(w, kwd))
        # details to pass on through with the form
        for name, value in [("ids", ",".join([str(i) for i in ids])),
                            ("state", kwd["state"]),
                            ("cur_id", work_id),
                            ("rids", kwd.get("rids", None))]:
            if value:
                send_widgets.append(dict(label="", helptext="",
                    widget=HiddenField(name, value)))
        # if we are adding everything together, show all of the items we
        # will be adding to.
        if add_together and (cur_id or next_id):
            cur_samples, sort_samples, sort_order = \
                    self._sample_list(trans, ids, kwd)
        else:
            cur_samples, sort_samples, sort_order = ([], [], {})
        if messages:
            msg = messages[0]
            msg_type = 'error'
        else:
            msg = ""
            msg_type = None
        return trans.fill_template('/nglims/samples.mako',
            title=request_type.name,
            form_id=kwd['_func_name'],
            form_url=web.url_for(controller=WEB_NAME,
                action=kwd['_func_name']),
            button_name='Save',
            add_finished=False,
            current_samples=cur_samples,
            sort_sample_order=util.json.to_json_string(sort_order),
            sort_samples=sort_samples,
            widgets=send_widgets,
            msg=msg,
            messagetype=msg_type)

    def _sample_list(self, trans, ids, kwd):
        """Retrieve a list of samples, either as a sortable list or a table.
        """
        prep_items = kwd.get('_next_gen_prep', 0)
        cur_samples = []
        sort_samples = []
        all_samples = [trans.sa_session.query(trans.app.model.Sample
                ).get(sid) for sid in ids]
        if not prep_items:
            cur_samples = self._make_displayready(self._get_sample_details(
                all_samples))
            sort_order = {}
        else:
            str_samples = self._make_displayready(self._get_sample_details(
                all_samples, include_barcode=True))
            sort_samples, sort_order = self._prepare_sortable_samples(trans,
                    str_samples, prep_items, kwd)
        return cur_samples, sort_samples, sort_order

    def _prepare_sortable_samples(self, trans, str_samples, sort_items, kwd):
        """Prepare samples ready for sorting to organize on flow cells.

        This hard codes sorting logic and preparation for an illumina flow cell
        and should eventually be extracted into a configurable class.
        """
        seq_config = self._config["sequencing"]
        num_lanes = int(seq_config["lanes"])
        order_info = util.json.from_json_string(kwd.get("sorted_samples", "{}"))
        if len(order_info) == 0:
            for l in range(num_lanes):
                order_info["lane%s" % (l + 1)] = []
        else:
            assert len(order_info) == num_lanes
        sort_samples = []
        control_samples = self._make_displayready(self._get_sample_details(
            self._get_standard_controls(trans), include_barcode=True))
        str_samples.extend(control_samples)
        final_order_info = {}
        samples_to_lanes = collections.defaultdict(list)
        for l, sids in order_info.iteritems():
            final_order_info[l] = []
            for sid in sids:
                samples_to_lanes[int(sid)].append(l)
        for sid, sname, sdescr, _ in str_samples:
            lanes = samples_to_lanes[sid]
            display_name = "%s %s" % (sname, sdescr)
            if len(lanes) == 0:
                sort_samples.append((sid, display_name))
            else:
                for l in lanes:
                    final_order_info[l].append((sid, display_name))
        return sort_samples, final_order_info

    def _get_standard_controls(self, trans):
        """Retrieve the standard controls for a next gen sequence run.
        """
        request_type = trans.sa_session.query(trans.app.model.RequestType
                ).filter_by(name="Control").first()
        request = trans.sa_session.query(trans.app.model.Request).filter_by(
                request_type_id = request_type.id).first()
        return request.samples_by_map()

    @web.expose
    def sample_arrived(self, trans, **kwd):
        """Manage the arrival of samples, moving them to the proper queue.
        """
        ids, cur_id, next_id = self._normalize_ids(**kwd)
        self._move_to_next_queue(trans, ids)

    @web.expose
    @pass_func_name
    def add_construction_details(self, trans, **kwd):
        """Manage the transition from construction to validation.
        """
        kwd['state'] = kwd.get("state", "Construction")
        return self._add_info_and_transition(trans, **kwd)

    @web.expose
    @pass_func_name
    def add_validation(self, trans, **kwd):
        kwd['state'] = kwd.get("state", "Validation")
        return self._add_info_and_transition(trans, **kwd)

    @web.expose
    @pass_func_name
    def add_quantitation(self, trans, **kwd):
        kwd['state'] = kwd.get("state", "Pre-sequencing quantitation")
        return self._add_info_and_transition(trans, **kwd)

    @web.expose
    @pass_func_name
    def add_to_sequencing_run(self, trans, **kwd):
        kwd['state'] = kwd.get("state", "Sequencing")
        kwd['_add_together'] = True
        kwd['_next_gen_prep'] = 8
        return self._add_info_and_transition(trans, **kwd)

    @web.expose
    def prepare_flow_cell(self, trans, **kwd):
        # Back compatibility
        return self.add_to_sequencing_run(trans, **kwd)

    @web.expose
    @pass_func_name
    def redo_sequencing(self, trans, **kwd):
        kwd['state'] = kwd.get("state", "Sequencing confirmation")
        kwd['_move_next'] = "Sequencing"
        kwd['_make_new_request'] = True
        kwd['_default_sqn_info'] = 'Failed'
        return self._add_info_and_transition(trans, **kwd)

    def _prefilled_sqn_info(self, trans, kwd, work_id, sqn_status):
        """Add information about a sequencing run to the results form.

        This pre-fills several items with the correct values that
        can be adjusted and updated as needed in the forms.
        """
        kwd['sequencing_result'] = sqn_status
        if work_id:
            sample = trans.sa_session.query(trans.app.model.Sample
                    ).get(work_id)
            latest_sqn = self._service_org.get_latest_sqn_run(sample)
            if latest_sqn:
                kwd['run_folder'] = latest_sqn["run_folder"]
        return kwd

    @web.expose
    @pass_func_name
    def completed(self, trans, **kwd):
        kwd['state'] = kwd.get("state", "Sequencing confirmation")
        kwd['_make_new_request'] = True
        kwd['_default_sqn_info'] = 'Passed'
        return self._add_info_and_transition(trans, **kwd)

    @web.expose
    @pass_func_name
    def reactivate(self, trans, **kwd):
        """Revert the given samples back to the most recent prior state.
        """
        (ids, _, _) = self._normalize_ids(**kwd)
        all_states = collections.defaultdict(int)
        for sid in ids:
            sample = trans.sa_session.query(trans.app.model.Sample).get(sid)
            # pick the most recent state before this one, and revert back to it
            next_state = sample.events[1].state.name
            new_state = self._service_org.move_sample_to_state(trans, sample,
                    next_state)
            all_states[new_state] += 1
        states = [(count, s) for (s, count) in all_states.items()]
        states.sort(reverse=True)
        trans.response.send_redirect(web.url_for(controller=WEB_NAME,
            action="list_queues", state=states[0][1]))

class _NGLimsREST:
    """Provide a programmatic REST interface to retrieve sequencing results.

    This exposes sequencing runs and sample information at a higher level
    than the database tables for automated processing downstream.
    """
    @web.expose_api
    @require_sequencing
    def api_sequencing_runs(self, trans, **kwd):
        """Retrieve a list of available sequencing runs.
        """
        request_type_name = "%s %s" % (self._service_org.next_gen_name(),
                self._service_org.output_name())
        request_type = self._get_request_type(trans, request_type_name)
        requests = trans.sa_session.query(trans.app.model.Request
                ).filter_by(type=request_type)
        runs = []
        for request in requests:
            request_vals = self.form_value_dict(request.values)
            runs.append(request_vals['run_folder'])
        return dict(runs = runs)

    @web.expose_api
    @require_sequencing
    def api_run_details(self, trans, **kwd):
        """Given the name of a sequencing run, retrieve sample details
        """
        run = kwd.get('run', '')
        details = None
        if run:
            request = self._service_org.sequencing_run_by_search(trans, run)
            if request:
                details = self._details_from_request(trans, request)
        if details is not None:
            out = dict(details=details,
                       run_name=request.name,
                       run_id=request.id)
        else:
            out = {"error": "Did not find sequencing run: %s" % run}
        return out

    def _details_from_request(self, trans, request):
        """Retrieve sequencing details for a run request object.
        """
        details = []
        for order, sample in request.samples_by_map(True):
            prequest = self._project_org.get_sample_project(sample)
            sample_vals = self.form_value_dict(sample.values)
            sample_vals["lane"] = order + 1
            sample_vals["sample_id"] = sample.id
            if prequest is not None:
                project_vals = self.form_value_dict(prequest.values)
                sample_vals['project_name'] = project_vals['project_name']
                sample_vals['payment'] = self._get_payment(project_vals)
                sample_vals["researcher"] = prequest.user.username
                sample_vals["researcher_id"] = prequest.user.id
                sample_vals["private_libs"] = self._get_user_libraries(trans, prequest.user)
                lab_association = ""
                if prequest.user.form_values_id is not None:
                    user_vals = self.form_value_dict_from_id(trans,
                            prequest.user.form_values_id)
                    lab_association = user_vals.get("lab_association",
                            "")
                sample_vals["lab_association"] = lab_association
            details.append(sample_vals)
            for sub_request in sample.requests_by_map():
                subr_vals = self.form_value_dict(sub_request.values)
                subr_name = sub_request.type.name
                if subr_name == "Quantitation details":
                    sample_vals["quantitation"] = \
                            subr_vals["quantitation_results"]
                elif subr_name == "Library construction inputs":
                    sample_vals["adapter"] = subr_vals["adapters"]
                elif subr_name == "Library construction details":
                    sample_vals["concentration"] = \
                            subr_vals["concentration"]
                    sample_vals["insertsize"] = \
                          subr_vals.get("insert_size",
                            subr_vals["insert_size_(including_adapters)"])
                elif subr_name == "Next gen sequencing inputs":
                    sample_vals["cycles"] = subr_vals["cycles"]
                    sample_vals["method"] = subr_vals["method"]
                elif subr_name == "Barcode details":
                    if subr_vals.get("barcodes", None):
                        sample_vals["multiplex"] = subr_vals["barcodes"]
                    else:
                        del subr_vals["barcodes"]
                        sample_vals["barcode"] = subr_vals
        return details

    def _get_user_libraries(self, trans, user):
        """Retrieve libraries accessible to a user, ordered by privacy.
        """
        libraries = trans.app.security_agent.get_accessible_libraries(trans, user)
        available = []
        for lib in libraries:
            roles = [r for r in lib.get_access_roles(trans) if not r.deleted]
            if len(roles) > 0:
                insert_first = user.email in [r.name for r in roles]
                info = (lib.name, roles[0].id)
                if insert_first:
                    available.insert(0, info)
                else:
                    available.append(info)
        return available

    @web.expose_api
    @require_sequencing
    def api_projects(self, trans, **kwd):
        """Retrieve sequencing projects along with high level details.
        """
        projects = []
        rows = []
        for project in self._project_org.get_projects(trans, restrict_to_user=False):
            project_info = self._project_org.form_value_dict(project.values)
            project_info['researcher'] = project.user.username
            project_info['last_updated'] = project.update_time.strftime(
                    "%b %d, %Y")
            projects.append((project.update_time, project_info))
        projects.sort(reverse=True)
        out = dict(projects=[p[1] for p in projects])
        return out

    @web.expose_api
    @require_sequencing
    def api_sqn_report(self, trans, **kwd):
        """Provide a report of sequencing accomplished within a time period.
        """
        finished_state = 'Complete'
        start = datetime.strptime(kwd['start'], "%Y-%m-%dT%H:%M:%S")
        end = datetime.strptime(kwd['end'], "%Y-%m-%dT%H:%M:%S")

        samples_seen = []
        samples = []
        for sample, project in self._get_samples_by_state(trans, finished_state,
                start, end):
            if sample.id not in samples_seen:
                samples_seen.append(sample.id)
                for run in self._get_sample_runs(sample):
                    project_info = self._project_org.form_value_dict(project.values)
                    sample_info = self._project_org.form_value_dict(sample.values)
                    user_vals = self.form_value_dict_from_id(trans,
                            project.user.form_values_id)
                    project_info['researcher'] = project.user.username
                    project_info['email'] = project.user.email
                    project_info['lab_association'] = user_vals.get(
                        "lab_association", "")
                    sample_info["project"] = project_info
                    sample_info["sqn_type"] = self._project_org.sample_summary(sample)
                    sample_info["sqn_run"] = run
                    sample_info["events"] = self._get_sample_events(sample)
                    samples.append(sample_info)
        return samples

    def _get_sample_runs(self, sample):
        """Retrieve all sequencing runs and lanes for a sample in the time period.
        """
        for run in self._service_org.get_sample_sqn_runs(sample):
            notes = self._service_org.get_sqn_run_results(sample, run["run_folder"])
            if notes is not None:
                run["results_notes"] = notes
                yield run

    def _get_sample_events(self, sample):
        """Retrieve events and timestamps for this sample.
        """
        def event_time(x):
            return x.update_time.strftime("%b %d, %Y")
        out = [{"event": "arrived",
                "time": event_time(self._service_org.get_sample_arrived_event(sample))}]
        for event in sample.events:
            out.append({"event": event.state.name,
                        "time": event_time(event)})
        return out

    def _get_samples_by_state(self, trans, want_state, start, end):
        """Retrieve samples and projects
        """
        state = trans.sa_session.query(trans.app.model.SampleState).filter_by(
                name=want_state).first()
        events = trans.sa_session.query(trans.app.model.SampleEvent).filter_by(
                 sample_state_id = state.id).filter(
                 "update_time > '%s'" % start.strftime("%Y-%m-%d %H:%M:%S")
                 ).filter(
                 "update_time < '%s'" % end.strftime("%Y-%m-%d %H:%M:%S"))
        for e in events:
            sample = trans.sa_session.query(trans.app.model.Sample).get(
                    e.sample_id)
            if sample.state.name == want_state:
                request = self._project_org.get_sample_project(sample)
                yield sample, request

    @web.expose_api
    @require_sequencing
    def api_upload_sqn_run_summary(self, trans, **kwd):
        """Upload summary of a sequencing run, saving in SqnRunResults table.
        """
        form_def = trans.sa_session.query(trans.app.model.FormDefinition
                ).filter_by(type=trans.app.model.FormDefinition.types.SQNRESULTS).first()
        if form_def is None:
            return dict(error="No sequencing results form. Run setup script.")
        for lane_info in kwd["payload"]["lanes"]:
            form_content = {}
            for field in form_def.fields:
                form_content[field['name']] = lane_info["metrics"].get(
                        field["label"], "")
            cur_results = trans.sa_session.query(trans.app.model.SqnRunResults
                    ).filter_by(lane=lane_info['lane']).filter_by(
                            request_id=lane_info['request']).filter_by(
                            sample_id=lane_info['sample']).first()
            if cur_results is None:
                cur_results = trans.app.model.SqnRunResults()
                cur_results.lane = lane_info['lane']
                cur_results.request_id = lane_info['request']
                cur_results.sample_id = lane_info['sample']
                cur_results.form_values = trans.app.model.FormValues(form_def,
                        form_content)
                trans.sa_session.add(cur_results)
            else:
                cur_results.form_values.content = form_content
            if lane_info.get("researcher", ""):
                cur_results.user_id = lane_info["researcher"]
            trans.sa_session.flush()

class NGLims(BaseUIController, _FormMixin, _RequestMixin, _NGLimsSequencingQueue,
        _NGLimsREST, _NGLimsResultsAnalysis, _NGLimsMultiplex, _NGLimsPlotting):
    def __init__(self, app):
        BaseUIController.__init__(self, app)
        self._testing = False
        self._load_config()
        self._err_msg = "nglims not yet configured. "\
                "Please see the documentation to enable."

    def _load_config(self):
        config_file = self.app.config.get("nglims_config_file", "")
        if config_file and os.path.exists(config_file):
            in_handle = open(config_file)
            self._config = yaml.load(in_handle)
            in_handle.close()
            self._service_org = _ServiceOrganizer(self._config, self._testing)
            self._project_org = _ProjectOrganizer(self._config, self._service_org,
                    self._testing)
        else:
            self._service_org = None

    @web.expose
    def index( self, trans, **kwd ):
        self._load_config()
        if self._service_org is None:
            return self._err_msg
        else:
            return trans.fill_template("nglims/index.mako",
               start_url=web.url_for(controller=WEB_NAME,
                   action="services_to_samples"),
               section_info=self._get_section_details(trans))

    def _get_section_details(self, trans):
        """Return the sections and items that organize our customer management.
        """
        if trans.user:
            user_roles = [r.name for r in trans.user.all_roles()]
        else:
            user_roles = []
        base_info = [
            ('Samples', [
              ('Define samples and services', web.url_for(controller=WEB_NAME,
                action="services_to_samples")),
              ('Submit samples as a project', web.url_for(controller=WEB_NAME,
                action="samples_to_project")),
              ('View projects', web.url_for(controller=WEB_NAME,
                action="list_projects")),
              ('Sequencing results', web.url_for(controller=WEB_NAME,
                action="list_sqn_results")),
              ])
            ]
        if 'sequencing' in user_roles:
            base_info.append(
            ('Sequencing', [
              ('Queues', web.url_for(controller=WEB_NAME,
                action="list_queues")),
              ('Runs', web.url_for(controller=WEB_NAME,
                action="list_sqn_runs")),
              ('Plots', web.url_for(controller=WEB_NAME,
                action="sqn_plots")),
             ]))
        return base_info

    def _move_to_next(self, trans, **kwd):
        try:
            cur_position = LIMS_ORDER.index(kwd['form_id'])
            next_id = LIMS_ORDER[cur_position + 1]
        except (IndexError, ValueError):
            next_id = None
        if next_id:
            trans.response.send_redirect(web.url_for(controller=WEB_NAME,
                action=next_id))
        else:
            return "Finished"

    def _make_displayready(self, retrieval_fn):
        final_info = []
        for sid, name, descr, details in retrieval_fn:
            descr_parts = []
            for key, val in details.items():
                key = " ".join(key.split("_"))
                key = key[0].upper() + key[1:]
                if type(val) in [list, tuple]:
                    val = ", ".join(val)
                descr_parts.append("%s: %s" % (key, val))
            final_info.append((sid, name, descr, "; ".join(descr_parts)))
        return final_info

    @web.expose
    @web.require_login("manage sequencing samples")
    def services_to_samples(self, trans, **kwd):
        """Entry point for adding details about a sample to be sequenced.
        """
        params = self._normalize_sample_kwds(kwd)
        params = self._update_sample_entry_params(trans, params)
        widgets = self._get_sample_widgets(trans, params)
        widgets = self._widgets_by_step(trans, params, widgets,
                                        "initial")
        return trans.fill_template('/nglims/sample_entry.mako',
            form_id="services_to_samples",
            form_url=web.url_for(controller=WEB_NAME,
                action="save_sample"),
            current_samples =
                self._add_display_url(trans,
                self._add_multiplex_url(trans,
                self._add_edit_url(trans,
                self._make_displayready(
                self._get_sample_details(
                self._saved_samples(trans, **kwd)))))),
            widgets=widgets)

    @web.expose
    @web.require_login("manage sequencing samples")
    def get_sample_form_detailed(self, trans, **kwd):
        """Retrieve detailed forms for entering sample information.
        """
        params = self._normalize_sample_kwds(kwd)
        params = self._update_sample_entry_params(trans, params, False)
        widgets = self._widgets_by_step(trans, params, [], "detailed")
        return trans.fill_template("/nglims/sample_entry_detailed.mako",
                widgets=widgets)

    @web.expose
    @web.require_login("manage sequencing samples")
    def save_sample(self, trans, **kwd):
        """Save a sample with all provided form details.
        """
        params = self._normalize_sample_kwds(kwd)
        cur_sample, error_msgs = self._save_service_request(trans, params)
        assert len(error_msgs) == 0, error_msgs
        barcodes = kwd.get('multiplex_barcodes', '')
        if barcodes and barcodes not in ["{}"] and cur_sample.id:
            self.assoc_barcodes(trans, data=barcodes,
                    parent_id=trans.security.encode_id(cur_sample.id))
        callback = params.get("callback", "")
        if callback:
            callback = callback.replace("__", "&")
            trans.response.send_redirect(callback)
        else:
            trans.response.send_redirect(web.url_for(controller=WEB_NAME,
                                                     action="services_to_samples"))

    @web.expose
    @web.require_login("manage sequencing samples")
    def edit_sample(self, trans, **kwd):
        """Edit all of the details of an existing sample.
        """
        only_sample = kwd.get("onlysample", "").upper() == "TRUE"
        params = self._normalize_sample_kwds(kwd)
        params = self._update_sample_entry_params(trans, params)
        widgets = self._get_sample_widgets(trans, params)
        widgets = self._widgets_by_step(trans, params, widgets,
                                        "detailed", not only_sample)
        return trans.fill_template('/nglims/samples.mako',
            form_id="services_to_samples",
            form_url=web.url_for(controller=WEB_NAME,
                                 action="save_sample",
                                 callback=trans.request.referer.replace("&", "__")),
            current_samples = [],
            widgets=widgets)

    def _normalize_sample_kwds(self, kwd):
        # Strip out the actual name of a build from the description
        dbkey_label = self._form_label(self._service_org.dbkey_label)
        dbkey_str = kwd.get(dbkey_label, "")
        if dbkey_str:
            parts = dbkey_str.split(" (")
            dbkey_str = parts[-1][:-1]
        kwd[dbkey_label] = dbkey_str
        params = util.Params(kwd)
        return params

    def _entry_step(self, params, buttons):
        """Retrieve the current step that we are in during sample entry.
        """
        if params.get("create_request_button", None) == buttons['cont']:
            return "high-level"
        elif (params.get("create_request_button", None)  == buttons['save'] or
              params.get("create_request_button_done", "") == buttons['finished']):
            return "final"
        elif params.get("create_request_button", None) is None:
            return "initial"
        else:
            raise ValueError("Unexpected step: %s" % params)

    def _widgets_by_step(self, trans, params, widgets, cur_step,
                         include_request_widgets=True):
        """Add additional display widgets based on our current processing step.
        """
        if cur_step == "detailed":
            request_ids = []
            display_requests = []
            services = params.get("services",
                                  params.get("services[]", []))
            if not isinstance(services, list):
                services = [services]
            for cur_request_ids in [s.split(",") for s in services]:
                cur_request_ids = [int(i) for i in cur_request_ids]
                for dname in self._service_org.type_ids_to_display_name(
                        trans, cur_request_ids):
                    if dname not in display_requests:
                        display_requests.append(dname)
                request_ids.extend(cur_request_ids)
            if include_request_widgets:
                for select_widget in self._service_org.selected_widgets(trans,
                        request_ids):
                    widgets.append(self._add_form_label(select_widget, params))
            else:
                widgets.append(dict(label="", helptext="", widget=HiddenField(
                    "sampleonly", "true")))
            widgets.append(dict(label="", helptext="", widget=HiddenField(
                "services", ",".join([str(r) for r in request_ids]))))
            widgets.append(dict(label="", helptext="", widget=HiddenField(
                "service_names", ",".join(display_requests))))
        elif cur_step == "initial":
            widgets.append(dict(label="Multiplexed",
                widget=CheckboxField("is_multiplex"), helptext="",
                title="Indicate if the sample uses barcoding. "
                      "Barcode details will be entered after the sample information."))
            widgets.append(self._service_org.multiselect_request_type(trans,
                self._service_org.default_services))
        else:
            raise ValueError("Unexpected step: %s" % cur_step)
        return widgets

    def _update_sample_entry_params(self, trans, params, update_sample_vals=True):
        """Update entry parameters based on our current entry step.
        """
        # if we are editing an existing sample, load up the paramters
        if params.get("editid", ""):
            edit_id = trans.security.decode_id(params.get("editid", ""))
            sample = trans.sa_session.query(trans.app.model.Sample).get(edit_id)
            new_params = self._get_sample_params(sample)
            new_params["services"] = self._service_org.display_name_to_type_ids(
                    trans, sample.desc.split(","))
            new_params["service_names"] = sample.desc
            #new_params["create_request_button"] = buttons["cont"]
            params.update(new_params)
        else:
            params = self._update_last_params(trans, params,
                                               update_sample_vals)
        return params

    def _get_sample_widgets(self, trans, params):
        """Retrieve high level widgets associated with a sample.
        """
        widgets = []
        # load sample information from our requests sample form
        sample_form = self._service_org.get_sample_form(trans)
        if sample_form is None:
            raise ValueError(self._err_msg)
        for widget in sample_form.get_widgets(trans.user):
            widget = self._add_form_label(widget, params)
            if widget['label'] == self._service_org.dbkey_label:
                widget = self._get_organism_choice_widget(widget)
            elif widget['label'] == 'Name':
                widget = self._get_name_widget(trans, widget, self._project_org)
            widgets.append(widget)
        return widgets

    def _add_display_url(self, trans, items):
        """Add a URL for displaying additional sample information.
        """
        fitems = []
        for group in items:
            sid = group[0]
            display_url = web.url_for(controller=WEB_NAME,
                    action="show_project_samples",
                    display="sample_details",
                    id=trans.security.encode_id(sid))
            fitems.append(group + (display_url,))
        return fitems

    def _add_multiplex_url(self, trans, items):
        """Add a URL reference to associated barcodes for multiplexing.
        """
        fitems = []
        for parts in items:
            multi_url = web.url_for(controller=WEB_NAME,
                    action="add_barcode",
                    parent_id=trans.security.encode_id(parts[0]))
            fitems.append(parts + (multi_url,))
        return fitems

    def _add_edit_url(self, trans, items):
        """Add a URL callback to allow editing a sample.
        """
        fitems = []
        for sid, sname, sdescr, sdetails in items:
            edit_url = web.url_for(controller=WEB_NAME,
                    action="edit_sample",
                    editid=trans.security.encode_id(sid))
            fitems.append((sid, sname, sdescr, sdetails, edit_url))
        return fitems

    def _update_last_params(self, trans, params, update_sample_vals):
        """Retrieve the last loaded parameters to fill in form boxes.

        This provides nice defaults from the last entry to get things started.
        """
        ignore_params = ["name", "description"]
        last_sample = None
        for sample in trans.sa_session.query(trans.app.model.Sample).order_by(
                "create_time DESC"):
            if sample.request.user == trans.user:
                last_sample = sample
                break
        if last_sample:
            new_params = self._get_sample_params(last_sample, update_sample_vals,
                    ignore_params)
            params.update(new_params)
        return params

    def _get_sample_params(self, sample, update_sample_vals=True,
            ignore_params=None):
        """Retrieve a dictionary of form parameters from the given sample.
        """
        if ignore_params is None:
            ignore_params = []
        new_params = dict()
        if update_sample_vals:
            sample_info = self.form_value_dict(sample.values)
            new_params.update(sample_info)
        for request in sample.requests_by_map():
            request_info = self.form_value_dict(request.values)
            new_params.update(request_info)
        for ignore in ignore_params:
            if new_params.has_key(ignore):
                del new_params[ignore]
        return new_params

    def _save_service_request(self, trans, params):
        """Save the details about a sample and service request.

        This checks for any missing required fields, returning appropriate
        error messages. If everything is here, the request will be saved and
        an empty list is returned.
        """
        request_ids = [int(r) for r in params.get("services", "").split(",")]
        # check if we are updating an existing sample
        # if so, update the data for that sample instead of adding new data
        cur_sample = trans.sa_session.query(trans.app.model.Sample).filter_by(
                name=params.get("name", "")).first()
        if cur_sample is not None:
            request_types = self._service_org.get_request_types(trans,
                    request_ids)
            sample_vals = self._get_form_values(trans, request_types[0].sample_form,
                    params)
            cur_sample.values = sample_vals
            if params.get("sampleonly", "").lower() != "true":
                all_forms = [t.request_form for t in request_types]
                all_forms.insert(0, request_types[0].sample_form)
                for request_type in request_types:
                    self._add_sub_request_data(trans, [cur_sample], request_type, params)
            else:
                all_forms = []
            all_requests = []
        # add the sample from scratch
        else:
            all_forms, all_requests, cur_sample = self._add_new_sample(trans,
                    params, request_ids)
        messages = self._check_submission(all_forms, params)
        # if we have messages, return those because we need to fix the form.
        if messages:
            return None, messages
        # otherwise save the request
        else:
            for i, request in enumerate(all_requests):
                sample_map = trans.app.model.SampleRequestMap(cur_sample,
                        request, i, True)
            if not self._testing:
                trans.sa_session.flush()
            return cur_sample, []

    def _add_new_sample(self, trans, params, request_ids):
        """Prepare a brand new sample using supplied form parameters.
        """
        all_requests = []
        all_forms = []
        for request_type in self._service_org.get_request_types(trans,
                request_ids):
            all_forms.append(request_type.request_form)
            form_values = self._get_form_values(trans,
                    request_type.request_form, params)
            trans.sa_session.add(form_values)
            cur_request = self._new_request(trans, request_type, form_values,
                    params, trans.app.model.Request.states.NEW)
            all_requests.append(cur_request)
            # get the sample form -- all requests have the same so keep the last
            sample_form = request_type.sample_form
        all_forms.insert(0, sample_form)
        sample_vals = self._get_form_values(trans, sample_form, params)
        trans.sa_session.add(sample_vals)
        # create a new sample
        cur_sample = trans.app.model.Sample(params.get("name", ""),
                params.get("service_names", ""), all_requests[0], sample_vals)
        trans.sa_session.add(cur_sample)
        return all_forms, all_requests, cur_sample

    def _check_submission(self, forms, params):
        """Determine if the submission paramters have required form information.

        This is the error checking step of form submission, making sure all
        required items have been passed.
        """
        messages = []
        for form in forms:
            for field in form.fields:
                form_label = self._form_label(field['label'])
                cur_val = params.get(form_label, None)
                if ((not cur_val or cur_val in ["?"]) and 
                        field['required'] == 'required'):
                    messages.append("Please enter information for: %s" %
                            field["label"])
        return messages

    def _saved_samples(self, trans, **kwd):
        """Retrieve information on saved samples available for submission.
        """
        event_q = trans.app.model.RequestEvent
        request_q = trans.app.model.Request
        query = trans.sa_session.query(trans.app.model.Sample)
        query = query.join(request_q).filter(request_q.user == trans.user)
        query = self._filter_request_by_state(trans, query,
                trans.app.model.Request.states.NEW)
        return query
        # XXX This needs to be a filtered query. It'll slow down once
        # we have a lot of samples.
        # samples = []
        #for sample in trans.sa_session.query(trans.app.model.Sample):
        #    if (sample.request.user == trans.user and
        #            sample.request.state == 
        #        samples.append(sample)
        #return samples

    def _get_sample_details(self, samples, include_barcode=False):
        """Retrieve high level summary for a group of samples.
        """
        summary = []
        for sample in samples:
            services = []
            for request in sample.requests_by_map():
                services.append(" ".join(request.type.name.split(" ")[:-1]))
            sample_details = self.form_value_dict(sample.values)
            name = sample_details['name']
            descr = sample_details['description']
            if include_barcode:
                barcode = self._service_org.get_barcode(sample)
                if barcode.get("barcode_id", ""):
                    descr += " [%s %s]" % (barcode["barcode_type"],
                                           barcode["barcode_id"])
                elif barcode.get("barcodes", ""):
                    descr += " [%s]" % self._text_barcode_summary(barcode["barcodes"])
                sort_item = (barcode.get("date", datetime.now()), sample.id)
            else:
                sort_item = sample.id
            out_info = dict()
            out_info['services'] = sample.desc.split(",")
            try:
                sqn_info = self._project_org.sample_summary(sample)
            except ValueError:
                sqn_info = ""
            out_info['sequencing'] = sqn_info
            summary.append((sort_item, (sample.id, name, descr, out_info)))
        if include_barcode:
            summary.sort()
        return [s for (_, s) in summary]

    @web.expose
    @web.require_login("manage sequencing samples")
    def samples_to_project(self, trans, **kwd):
        """Define project details and assign samples to your project.
        """
        buttons = dict(
            save = "Submit")
        params = util.Params(kwd)
        is_submit = (params.get("create_request_button", None) == buttons['save'])
        try:
            project_form = self._project_org.get_project_form(trans)
        except ValueError:
            return self._err_msg
        message_type = None
        if is_submit:
            messages = self._check_submission([project_form], params)
            if len(messages) > 0:
                message_type = 'error'
        else:
            messages = []
        widgets = []
        for widget in project_form.get_widgets(trans.user):
            widget = self._add_form_label(widget, params)
            widgets.append(widget)
        options = []
        for sid, sname, sdescr, sdetails in self._make_displayready(
                self._get_sample_details(self._saved_samples(trans, **kwd))):
            options.append(dict(name="%s: %s -- %s" % (sname, sdescr, sdetails),
                value=str(sid), options=[]))
        picked_vals = params.get('samples', [])
        if not picked_vals and is_submit:
            message_type = 'error'
            messages.append('Please enter information for: Samples')
        if len(options) == 0:
            message_type = 'error'
            messages.append('Please describe some samples before submitting '
                            'a project')
        widgets.append(dict(label="Samples", helptext="",
            widget=DrillDownField("samples", multiple=True,
                display="checkbox", options=options, value=picked_vals)))
        if len(messages) == 0:
            message_type = "info"
            messages.append(self._config["messages"]["dropoff"])
        if (is_submit and message_type not in ["error"]):
            self._project_org.save_project(trans, params)
            return self._move_to_next(trans, **kwd)
        else:
            if messages:
                msg = messages[0]
            else:
                msg = ""
            return trans.fill_template('/nglims/form_entry.mako',
                title="Specify project details",
                form_id="samples_to_project",
                form_url=web.url_for(controller=WEB_NAME,
                    action="samples_to_project"),
                msg=msg,
                messagetype=message_type,
                button_name=buttons['save'],
                widgets=widgets)

    def _handle_grid_kwds(self, trans, **kwd):
        """Provide redirects for various requests associated with grids.
        """
        if ('operation' in kwd or 'display' in kwd) and 'id' in kwd:
            op = kwd.get('operation', None)
            if op is None:
                op = kwd['display']
            operation = op.lower().replace(" ", "_")
            if not isinstance(kwd['id'], list):
                ids = kwd['id'].split(",")
            else:
                ids = kwd['id']
            op_ids = [trans.security.decode_id(i) for i in ids if i]
            del kwd['id']
            if kwd.has_key('operation'):
                del kwd['operation']
            else:
                del kwd['display']
            if len(op_ids) > 0:
                trans.response.send_redirect(web.url_for(controller=WEB_NAME,
                    action=operation, ids=op_ids, **kwd))
            else:
                trans.response.send_redirect(trans.request.referrer)
        elif 'f-free-text-search' in kwd:
            trans.response.send_redirect(web.url_for(controller=WEB_NAME,
                action="show_project_samples",
                search=kwd['f-free-text-search']))
        elif 'f-results-search' in kwd:
            kwd['search'] = kwd['f-results-search']
            del kwd['f-results-search']
            del kwd["sort"]
        return kwd

    @web.expose
    @web.require_login("manage sequencing samples")
    def list_projects(self, trans, **kwd):
        """List all submitted projects that need to be processed.
        """
        kwd = self._handle_grid_kwds(trans, **kwd)
        if 'sequencing' in [r.name for r in trans.user.all_roles()]:
            kwd['_allow_edit'] = True
        request_grid = _ProjectGrid(self._project_org)
        return request_grid(trans, **kwd)

    @web.expose
    def show_project_samples(self, trans, **kwd):
        kwd = self._handle_grid_kwds(trans, **kwd)
        kwd['_include_state'] = True
        if 'sequencing' in [r.name for r in trans.user.all_roles()]:
            kwd['_allow_edit'] = True
        grid = _SampleDetailsGrid(self._project_org, self._service_org)
        return grid(trans, **kwd)

    @web.expose
    def sample_details(self, trans, **kwd):
        """Display a sample and associated requests. For HTML output.
        """
        allow_edit = kwd.get("edit", "").upper() == "TRUE"
        sample = trans.sa_session.query(trans.app.model.Sample).get(
                kwd['ids'])
        sample_info = self.form_value_dict(sample.values)
        services, service_details, service_ids = \
                self._saved_sample_details(sample)
        edit_urls = dict()
        base_edit = None
        if allow_edit:
            base_edit = web.url_for(controller=WEB_NAME, action="edit_sample",
                                    editid=trans.security.encode_id(sample.id),
                                    onlysample=True)
            for sname, sid_group in service_ids.iteritems():
                edit_urls[sname] = []
                # special case of barcode editing
                if sname == "Barcode":
                    assert len(sid_group) == 1
                    edit_urls[sname].append(web.url_for(
                        controller=WEB_NAME, action="add_barcode",
                        parent_id=trans.security.encode_id(sample.id)))
                # standard case
                else:
                    for sids in sid_group:
                        edit_urls[sname].append(web.url_for(controller=WEB_NAME,
                            action="edit_request",
                            sid=trans.security.encode_id(sample.id),
                            rids=util.json.to_json_string(
                                [trans.security.encode_id(i) for i in sids])))
        sqn_runs = self._service_org.get_sample_sqn_runs(sample)
        ignore = ["name"]
        ready_sample_info = []
        for key, value in sorted(sample_info.iteritems()):
            if key not in ignore and value:
                new_key = key[0].upper() + " ".join(key[1:].split("_"))
                ready_sample_info.append([new_key, value])
        return trans.fill_template('/nglims/sample_details.mako',
                name=sample_info["name"],
                sample_info=ready_sample_info,
                services=services,
                sqn_runs=sqn_runs,
                service_details=service_details,
                base_edit=base_edit,
                edit_urls=edit_urls)

    @web.expose
    @pass_func_name
    def edit_request(self, trans, **kwd):
        """Edit an existing request associated with a sample.
        """
        messages = []
        new_request = True
        # handle editing a top level project request
        if kwd.get("edit", "").upper() == "TRUE":
            request_ids = [kwd['ids']]
            kwd["rids"] = util.json.to_json_string(
                [trans.security.encode_id(i) for i in request_ids])
            kwd["sid"] = ""
            add_together = True
        else:
            request_ids = [trans.security.decode_id(i) for i in
                           util.json.from_json_string(kwd['rids'])]
            add_together = False
        # check if we are saving existing information
        if kwd.get('create_request_button', None) == 'Save':
            new_request = False
            # standard addition of requests to samples
            if kwd.get("sid", ""):
                cur_id = kwd.get('cur_id', None)
                kwd["_make_new_request"] = False
                for request_id in request_ids:
                    request = trans.sa_session.query(trans.app.model.Request).get(request_id)
                    messages.extend(self._check_and_add_sample_data(trans, cur_id, [cur_id],
                            request.type, False, kwd))
            # top level addition of a request only
            else:
                add_together = True
                messages = self._edit_top_level_request(trans, kwd, request_ids[0])
        # if a new request or there are errors, present the edit form
        if new_request or len(messages) > 0:
            kwd["state"] = "Edit"
            sample_id = trans.security.decode_id(kwd['sid']) if kwd.get("sid", "") else ""
            widgets = []
            for request_id in request_ids:
                request = trans.sa_session.query(trans.app.model.Request).get(request_id)
                # add existing values for display
                request_info = self.form_value_dict(request.values)
                kwd.update(request_info)
                widgets.extend(request.type.request_form.get_widgets(trans.user))
            if new_request:
                messages = []
            return self._sample_submission_form(trans, [sample_id],
                    sample_id, sample_id, widgets, messages, request.type,
                    add_together, kwd)
        else:
            if kwd.get("cur_id", None):
                sample = trans.sa_session.query(trans.app.model.Sample).get(kwd["cur_id"])
            else:
                sample = None
            self._redirect_to_edit(trans, sample)

    def _edit_top_level_request(self, trans, kwd, rid):
        """Edit a high level requests like project information.
        """
        params = util.Params(kwd)
        request = trans.sa_session.query(trans.app.model.Request).get(rid)
        cur_form = request.values.form_definition
        messages = self._check_submission([cur_form], params)
        if len(messages) == 0:
            request.values = self._get_form_values(trans, cur_form, params)
            if not self._testing:
                trans.sa_session.flush()
        return messages

    def _redirect_to_edit(self, trans, sample):
        project_id = None
        if sample:
            for parent in sample.parent_requests_by_map():
                if parent.type.name == 'Project':
                    project_id = parent.id
                    break
        if project_id:
            trans.response.send_redirect(web.url_for(controller=WEB_NAME,
                action="show_project_samples", ids=project_id,
                _allow_edit="true"))
        else:
            trans.response.send_redirect(web.url_for(controller=WEB_NAME,
                action="list_projects"))

    @web.expose
    @pass_func_name
    def modify_state(self, trans, **kwd):
        """Modify the state of passed constructs; an admin level function.
        """
        (ids, _, _) = self._normalize_ids(**kwd)
        new_state = kwd.get('new_state', None)
        samples = []
        for sid in ids:
            samples.append(trans.sa_session.query(trans.app.model.Sample).get(sid))
        # if we have a state, move the samples over to it
        if new_state:
            sample = None
            for sample in samples:
                new_state = self._service_org.move_sample_to_state(trans, sample,
                        new_state)
            self._redirect_to_edit(trans, sample)
        # otherwise display a form which allows us to select a state
        else:
            messages = []
            widgets = []
            select = SelectField("new_state")
            for state in self._service_org.get_states():
                select.add_option(state, state)
            widgets.append(dict(label="New state", helptext="",
                    widget=select))
            widgets.append(dict(label="", helptext="",
                    widget=HiddenField("ids", ",".join([str(i) for i in ids]))))
            if messages:
                msg = messages[0]
                msg_type = 'error'
            else:
                msg = ""
                msg_type = None
            return trans.fill_template('/nglims/samples.mako',
                title="Modify state",
                form_id=kwd['_func_name'],
                form_url=web.url_for(controller=WEB_NAME,
                    action=kwd['_func_name']),
                button_name='Save',
                add_finished=False,
                current_samples=self._add_display_url(trans,
                                self._add_empty(
                                self._add_empty(
                                self._make_displayready(
                                self._get_sample_details(
                                samples))))),
                sort_sample_order=None,
                sort_samples=None,
                widgets=widgets,
                msg=msg,
                messagetype=msg_type)

    def _add_empty(self, items):
        fitems = []
        for item in items:
            item = item + ("",)
            fitems.append(item)
        return fitems

    def _saved_sample_details(self, sample):
        """Retrieve details on all information available for a sample.
        """
        services = []
        full_services_seen = []
        service_info = dict()
        service_ids = dict()
        for request in sample.requests_by_map():
            request_info = self.form_value_dict(request.values)
            service_name = " ".join(request.type.name.split(" ")[:-1])
            if service_name not in services:
                services.append(service_name)
                service_info[service_name] = []
                service_ids[service_name] = []
            # if we've already seen this service, add a new version
            # to avoid overwriting
            if (request.type.name in full_services_seen or
                    len(service_info[service_name]) == 0):
                service_info[service_name].append(request_info)
                service_ids[service_name].append([request.id])
            # otherwise update the combined version
            else:
                service_info[service_name][-1].update(request_info)
                service_ids[service_name][-1].append(request.id)
            full_services_seen.append(request.type.name)
        services = self._service_org.order_services(services)
        return services, service_info, service_ids

class _SampleDetailsGrid(grids.Grid, _RequestMixin):
    """Display details for a sample request within a project.
    """
    template = "/nglims/sample_details_grid.mako"
    model_class = model.Sample
    def __init__(self, project_org, service_org, default_sort=None):
        self.columns = [
            grids.GridColumn("ID", key="id", visible=False),
            grids.GridColumn("Name", key="name",
                 link=(lambda item: dict(display="sample_details", id=item.id))),
            grids.GridColumn("Description", key="description"),
            grids.GridColumn("Researcher", key="researcher"),
            grids.GridColumn("Sequencing", key="seq_type"),
            grids.GridColumn("Services", key="services"),
            grids.GridColumn("Barcode", key="barcode"),
            grids.GridColumn("Last update", key="update_time"),
            ]
        self.operations = []
        grids.Grid.__init__(self)
        self._project_org = project_org
        self._service_org = service_org
        self._default_sort = default_sort

    def __call__(self, trans, **kwargs):
        # save sort before the call, and handle it later
        self._cur_sort = kwargs.get('sort', None)
        # override our table class to handle not having the column
        # add it in, and then take it back out so sort won't complain
        # XXX This is a bad hack to work around non-db derived tables
        next_sort = None
        if self._cur_sort:
            if self._cur_sort.startswith("-"):
                name = self._cur_sort[1:]
            else:
                name = self._cur_sort
            self.model_class.table.c.add(Column(name))
        out = grids.Grid.__call__(self, trans, **kwargs)
        if self._cur_sort:
            self.model_class.table.c.remove(Column(name))
        return out
    
    def apply_query_filter(self, trans, query, **kwd):
        if kwd.has_key('_include_lane'):
            self.columns.insert(0,
                    grids.GridColumn("Lane", key="lane"))
        if kwd.has_key('_include_sqn_run'):
            self.columns.insert(-1,
                    grids.GridColumn("Run", key="sqn_run"))
        if kwd.has_key('_include_state'):
            self.columns.insert(-1,
                    grids.GridColumn("State", key='state'))
        if kwd.has_key("_include_date_received"):
            self.columns.insert(-1,
                    grids.GridColumn("Received", key="received"))
        if kwd.has_key("_allow_edit"):
            self.columns.append(grids.GridColumn("", key="edit_barcodes",
                    link = (lambda item: dict(display="add_barcode",
                        id=item.id, parent_id=trans.security.encode_id(item.id)))))
            self.columns.append(grids.GridColumn("", key="edit",
                    link = (lambda item: dict(display="sample_details",
                        id=item.id, edit="true"))))
            self.operations.append(grids.GridOperation("Modify state"))
        if self._default_sort is None:
            for column in self.columns:
                column.sortable=False
        if kwd.has_key('ids'):
            items = self._samples_by_project(trans, kwd['ids'])
        elif kwd.has_key('search'):
            items = self._samples_by_search(trans, kwd['search'])
        else:
            items =  self._samples_by_state(trans, kwd['state'])
        return _QueryLikeList(items)

    def _samples_by_search(self, trans, search_term):
        """Retrieve samples matching a provided search term.

        This implements free-text-searching of samples for quickly finding items
        of interest.

        Finds the term using a case-insensitive search in either:
        sample name
        user name or user e-mail
        within the specifications of the sample (description text)

        The description text search is hairy because the underlying column is a
        blob not text, so it needs to be converted to text before comparing.
        """
        model = trans.app.model
        if search_term == 'search':
            search_term = ''
        query = trans.sa_session.query(model.Sample).join(
                model.Request)
        query = self._filter_request_by_state(trans, query,
                model.Request.states.SUBMITTED)
        user_roles = [r.name for r in trans.user.all_roles()]
        if 'sequencing' not in user_roles:
            query = query.filter(model.Request.user == trans.user)
        if search_term:
            query = query.join(model.User).join(model.Sample.values)
            term = '%' + search_term.lower() + '%'
            # SQLite has good handling of Blobs
            if trans.app.model.engine.name in ["sqlite"]:
                search_phrase = func.lower(model.FormValues.content).like(term)
            elif trans.app.model.engine.name in ["postgres"]:
                # Use escape since not all postgres have UTF8. Won't internationalize
                # but should work for our needs
                search_phrase = "lower(encode(form_values.content, 'escape')) LIKE '%s'" % (term)
            # others (MySQL tested) require conversion
            else:
                search_phrase = "LOWER(CONVERT(form_values.content USING utf8)) LIKE '%s'" % (term)
            query = query.filter(or_(
                func.lower(model.Sample.name).like(term),
                search_phrase,
                func.lower(model.User.username).like(term),
                func.lower(model.User.email).like(term),
                ))
        self.title = "Search: %s" % search_term
        return self._rows_from_samples([(0, s) for s in query])

    def _samples_by_state(self, trans, state):
        """Retrieve all samples beloning to a particular state.
        """
        pass_samples = []
        for sample in trans.sa_session.query(trans.app.model.Sample):
            if sample.state and sample.state.name == state:
                pass_samples.append((0, sample))
        return self._rows_from_samples(pass_samples)

    def _samples_by_project(self, trans, project_id):
        """Retrieve all samples belonging to a specified project.
        """
        request = trans.sa_session.query(trans.app.model.Request).get(
                project_id)
        rows = self._rows_from_samples(request.samples_by_map(
            include_order=True))
        # side effect. Ugh.
        request_dict = self._project_org.form_value_dict(request.values)
        name = ""
        for toget in ["project_name", "run_folder"]:
            name = request_dict.get(toget, "")
            if name:
                break
        self.title = "%s -- %s" % (name, request.user.username)
        return rows

    def _rows_from_samples(self, samples):
        rows = []
        # set up our sorting parameter
        if self._cur_sort and self._cur_sort.startswith("-"):
            reverse = True
            cur_sort = self._cur_sort[1:]
        elif self._cur_sort:
            reverse = False
            cur_sort = self._cur_sort
        else:
            reverse = False
            cur_sort = self._default_sort

        for lane, sample in samples:
            sample_info = self._project_org.form_value_dict(sample.values)
            try:
                seq_type = self._project_org.sample_summary(sample)
            except ValueError:
                seq_type = ""
            services = sample.desc.split(",")
            latest_sqn = self._service_org.get_latest_sqn_run(sample)
            barcode = self._service_org.get_barcode(sample)
            arrived_event = self._service_org.get_sample_arrived_event(sample)
            user = ""
            state = ""
            utime = ""
            atime = ""
            cur_sqn = ""
            if sample.request.user:
                user = sample.request.user.username
            if sample.state:
                state = sample.state.name
            if len(sample.events) > 0:
                utime = sample.events[0].update_time.strftime("%b %d, %Y")
            if arrived_event:
                atime = arrived_event.update_time.strftime("%b %d, %Y")
            if latest_sqn:
                cur_sqn = latest_sqn["run_folder"]
            if barcode.get("barcodes", ""):
                barcode_str = self._text_barcode_summary(barcode["barcodes"])
            else:
                barcode_str = "%s %s" % (barcode.get("barcode_type", ""),
                                         barcode.get("barcode_id", ""))
            rows.append(_GridRowSample(sample.id, sample_info['name'],
                sample_info['description'], user, state,
                seq_type, ", ".join(services), utime, atime, cur_sqn,
                lane + 1, # 1-based display
                barcode=barcode_str,
                num_lanes=1,
                sort_attr=cur_sort
                ))
        # finally, actually sort our items based on the passed in sort key
        if cur_sort:
            rows.sort(reverse=reverse)
        return rows

class _GridRowSample:
    def __init__(self, id, name, description, researcher, state, seq_type,
            services, update_time, received, sqn_run, lane, barcode,
            num_lanes=1, sort_attr=None):
        self.id = id
        self.name = name
        self.description = description
        self.researcher = researcher
        self.state = state
        self.seq_type = seq_type
        self.services = services
        self.update_time = update_time
        self.received = received
        self.sqn_run = sqn_run
        self.lane = lane
        self.barcode = barcode
        self.num_lanes = num_lanes
        self.edit_barcodes = "Edit barcodes"
        self.edit = "Edit"
        if sort_attr == 'None':
            sort_attr = None
        self._sort_attr = sort_attr or 'update_time'

    def __cmp__(self, other):
        if isinstance(other, _GridRowSample):
            # handle time based sorting
            if self._sort_attr == "update_time":
                try:
                    cmp_one = datetime.strptime(self.update_time, "%b %d, %Y")
                except ValueError:
                    cmp_one = datetime(1900, 1, 1)
                try:
                    cmp_two = datetime.strptime(other.update_time, "%b %d, %Y")
                except ValueError:
                    cmp_two = datetime(1900, 1, 1)
            else:
                cmp_one = getattr(self, self._sort_attr)
                cmp_two = getattr(other, self._sort_attr)
        else:
            cmp_one = self.id
            cmp_two = other
        return cmp(cmp_one, cmp_two)

class _PagingMixin:
    def _paging(self, query, kwd):
        page_num = kwd.get('page', '1')
        if page_num != 'all':
            total_count = query.count()
            query = query.limit(self.num_rows_per_page).offset((int(page_num) - 1) *
                    self.num_rows_per_page)
        else:
            total_count = None
        return query, total_count

class _SqnRunGrid(grids.Grid, _RequestMixin, _FormMixin, _PagingMixin):
    """Display a high level grid with various sequencing runs performed.
    """
    title = "Sequencing runs"
    model_class = model.Request
    num_rows_per_page = 25
    use_paging = True
    columns = [
        grids.GridColumn("Run folder", key="run_folder"),
        grids.GridColumn("Samples", key='samples',
                link = (lambda item: dict(operation="show_sqnrun_samples",
                    id=item.id))),
        grids.GridColumn("Date", key="date"),
        grids.GridColumn("ID", key="id", visible=False),
        grids.GridColumn("", key="results",
            link = (lambda item: dict(action="list_sqn_results",
                search=item.run_folder))),
        grids.GridColumn("", key="edit",
                link = (lambda item: dict(operation="edit_sqnrun",
                    id=item.id))),
        grids.GridColumn("", key="save",
                link = (lambda item: dict(operation="download_sqnrun",
                    id=item.id))),
    ]
    def __init__(self, service_org):
        grids.Grid.__init__(self)
        for column in self.columns:
            column.sortable=False
        self._service_org = service_org
    
    def apply_query_filter(self, trans, query, **kwd):
        rows = []
        total_count = None
        user_roles = [r.name for r in trans.user.all_roles()]
        if 'sequencing' in user_roles:
            request_type_name = "%s %s" % (self._service_org.next_gen_name(),
                    self._service_org.output_name())
            try:
                request_type = self._get_request_type(trans, request_type_name)
            except ValueError:
                request_type = None
            if request_type:
                requests = trans.sa_session.query(trans.app.model.Request
                        ).filter_by(type=request_type
                        ).order_by("create_time DESC")
                requests, total_count = self._paging(requests, kwd)
            else:
                requests = []
            for request in requests:
                request_vals = self.form_value_dict(request.values)
                samples = sum(1 for s in request.samples_by_map())
                rows.append(_GridRowSqnRun(request.id, samples,
                    request_vals['run_folder'],
                    request.update_time.strftime("%b %d, %Y")))
        return _QueryLikeList(rows, total=total_count)

class _GridRowSqnRun:
    def __init__(self, rid, samples, run_folder, date):
        self.id = rid
        self.samples = samples
        self.run_folder = run_folder
        self.date = date
        self.results = "Results"
        self.edit = "Edit"
        self.save = "Save"

class _ProjectGrid(grids.Grid, _PagingMixin, _FormMixin):
    """Display a grid of project information.
    """
    title = "Sequencing projects"
    model_class = model.Request
    num_rows_per_page = 25
    use_paging = True
    def __init__(self, project_org):
        self.columns = [
            grids.GridColumn("Project", key="project"),
            grids.GridColumn("Researcher", key="researcher"),
            grids.GridColumn("Samples", key='samples',
                    link = (lambda item: dict(operation="show_project_samples",
                        id=item.id))),
            grids.GridColumn("Sequencing", key="seq_type"),
            grids.GridColumn("Sample States", key="request_type"),
            grids.GridColumn("Payment", key="payment"),
            grids.GridColumn("Last update", key="update_time"),
            grids.GridColumn("ID", key="id", visible=False),
            grids.MulticolFilterColumn("Search", [], key="free-text-search",
                    visible=False, filterable="standard"),
        ]
        grids.Grid.__init__(self)
        self._project_org = project_org
        # No sorting implemented right now
        for column in self.columns:
            column.sortable=False

    def apply_query_filter(self, trans, query, **kwd):
        if kwd.has_key("_allow_edit"):
            self.columns.append(grids.GridColumn("", key="edit",
                    link = (lambda item: dict(display="edit_request",
                                              id=item.id, edit="true"))))
            self.columns[-1].sortable = False
        user_roles = [r.name for r in trans.user.all_roles()]
        restrict_to_user = 'sequencing' not in user_roles
        rows = []
        query = self._project_org.get_projects(trans,
                restrict_to_user=restrict_to_user)
        query = query.order_by("request.create_time DESC")
        query, total_count = self._paging(query, kwd)
        for project in query:
            project_info = self._project_org.form_value_dict(project.values)
            num_samples = 0
            updates = []
            sample_states = []
            seq_types = collections.defaultdict(int)
            for sample in project.samples_by_map():
                num_samples += 1
                seq_type = self._project_org.sample_summary(sample)
                seq_types[seq_type] += 1
                sample_states.append(sample.state.name)
                updates.append(sample.events[0].update_time)
            updates.sort(reverse=True)
            if len(updates) > 0:
                last_update = updates[0].strftime("%b %d, %Y")
            else:
                last_update = ""
            sample_states = sorted(list(set(sample_states)))
            seq_types = sorted(seq_types.keys())
            rows.append(_GridRowProject(project.id,
                    project_info.get("project_name", ""),
                    project.user.username, num_samples,
                    ", ".join(sample_states), ", ".join(seq_types),
                    self._get_payment(project_info),
                    last_update))
        rows.sort(reverse=True)
        return _QueryLikeList(rows, total=total_count)

class _QueryLikeList(list):
    def __init__(self, *args, **kwargs):
        if kwargs.has_key('total'):
            self._total = kwargs['total']
            del kwargs['total']
        else:
            self._total = None
        list.__init__(self, *args, **kwargs)

    def count(self):
        if self._total is not None:
            return self._total
        else:
            return len(self)

    def order_by(self, *args, **kwargs):
        """No ordering here; we handle it separately.
        """
        return self

    def limit(self, *args, **kwargs):
        """Need to handle in apply_query_filter.
        """
        return self

    def offset(self, *args, **kwargs):
        """Need to handle in apply_query_filter.
        """
        return self

class _GridRowProject:
    def __init__(self, id, project, researcher, samples, request_type,
            seq_type, payment, update_time):
        self.id = id
        self.project = project
        self.researcher = researcher
        self.samples = samples
        self.request_type = request_type
        self.seq_type = seq_type
        self.payment = payment
        self.update_time = update_time
        self.edit = "Edit"

    def __cmp__(self, other):
        if isinstance(other, self.__class__):
            return cmp(datetime.strptime(self.update_time, "%b %d, %Y"),
                       datetime.strptime(other.update_time, "%b %d, %Y"))
        else:
            return cmp(self.id, other)

class _ResultsGrid(grids.Grid, _PagingMixin):
    """Display a grid of sequencing results stats.
    """
    title = "Sequencing results"
    model_class = model.SqnRunResults
    model_class.web_display_name = "results"
    num_rows_per_page = 25
    use_paging = True
    def __init__(self, project_org, web_ready=True):
        self.columns = [
            grids.GridColumn("Run", key="run"),
            grids.GridColumn("Lane", key="lane"),
            grids.GridColumn("Researcher", key="researcher"),
            grids.GridColumn("Name", key="name"),
            grids.GridColumn("Description", key="description"),
            grids.GridColumn("Genome", key="genome_build"),
            grids.GridColumn("Length", key="read_length"),
            grids.GridColumn("Clusters", key="clusters"),
            grids.GridColumn("Passing clusters (reads)", key="reads"),
            grids.GridColumn("ID", key="id", visible=False),
            grids.MulticolFilterColumn("Search", [], key="results-search",
                    visible=False, filterable="standard"),
        ]
        self.operations = [grids.GridOperation("Download",
                allow_multiple=False, allow_popup=False,
                global_operation=(lambda: dict(operation="download")))]
        grids.Grid.__init__(self)
        self._project_org = project_org
        self.web_ready = web_ready
        # No sorting implemented right now
        for column in self.columns:
            column.sortable=False

    def apply_query_filter(self, trans, query, **kwd):
        model = trans.app.model
        user_roles = [r.name for r in trans.user.all_roles()]
        query = trans.sa_session.query(model.SqnRunResults)
        if 'sequencing' not in user_roles:
            query = query.filter_by(user=trans.user)
        query = query.order_by(
              ["sqn_run_results.request_id DESC", "lane ASC", "sample_id DESC"])
        search_term = kwd.get("search", None)
        if search_term:
            search_term = '%' + search_term.lower() + '%'
            query = query.outerjoin(model.SqnRunResults.user).join(
                    model.SqnRunResults.request).join(
                    model.SqnRunResults.sample)
            query = query.filter(or_(
                func.lower(model.Sample.name).like(search_term),
                func.lower(model.User.username).like(search_term),
                func.lower(model.Request.name).like(search_term),
                ))
            # on searches, show all results
            kwd['page'] = 'all'
        query, total_count = self._paging(query, kwd)
        rows = []
        for result in query:
            request_vals = self._project_org.form_value_dict(
                    result.request.values)
            sample_vals = self._project_org.form_value_dict(
                    result.sample.values)
            vals = self._project_org.form_value_dict(result.form_values)
            user = ""
            if result.user:
                user = result.user.username
            if vals.get("reads", ""):
                reads = vals["reads"]
            else:
                reads = vals["clusters_passed"]
            rows.append(_GridRowResults(result.request.id,
                request_vals["run_folder"], result.lane, user,
                sample_vals["name"], sample_vals["description"],
                sample_vals["genome_build"],
                vals["read_length"],
                self._num_finalize(vals["clusters"], None),
                self._num_finalize(reads, vals["clusters"])))
        return _QueryLikeList(rows, total=total_count)

    def _num_finalize(self, base, comparison):
        if not self.web_ready:
            return str(base)
        def _add_commas(s, sep=','):
            """Add commas to output counts.

            From: http://code.activestate.com/recipes/498181
            """
            if len(s) <= 3: return s
            return _add_commas(s[:-3], sep) + sep + s[-3:]
        comma_base = _add_commas(str(base))
        if comparison and int(comparison) >= int(base):
            percent = " (%.1f%%)" % (float(base) * 100.0 / float(comparison))
        else:
            percent = ""
        return comma_base + percent

class _GridRowResults:
    """Hold sequencing results for a sequencing run and lane.
    """
    def __init__(self, rid, run, lane, researcher, name, description,
            genome_build, read_length, clusters, reads):
        self.id = (rid, lane)
        self.run = run
        self.lane = lane
        self.researcher = researcher
        self.name = name
        self.description = description
        self.genome_build = genome_build
        self.read_length = read_length
        self.clusters = clusters
        self.reads = reads

class _ProjectOrganizer(_FormMixin, _RequestMixin):
    """Organize high level details associated with a sequencing project.

    This is a way to organize a set of samples into a single project with
    associated metadata. The naming of high level projects is also standardized
    in this class, and can be adjusted here.
    """
    def __init__(self, config, service_org, testing=False):
        self.name = None
        for request in config["requests"]:
            if request.get("top_level", False):
                self.name = request["name"]
                break
        assert self.name is not None, "Top level project config not specified"
        self._service_org = service_org
        self._testing = testing

    def get_sample_project(self, sample):
        """Retrieve a project containing the given sample.
        """
        for parent in sample.parent_requests_by_map():
            if parent.type.name == self.name:
                return parent
        return None

    def _current_request_type(self, trans):
        rt = self._get_request_type(trans, self.name)
        form = rt.request_form
        if form.id != form.current.latest_form.id:
            rt.request_form = form.current.latest_form
        return rt

    def get_project_form(self, trans):
        """Retrieve the form information associated with a project.
        """
        rt = self._current_request_type(trans)
        if rt:
            return rt.request_form
        else:
            raise ValueError("Need to define a project inputs form")

    def get_projects(self, trans, restrict_to_user=False,
            active_only=True):
        rtype = trans.sa_session.query(trans.app.model.RequestType).filter_by(
                name=self.name).first()
        requests = trans.sa_session.query(trans.app.model.Request).filter_by(
                type=rtype)
        if active_only:
            requests = self._filter_request_by_state(trans, requests,
                    trans.app.model.Request.states.SUBMITTED)
        if restrict_to_user:
            requests = requests.filter(
                    trans.app.model.Request.user == trans.user)
        return requests

    def save_project(self, trans, params):
        """Save a project request and associated samples.
        """
        request_type = self._current_request_type(trans)
        form_values = self._get_form_values(trans, request_type.request_form,
                params)
        cur_request = self._new_request(trans, request_type, form_values,
                params, trans.app.model.Request.states.SUBMITTED)
        # now find all of the samples and associate them with this request
        sample_ids= params.get('samples', [])
        if not isinstance(sample_ids, list):
            sample_ids = [sample_ids]
        assert len(sample_ids) > 0
        trans.sa_session.add(cur_request)
        if not self._testing:
            trans.sa_session.flush()
            for i, sid in enumerate(sample_ids):
                sample = trans.sa_session.query(trans.app.model.Sample).get(sid)
                assert sample is not None, (sid, sample_ids)
                self._service_org.move_to_starting_state(trans, sample)
                sample.request = cur_request
                request_map = trans.app.model.SampleRequestMap(sample,
                        cur_request, i, False)
            trans.sa_session.flush()

    def sample_summary(self, sample):
        """Return high level summary information for a sequencing sample.
        """
        seq_type = None
        for request in sample.requests_by_map():
            if request.type.name == "%s %s" % (
                    self._service_org.next_gen_name(),
                    self._service_org.input_name()):
                request_info = self.form_value_dict(request.values)
                seq_type = "%s %s" % (request_info['cycles'],
                        request_info['method'].split()[0])
                break
        if seq_type is None:
            raise ValueError("No sequencing info found for %s" %
                    self.form_value_dict(sample.values))
        return seq_type

class _ServiceOrganizer(_FormMixin):
    """Organize services involved in a LIMS, transparently handling in/outputs.

    Services have both inputs and outputs. For a set of chained services, we
    will need the inputs of the first and any inputs of subsequent services. If
    services are cherry-picked, we will need output information from previous
    services. This helps organize this and reveal only high level services.
    """
    def __init__(self, config, testing=False):
        self._service_order = None
        self._service_types = None
        self._testing=testing

        self._setup_states(config)
        self._setup_requests(config)
        self._setup_defaults(config)

        #self._state_order = ["On hold", "Awaiting sample", "Construction",
        #                     "Validation", "Pre-sequencing quantitation",
        #                     "Sequencing", "Sequencing confirmation",
        #                     "Complete", "Cancelled"]
        ## we begin at the "Awaiting sample"
        #self._start_state_index = 1
        #self._next_gen_name = "Next gen sequencing"
        #self._services = ["Library construction", "Library validation",
        #                       "Quantitation", self._next_gen_name,
        #                       "Sequencing confirmation"]
        #self._state_map = {
        #  "Construction" : "Library construction",
        #  "Validation" : "Library validation",
        #  "Pre-sequencing quantitation" : "Quantitation",
        #  "Sequencing" : self._next_gen_name,
        #  }
        # quantitation and controls are part of sequencing, but not exposed
        #self._not_exposed = ["Quantitation details", "Control",
        #                     "Sequencing confirmation details"]
        #self._ignore_names = [o.name for o in other_orgs] + self._not_exposed

    def _setup_states(self, config):
        """Read state information from the input configuration file.
        """
        self._state_order = []
        self._start_state = None
        self._state_operations = dict()
        for state in config["samples"]["states"]:
            if state.get("display", True):
                self._state_order.append(state["name"])
                if state.get("start", False):
                    self._start_state = state["name"]
                operations = state.get("operations", [])
                if not isinstance(operations, list):
                    operations = [operations]
                self._state_operations[state["name"]] = operations
        assert self._start_state is not None, \
                "No starting state specified in configuration file."

    def _setup_requests(self, config):
        """Read request information from input configuration file.
        """
        self._input_name = "inputs"
        self._output_name = "details"
        self._next_gen_name = None
        self._barcode_name = None
        self._exposed_services = []
        self._services = []
        self.default_services = []
        self._state_map = {}
        self._starting_states = []
        for request in config["requests"]:
            if not request.get("top_level", False):
                self._services.append(request["name"])
                if request.get("available", False):
                    self._exposed_services.append(request["name"])
                    self._starting_states.append((request["name"],
                        request["start_state"]))
                    if request.get("default", False):
                        self.default_services.append(request["name"])
                if request.get("state", "") == "Sequencing":
                    self._next_gen_name = request["name"]
                if (request.get("state", "") == "Multiplex" and
                    request["name"].lower().find("construction") == -1):
                    self._barcode_name = request["name"]
                if request.get("state", ""):
                    self._state_map[request["state"]] = request["name"]
        self._confirmation_name = self._services[-1]
        assert self._next_gen_name is not None, \
                "Need to have a sequencing associated request"

    def _setup_defaults(self, config):
        """Establish default information from the configuration file.
        """
        # identify the form value mapping to database keys
        self.dbkey_label = None
        for form_info in config["samples"]["form"]:
            if form_info.get("synonym", "") == "dbkey":
                self.dbkey_label = form_info["label"]
        assert self.dbkey_label is not None, \
                "Must setup a reference to a dbkey in sample form config"

    def pre_received_states(self):
        index = self._state_order.index(self._start_state)
        return self._state_order[:index + 1]

    def next_gen_name(self):
        return self._next_gen_name

    def input_name(self):
        return self._input_name

    def output_name(self):
        return self._output_name

    def get_states(self):
        return self._state_order

    def get_sample_sqn_runs(self, sample):
        """Retrieve sequencing runs associated with the given sample.
        """
        sqn_runs = []
        for order, request in sample.parent_requests_by_map(include_order=True):
            if request.type.name.startswith(self.next_gen_name()):
                request_vals = self.form_value_dict(request.values)
                request_vals['lane'] = order + 1
                request_vals['date'] = request.update_time.strftime("%b %d, %Y")
                request_vals['id'] = request.id
                sqn_runs.append(request_vals)
        return sqn_runs

    def get_sqn_run_results(self, sample, run_folder):
        """Retrieve the results information about a sequencing run.
        """
        for request in sample.requests_by_map():
            if request.type.name.startswith(self._confirmation_name):
                values = self.form_value_dict(request.values)
                if values["sequencing_result"].lower().find("pass") >= 0:
                    return values["results_notes"]
        return None

    def get_latest_sqn_run(self, sample):
        runs = self.get_sample_sqn_runs(sample)
        if len(runs) == 0:
            return None
        to_sort = [(r["id"], r) for r in runs]
        to_sort.sort(reverse=True)
        return to_sort[0][1]

    def get_barcode(self, sample):
        """Retrieve the barcode information associated with a sample.
        """
        for request in sample.requests_by_map():
            if request.type.name.startswith(self._barcode_name):
                vals = self.form_value_dict(request.values)
                vals["date"] = request.values.update_time
                return vals
        return dict()

    def get_sample_arrived_event(self, sample):
        """Retrieve the event when a sample physically arrived for processing.
        """
        prev_event = None
        found = False
        for event in sample.events:
            if self._start_state == event.state.name:
                found = True
                break
            else:
                prev_event = event
        if found and prev_event:
            return prev_event
        else:
            return None

    def sequencing_run_by_search(self, trans, name):
        """Retrieve a sequencing run based on the name ID associated with it.
        """
        form_def = trans.sa_session.query(trans.app.model.FormDefinition
                ).filter(trans.app.model.FormDefinition.name.like(
                "%s %s" % (self.next_gen_name(), self.output_name()))).first()
        term = "%" + name.lower() + "%"
        # SQLite has good handling of Blobs
        if trans.app.model.engine.name in ["sqlite"]:
            search_phrase = func.lower(model.FormValues.content).like(term)
        elif trans.app.model.engine.name in ["postgres"]:
            # Use escape since not all postgres have UTF8. Won't internationalize
            # but should work for our needs
            search_phrase = "lower(encode(form_values.content, 'escape')) LIKE '%s'" % (term)
        # others (MySQL tested) require conversion
        else:
            search_phrase = "LOWER(CONVERT(form_values.content USING utf8)) LIKE '%s'" % (term)
        form_val = trans.sa_session.query(trans.app.model.FormValues
            ).filter_by(form_definition=form_def).filter(search_phrase).order_by(
                    "id DESC")
        form_val = form_val.first()
        if form_val:
            request = trans.sa_session.query(trans.app.model.Request
                    ).filter_by(values=form_val).first()
            if request:
                return request
        return None

    def operations_by_state(self, state):
        """Return grid operations available depending on the queue being viewed.
        """
        operations = []
        for op in self._state_operations.get(state, []):
            operations.append(grids.GridOperation(op))
        return operations
        #if state in ["On hold", "Cancelled"]:
        #    operations.append(grids.GridOperation("Reactivate"))
        #if state in ["Awaiting sample"]:
        #    operations.append(grids.GridOperation("Samples arrived"))
        #if state in ["Construction"]:
        #    operations.append(grids.GridOperation("Add construction details"))
        #if state in ["Validation"]:
        #    operations.append(grids.GridOperation("Add validation"))
        #if state in ["Pre-sequencing quantitation"]:
        #    operations.append(grids.GridOperation("Add quantitation"))
        #if state in ["Sequencing"]:
        #    operations.append(grids.GridOperation("Prepare flow cell",
        #        allow_popup=False))
        #if state in ["Sequencing confirmation"]:
        #    operations.append(grids.GridOperation("Redo sequencing"))
        #    operations.append(grids.GridOperation("Completed"))

    def move_sample_to_state(self, trans, sample, state_name):
        new_state = trans.sa_session.query(trans.app.model.SampleState
                ).filter_by(name=state_name).first()
        event = trans.app.model.SampleEvent(sample, new_state)
        trans.sa_session.add(event)
        if not self._testing:
            trans.sa_session.flush()
        return new_state.name

    def order_services(self, service_names):
        """Organize a list of service names based on a configured order.
        """
        sort_names = [(self._services.index(n), n) for n in service_names]
        sort_names.sort()
        return [n for (_, n) in sort_names]

    def move_to_starting_state(self, trans, sample):
        # first state is a holding state, second is where everything begins
        return self.move_sample_to_state(trans, sample, self._start_state)

    def move_to_next_state(self, trans, sample):
        """Move samples to the next state in the linear flow of processes.

        This hardcodes the logic for moving from step to step in a single
        function.
        """
        cur_state = sample.state.name
        # Get the state a sample should start in, based on desired services.
        if cur_state == self._start_state:
            services = sample.desc.split(",")
            for service_name, state in self._starting_states:
                if service_name in services:
                    return self.move_sample_to_state(trans, sample, state)
            raise ValueError("Did not find initial state for services: %s" %
                    services)
        else:
            try:
                cur_pos = self._state_order.index(cur_state)
                next_state = self._state_order[cur_pos + 1]
            except (ValueError, IndexError):
                raise ValueError("Unexpected state for transition: %s" % cur_state)
            return self.move_sample_to_state(trans, sample, next_state)

    def get_detail_widgets(self, trans, state):
        request_name = "%s %s" % (self._state_map.get(state, state),
                self._output_name)
        request_type = trans.sa_session.query(trans.app.model.RequestType
                ).filter_by(name=request_name).first()
        if request_type is None:
            raise ValueError("Did not find widgets for state %s" % state)
        widgets = request_type.request_form.get_widgets(trans.user)
        return widgets, request_type

    def _get_service_details(self, trans):
        if self._service_order is None:
            display_types = dict()
            dt_names = []
            for rt in trans.sa_session.query(trans.app.model.RequestType
                    ).order_by("id").all():
                if not rt.deleted:
                    exposed = [n for n in self._exposed_services if
                            rt.name.startswith(n)]
                    if len(exposed) > 0:
                        name = " ".join(rt.name.split()[:-1])
                        try:
                            display_types[name].append(rt.id)
                        except KeyError:
                            dt_names.append(name)
                            display_types[name] = [rt.id]
            self._service_order = self.order_services(dt_names)
            self._service_types = display_types
        return self._service_order, self._service_types

    def _get_organized_requests(self, trans, request_ids):
        """Given a set of requests, return request names and associated IDs.
        """
        dt_names, display_types = self._get_service_details(trans)
        need_ids = collections.defaultdict(list)
        for dt_name in dt_names:
            dt_ids = display_types[dt_name]
            if len(dt_ids) == 2:
                input_id, output_id = dt_ids
            elif len(dt_ids) == 1:
                # Crappy way to decide if it's an input or output. Based on the
                # name of the request type.
                request_type = trans.sa_session.query(
                        trans.app.model.RequestType).get(dt_ids[0])
                name_parts = request_type.name.split()
                if name_parts[-1] == self.input_name():
                    input_id = dt_ids[0]
                    output_id = None
                else:
                    input_id = None
                    output_id = dt_ids[0]
            else:
                raise ValueError("Unexpected types associated with name: %s" %
                        (dt_name, dt_ids))
            # Always need inputs for the processes
            if input_id is not None:
                need_ids[dt_name].append(input_id)
            # If we did not do this one, we need to collect the outputs.
            if output_id is not None and output_id not in request_ids:
                need_ids[dt_name].append(output_id)
        return dt_names, need_ids

    def get_sample_form(self, trans):
        """Retrieve the form with details about sample information.

        This assumes that all requests have the same sample form definition,
        which is how we are implemented.
        """
        dt_names, display_types = self._get_service_details(trans)
        # we have not yet loaded any sample forms
        if len(display_types) == 0:
            return None
        one_id = display_types.values()[0][0]
        request = trans.sa_session.query(trans.app.model.RequestType
                ).get(one_id)
        return request.sample_form

    def get_request_types(self, trans, request_ids):
        """Retrieve an ordered set of request types for the given request IDs.
        """
        dt_names, need_ids = self._get_organized_requests(trans, request_ids)
        requests = []
        for dt_name in dt_names:
            for cur_id in need_ids[dt_name]:
                request_type = trans.sa_session.query(
                        trans.app.model.RequestType).get(cur_id)
                requests.append(request_type)
        return requests

    def selected_widgets(self, trans, request_ids):
        """Return widgets for a set of selected request IDs.
        """
        dt_names, need_ids = self._get_organized_requests(trans, request_ids)
        widgets = []
        # present the last (sequencing) items first
        for dt_name in reversed(dt_names):
            cur_ids = need_ids[dt_name]
            if len(cur_ids) > 0:
                widgets.append(dict(label="", helptext="", widget=
                    _SectionLabel(dt_name)))
                for cur_id in cur_ids:
                    request_type = trans.sa_session.query(
                            trans.app.model.RequestType).get(cur_id)
                    widgets.extend(request_type.request_form.get_widgets(
                        trans.user))
        return widgets

    def type_ids_to_display_name(self, trans, type_ids):
        """Given a set of type IDs, return the associated request display name.
        """
        dt_names, display_types = self._get_service_details(trans)
        names = []
        for dt_name in dt_names:
            for cur_id in display_types[dt_name]:
                if cur_id in type_ids:
                    names.append(dt_name)
                    break
        return names

    def display_name_to_type_ids(self, trans, display_names):
        """Given display names, reconsitute the typeIDs they point to.

        This is useful for reconstructing a form parameter from a saved sample
        in the database.
        """
        dt_names, display_types = self._get_service_details(trans)
        type_ids = []
        for dt_name in dt_names:
            if dt_name in display_names:
                type_ids.append(",".join([str(i) for i in
                    display_types[dt_name]]))
        return type_ids

    def multiselect_request_type(self, trans, pre_checked=None):
        """Retrieve a widget ready select box for picking multiple requests.
        """
        if pre_checked is None:
            pre_checked = []
        dt_names, display_types = self._get_service_details(trans)
        options = []
        checked_vals = []
        for dt_name in dt_names:
            dt_id_str = ",".join([str(i) for i in display_types[dt_name]])
            options.append(dict(name=dt_name, value=dt_id_str,
                options=[]))
            if dt_name in pre_checked:
                checked_vals.append(dt_id_str)
        service_w = DrillDownField("services_check", multiple=True,
                display="checkbox", options=options, value=checked_vals)
        tooltip = "Sequencing services needed for this sample. You'll be asked "\
                "to specify additional sample details based on the services "\
                "selected."
        return dict(label="Services needed", widget=service_w,
            helptext="(Required)", title=tooltip)

class _SectionLabel:
    """Provide a simple HTML label for widget-based form display.
    """
    def __init__(self, text):
        self.text = text

    def get_html(self):
        return "<h3 class='section_label'>%s</h3>" % self.text
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.