Source

django-lfs / lfs / catalog / models.py

Full commit
   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
# Python imports
import locale
import math
import uuid

# django imports
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

# lfs imports
import lfs.catalog.utils
from lfs.core.fields.thumbs import ImageWithThumbsField
from lfs.core.managers import ActiveManager
from lfs.catalog.settings import CHOICES, CONTENT_CATEGORIES
from lfs.catalog.settings import CHOICES_STANDARD
from lfs.catalog.settings import CHOICES_YES
from lfs.catalog.settings import PRODUCT_TYPE_CHOICES
from lfs.catalog.settings import CONFIGURABLE_PRODUCT
from lfs.catalog.settings import STANDARD_PRODUCT
from lfs.catalog.settings import VARIANT
from lfs.catalog.settings import PRODUCT_WITH_VARIANTS
from lfs.catalog.settings import CAT_CATEGORY_PATH
from lfs.catalog.settings import CATEGORY_TEMPLATES
from lfs.catalog.settings import CONTENT_PRODUCTS
from lfs.catalog.settings import LIST
from lfs.catalog.settings import DELIVERY_TIME_UNIT_CHOICES
from lfs.catalog.settings import DELIVERY_TIME_UNIT_SINGULAR
from lfs.catalog.settings import DELIVERY_TIME_UNIT_HOURS
from lfs.catalog.settings import DELIVERY_TIME_UNIT_DAYS
from lfs.catalog.settings import DELIVERY_TIME_UNIT_WEEKS
from lfs.catalog.settings import DELIVERY_TIME_UNIT_MONTHS
from lfs.catalog.settings import PROPERTY_FIELD_CHOICES
from lfs.catalog.settings import PROPERTY_NUMBER_FIELD
from lfs.catalog.settings import PROPERTY_SELECT_FIELD
from lfs.catalog.settings import PROPERTY_TEXT_FIELD
from lfs.catalog.settings import PROPERTY_STEP_TYPE_CHOICES
from lfs.catalog.settings import PROPERTY_STEP_TYPE_AUTOMATIC
from lfs.catalog.settings import PROPERTY_STEP_TYPE_MANUAL_STEPS
from lfs.catalog.settings import PROPERTY_STEP_TYPE_FIXED_STEP
from lfs.catalog.settings import PROPERTY_VALUE_TYPE_DEFAULT
from lfs.catalog.settings import PROPERTY_VALUE_TYPE_DISPLAY
from lfs.catalog.settings import PROPERTY_VALUE_TYPE_VARIANT
from lfs.catalog.settings import PRODUCT_TEMPLATES
from lfs.catalog.settings import QUANTITY_FIELD_TYPES
from lfs.catalog.settings import QUANTITY_FIELD_INTEGER
from lfs.catalog.settings import QUANTITY_FIELD_DECIMAL_1
from lfs.catalog.settings import THUMBNAIL_SIZES
from lfs.catalog.settings import VARIANTS_DISPLAY_TYPE_CHOICES
from lfs.catalog.settings import CATEGORY_VARIANT_CHEAPEST_PRICE
from lfs.catalog.settings import CATEGORY_VARIANT_CHEAPEST_BASE_PRICE
from lfs.catalog.settings import CATEGORY_VARIANT_CHEAPEST_PRICES
from lfs.catalog.settings import CATEGORY_VARIANT_DEFAULT

from lfs.tax.models import Tax
from lfs.supplier.models import Supplier
from lfs.manufacturer.models import Manufacturer


def get_unique_id_str():
    return str(uuid.uuid4())

LFS_UNITS = []
for u in settings.LFS_UNITS:
    LFS_UNITS.append([u, u])

LFS_PRICE_UNITS = []
for u in settings.LFS_PRICE_UNITS:
    LFS_PRICE_UNITS.append([u, u])

LFS_BASE_PRICE_UNITS = []
for u in settings.LFS_BASE_PRICE_UNITS:
    LFS_BASE_PRICE_UNITS.append([u, u])

LFS_PACKING_UNITS = []
for u in settings.LFS_PACKING_UNITS:
    LFS_PACKING_UNITS.append([u, u])


class Category(models.Model):
    """A category is used to browse through the shop products. A category can
    have one parent category and several child categories.

    **Attributes:**

    name
        The name of the category.

    slug
        Part of the URL

    parent
        Parent of the category. This is used to create a category tree. If
        it's None the category is a top level category.

    show_all_products
       If True the category displays it's direct products as well as products
       of it's sub categories. If False only direct products will be
       displayed.

    products
        The assigned products of the category.

    short_description
        A short description of the category. This is used in overviews.

    description
        The description of the category. This can be used in details views
        of the category.

    image
        The image of the category.

    position
        The position of the category within the shop resp. the parent
        category.

    static_block
        A assigned static block to the category.

    content
        decides which content will be displayed. At the moment this is either
        sub categories or products.

    active_formats
        If True product_rows, product_cols and category_cols are taken from
        the category otherwise from the parent.

    product_rows, product_cols, category_cols
        Format information for the category views

    meta_title
        Meta title of the category (HTML title)

    meta_keywords
        Meta keywords of the category

    meta_description
       Meta description of the category

    uid
       The unique id of the category

    level
       The level of the category within the category hierachie, e.g. if it
       is a top level category the level is 1.

    template
       Sets the template which renders the category view. If left to None, default template is used.
    """
    name = models.CharField(_(u"Name"), max_length=50)
    slug = models.SlugField(_(u"Slug"), unique=True)
    parent = models.ForeignKey("self", verbose_name=_(u"Parent"), blank=True, null=True)

    # If selected it shows products of the sub categories within the product
    # view. If not it shows only direct products of the category.
    show_all_products = models.BooleanField(_(u"Show all products"), default=True)

    products = models.ManyToManyField("Product", verbose_name=_(u"Products"), blank=True, related_name="categories")
    short_description = models.TextField(_(u"Short description"), blank=True)
    description = models.TextField(_(u"Description"), blank=True)
    image = ImageWithThumbsField(_(u"Image"), upload_to="images", blank=True, null=True, sizes=((60, 60), (100, 100), (200, 200), (400, 400)))
    position = models.IntegerField(_(u"Position"), default=1000)
    exclude_from_navigation = models.BooleanField(_(u"Exclude from navigation"), default=False)

    static_block = models.ForeignKey("StaticBlock", verbose_name=_(u"Static block"), blank=True, null=True, related_name="categories")
    template = models.PositiveSmallIntegerField(_(u"Category template"), max_length=400, blank=True, null=True, choices=CATEGORY_TEMPLATES)
    active_formats = models.BooleanField(_(u"Active formats"), default=False)

    product_rows = models.IntegerField(_(u"Product rows"), default=3)
    product_cols = models.IntegerField(_(u"Product cols"), default=3)
    category_cols = models.IntegerField(_(u"Category cols"), default=3)

    meta_title = models.CharField(_(u"Meta title"), max_length=100, default="<name>")
    meta_keywords = models.TextField(_(u"Meta keywords"), blank=True)
    meta_description = models.TextField(_(u"Meta description"), blank=True)

    level = models.PositiveSmallIntegerField(default=1)
    uid = models.CharField(max_length=50, editable=False, unique=True, default=get_unique_id_str)

    class Meta:
        ordering = ("position", )
        verbose_name_plural = 'Categories'

    def __unicode__(self):
        return "%s (%s)" % (self.name, self.slug)

    def get_absolute_url(self):
        """
        Returns the absolute_url.
        """
        return ("lfs.catalog.views.category_view", (), {"slug": self.slug})
    get_absolute_url = models.permalink(get_absolute_url)

    @property
    def content_type(self):
        """
        Returns the content type of the category as lower string.
        """
        return u"category"

    def get_all_children(self):
        """
        Returns all child categories of the category.
        """
        def _get_all_children(category, children):
            for category in Category.objects.filter(parent=category.id):
                children.append(category)
                _get_all_children(category, children)

        cache_key = "%s-category-all-children-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)
        children = cache.get(cache_key)
        if children is not None:
            return children

        children = []
        for category in Category.objects.filter(parent=self.id):
            children.append(category)
            _get_all_children(category, children)

        cache.set(cache_key, children)
        return children

    def get_children(self):
        """
        Returns the first level child categories.
        """
        cache_key = "%s-category-children-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)

        categories = cache.get(cache_key)
        if categories is not None:
            return categories

        categories = Category.objects.filter(parent=self.id)
        cache.set(cache_key, categories)

        return categories

    def get_format_info(self):
        """
        Returns format information.
        """
        if self.active_formats == True:
            return {
                "product_cols": self.product_cols,
                "product_rows": self.product_rows,
                "category_cols": self.category_cols,
            }
        else:
            if self.parent is None:
                try:
                    # TODO: Use cache here. Maybe we need a lfs_get_object,
                    # which raise a ObjectDoesNotExist if the object does not
                    # exist
                    from lfs.core.models import Shop
                    shop = Shop.objects.get(pk=1)
                except ObjectDoesNotExist:
                    return {
                        "product_cols": 3,
                        "product_rows": 3,
                        "category_cols": 3,
                    }
                else:
                    return {
                        "product_cols": shop.product_cols,
                        "product_rows": shop.product_rows,
                        "category_cols": shop.category_cols,
                    }
            else:
                return self.parent.get_format_info()

    def get_meta_title(self):
        """
        Returns the meta keywords of the catgory.
        """
        mt = self.meta_title.replace("<name>", self.name)
        return mt

    def get_meta_keywords(self):
        """
        Returns the meta keywords of the catgory.
        """
        mk = self.meta_keywords.replace("<name>", self.name)
        mk = mk.replace("<short-description>", self.short_description)
        return mk

    def get_meta_description(self):
        """
        Returns the meta description of the product.
        """
        md = self.meta_description.replace("<name>", self.name)
        md = md.replace("<short-description>", self.short_description)
        return md

    def get_image(self):
        """
        Returns the image of the category if it has none it inherits that from
        the parent category.
        """
        if self.image:
            return self.image
        else:
            if self.parent:
                return self.parent.get_image()

        return None

    def get_parents(self):
        """
        Returns all parent categories.
        """
        cache_key = "%s-category-parents-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)
        parents = cache.get(cache_key)
        if parents is not None:
            return parents

        parents = []
        category = self.parent
        while category is not None:
            parents.append(category)
            category = category.parent

        cache.set(cache_key, parents)
        return parents

    def get_products(self):
        """
        Returns the direct products of the category.
        """
        cache_key = "%s-category-products-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)
        products = cache.get(cache_key)
        if products is not None:
            return products

        products = self.products.filter(active=True).exclude(sub_type=VARIANT)
        cache.set(cache_key, products)

        return products

    def get_property_groups(self):
        """
        Returns property groups for given category.
        """
        cache_key = "%s-category-property-groups-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)
        pgs = cache.get(cache_key)
        if pgs is not None:
            return pgs
        products = self.get_products()
        pgs = lfs.catalog.models.PropertyGroup.objects.filter(products__in=products).distinct()
        cache.set(cache_key, pgs)

        return pgs

    def get_all_products(self):
        """
        Returns the direct products and all products of the sub categories
        """
        cache_key = "%s-category-all-products-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)
        products = cache.get(cache_key)
        if products is not None:
            return products

        categories = [self]
        categories.extend(self.get_all_children())

        products = lfs.catalog.models.Product.objects.distinct().filter(
            active=True,
            categories__in=categories).exclude(sub_type=VARIANT).distinct()

        cache.set(cache_key, products)
        return products

    def get_filtered_products(self, filters, price_filter, sorting):
        """
        Returns products for this category filtered by passed filters,
        price_filter and sorted by passed sorting.
        """
        return lfs.catalog.utils.get_filtered_products_for_category(
            self, filters, price_filter, sorting)

    def get_static_block(self):
        """
        Returns the static block of the category.
        """
        cache_key = "%s-static-block-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)
        blocks = cache.get(cache_key)
        if blocks is not None:
            return blocks

        block = self.static_block
        cache.set(cache_key, blocks)

        return block

    # 3rd party contracts
    def get_parent_for_portlets(self):
        """
        Returns the parent for portlets.
        """
        # TODO: Circular imports
        import lfs.core.utils
        return self.parent or lfs.core.utils.get_default_shop()

    def get_template_name(self):
        """
        Returns the path of the category template.
        """
        if self.template != None:
            id = int(self.template)
            return CATEGORY_TEMPLATES[id][1]["file"]

        return None

    def get_content(self):
        """
        Returns the type of content the template is rendering depending on its
        path.
        """
        if self.get_template_name() == None:
            return CONTENT_PRODUCTS
        if self.get_template_name().startswith(CAT_CATEGORY_PATH):
            return CONTENT_CATEGORIES
        return CONTENT_PRODUCTS


class Product(models.Model):
    """
    A product is sold within a shop.

    **Parameters:**

    name
        The name of the product

    slug
        Part of the URL

    sku
        The external unique id of the product

    price
        The gross price of the product

    price_calculator
        Class that implements lfs.price.PriceCalculator for calculating product price.

    effective_price:
        Only for internal usage (price filtering).

    unit
        The unit of the product. This is displayed beside the quantity
        field.

    price_unit
        The unit of the product's price. This is displayed beside the price

    short_description
        The short description of the product. This is used within overviews.

    description
        The description of the product. This is used within the detailed view
        of the product.

    images
        The images of the product.

    meta_title
        the meta title of the product (the title of the HTML page).

    meta_keywords
        the meta keywords of the product.

    meta_description
        the meta description of the product.

    related_products
        Related products for this products.

    accessories
        Accessories for this products.

    for_sale
        If True the product is for sale and the for sale price will be
        displayed.

    for_sale_price
        The for sale price for the product. Will be displayed if the product
        is for sale.

    active
        If False the product won't be displayed to shop users.

    creation_date
        The creation date of the product

    deliverable
        If True the product is deliverable. Otherwise not.

    manual_delivery_time
        If True the delivery_time of the product is taken. Otherwise the
        delivery time will be calculate on global delivery times and
        selected shipping method.

    delivery_time
        The delivery time of the product. This is only relevant if
        manual_delivery_time is set to true.

    order_time
        Order time of the product when no product is within the stock. This
        is added to the product's delivery time.

    ordered_at
        The date when the product has been ordered. To calculate the rest of
        the order time since the product has been ordered.

    manage_stock_amount
        If true the stock amount of the product will be decreased when a
        product has been saled.

    weight, height, length, width
        The dimensions of the product relevant for the the stock (IOW the
        dimension of the product's box not the product itself).

    tax
        Tax rate of the product.

    static_block
        A static block which has been assigned to the product.

    sub_type
        Sub type of the product. At the moment that is standard, product with
        variants, variant.

    default_variant
        The default variant of a product with variants. This will be
        displayed at first if the shop customer browses to a product with
        variant.

    variant_category
        The variant of a product with variants which will be displayed within
        the category overview.

    variants_display_type
        This decides howt the variants of a product with variants are
        displayed. This is select box of list.

    parent
        The parent of a variant (only relevant for variants)

    active_xxx
        If set to true the information will be taken from the variant.
        Otherwise from the parent product (only relevant for variants)

    supplier
        The supplier of the product

    template
        Sets the template, which renders the product content. If left to None, default template is used.

    active_price_calculation
        If True the price will be calculated by the field price_calculation

    price_calculation
        Formula to calculate price of the product.

    sku_manufacturer
        The product's article ID of the manufacturer (external article id)

    manufacturer
        The manufacturer of the product.

    uid
       The unique id of the product

    type_of_quantity_field
        The type of the quantity field: Integer or Decimal for now.
    """
    # All products
    name = models.CharField(_(u"Name"), help_text=_(u"The name of the product."), max_length=80, blank=True)
    slug = models.SlugField(_(u"Slug"), help_text=_(u"The unique last part of the Product's URL."), unique=True, max_length=80)
    sku = models.CharField(_(u"SKU"), help_text=_(u"Your unique article number of the product."), blank=True, max_length=30)
    price = models.FloatField(_(u"Price"), default=0.0)
    price_calculator = models.CharField(_(u"Price calculator"), null=True, blank=True,
                                        choices=settings.LFS_PRICE_CALCULATORS,
                                        max_length=255)
    effective_price = models.FloatField(_(u"Price"), blank=True)
    price_unit = models.CharField(_(u"Price unit"), blank=True, max_length=20, choices=LFS_PRICE_UNITS)
    unit = models.CharField(_(u"Quanity field unit"), blank=True, max_length=20, choices=LFS_UNITS)
    short_description = models.TextField(_(u"Short description"), blank=True)
    description = models.TextField(_(u"Description"), blank=True)
    images = generic.GenericRelation("Image", verbose_name=_(u"Images"),
        object_id_field="content_id", content_type_field="content_type")

    meta_title = models.CharField(_(u"Meta title"), blank=True, default="<name>", max_length=80)
    meta_keywords = models.TextField(_(u"Meta keywords"), blank=True)
    meta_description = models.TextField(_(u"Meta description"), blank=True)

    related_products = models.ManyToManyField("self", verbose_name=_(u"Related products"), blank=True, null=True,
        symmetrical=False, related_name="reverse_related_products")

    accessories = models.ManyToManyField("Product", verbose_name=_(u"Acessories"), blank=True, null=True,
        symmetrical=False, through="ProductAccessories",
        related_name="reverse_accessories")

    for_sale = models.BooleanField(_(u"For sale"), default=False)
    for_sale_price = models.FloatField(_(u"For sale price"), default=0.0)
    active = models.BooleanField(_(u"Active"), default=False)
    creation_date = models.DateTimeField(_(u"Creation date"), auto_now_add=True)

    # Stocks
    supplier = models.ForeignKey(Supplier, null=True, blank=True)
    deliverable = models.BooleanField(_(u"Deliverable"), default=True)
    manual_delivery_time = models.BooleanField(_(u"Manual delivery time"), default=False)
    delivery_time = models.ForeignKey("DeliveryTime", verbose_name=_(u"Delivery time"), blank=True, null=True, related_name="products_delivery_time")
    order_time = models.ForeignKey("DeliveryTime", verbose_name=_(u"Order time"), blank=True, null=True, related_name="products_order_time")
    ordered_at = models.DateField(_(u"Ordered at"), blank=True, null=True)
    manage_stock_amount = models.BooleanField(_(u"Manage stock amount"), default=False)
    stock_amount = models.FloatField(_(u"Stock amount"), default=0)

    active_packing_unit = models.PositiveSmallIntegerField(_(u"Active packing"), default=0)
    packing_unit = models.FloatField(_(u"Amount per packing"), blank=True, null=True)
    packing_unit_unit = models.CharField(_(u"Packing unit"), blank=True, max_length=30, choices=LFS_PACKING_UNITS)

    static_block = models.ForeignKey("StaticBlock", verbose_name=_(u"Static block"), blank=True, null=True, related_name="products")

    # Dimension
    weight = models.FloatField(_(u"Weight"), default=0.0)
    height = models.FloatField(_(u"Height"), default=0.0)
    length = models.FloatField(_(u"Length"), default=0.0)
    width = models.FloatField(_(u"Width"), default=0.0)

    # Standard Products
    tax = models.ForeignKey(Tax, verbose_name=_(u"Tax"), blank=True, null=True)
    sub_type = models.CharField(_(u"Subtype"),
        max_length=10, choices=PRODUCT_TYPE_CHOICES, default=STANDARD_PRODUCT)

    # Varianted Products
    default_variant = models.ForeignKey("self", verbose_name=_(u"Default variant"), blank=True, null=True)
    category_variant = models.SmallIntegerField(_(u"Category variant"), blank=True, null=True,)

    variants_display_type = models.IntegerField(_(u"Variants display type"),
        choices=VARIANTS_DISPLAY_TYPE_CHOICES, default=LIST)

    # Product Variants
    variant_position = models.IntegerField(default=999)
    parent = models.ForeignKey("self", blank=True, null=True, verbose_name=_(u"Parent"), related_name="variants")
    active_name = models.BooleanField(_(u"Active name"), default=False)
    active_sku = models.BooleanField(_(u"Active SKU"), default=False)
    active_short_description = models.BooleanField(_(u"Active short description"), default=False)
    active_static_block = models.BooleanField(_(u"Active static bock"), default=False)
    active_description = models.BooleanField(_(u"Active description"), default=False)
    active_price = models.BooleanField(_(u"Active price"), default=False)
    active_for_sale = models.PositiveSmallIntegerField(_("Active for sale"), choices=CHOICES, default=CHOICES_STANDARD)
    active_for_sale_price = models.BooleanField(_(u"Active for sale price"), default=False)
    active_images = models.BooleanField(_(u"Active Images"), default=False)
    active_related_products = models.BooleanField(_(u"Active related products"), default=False)
    active_accessories = models.BooleanField(_(u"Active accessories"), default=False)
    active_meta_title = models.BooleanField(_(u"Active meta title"), default=False)
    active_meta_description = models.BooleanField(_(u"Active meta description"), default=False)
    active_meta_keywords = models.BooleanField(_(u"Active meta keywords"), default=False)
    active_dimensions = models.BooleanField(_(u"Active dimensions"), default=False)
    template = models.PositiveSmallIntegerField(_(u"Product template"), blank=True, null=True, choices=PRODUCT_TEMPLATES)

    # Price calculation
    active_price_calculation = models.BooleanField(_(u"Active price calculation"), default=False)
    price_calculation = models.CharField(_(u"Price Calculation"), blank=True, max_length=100)

    # Base price
    active_base_price = models.PositiveSmallIntegerField(_(u"Active base price"), default=0)
    base_price_unit = models.CharField(_(u"Base price unit"), blank=True, max_length=30, choices=LFS_BASE_PRICE_UNITS)
    base_price_amount = models.FloatField(_(u"Base price amount"), default=0.0, blank=True, null=True)

    # Manufacturer
    sku_manufacturer = models.CharField(_(u"SKU Manufacturer"), blank=True, max_length=100)
    manufacturer = models.ForeignKey(Manufacturer, verbose_name=_(u"Manufacturer"), blank=True, null=True, related_name="products")
    type_of_quantity_field = models.PositiveSmallIntegerField(_(u"Type of quantity field"), blank=True, null=True, choices=QUANTITY_FIELD_TYPES)

    objects = ActiveManager()

    uid = models.CharField(max_length=50, editable=False, unique=True, default=get_unique_id_str)

    class Meta:
        ordering = ("name", )

    def __unicode__(self):
        return "%s (%s)" % (self.name, self.slug)

    def save(self, *args, **kwargs):
        """
        Overwritten to save effective_price.
        """
        if self.for_sale:
            self.effective_price = self.for_sale_price
        else:
            self.effective_price = self.price

        super(Product, self).save(*args, **kwargs)

    def get_absolute_url(self):
        """
        Returns the absolute url of the product.
        """
        return ("lfs.catalog.views.product_view", (), {"slug": self.slug})
    get_absolute_url = models.permalink(get_absolute_url)

    @property
    def content_type(self):
        """
        Returns the content type of the product as lower string.
        """
        return u"product"

    def decrease_stock_amount(self, amount):
        """
        If the stock amount is managed by LFS, it decreases stock amount by
        given amount.
        """
        if self.manage_stock_amount:
            self.stock_amount -= amount
        self.save()

    def get_accessories(self):
        """
        Returns the ProductAccessories relationship objects - not the accessory
        (Product) objects.

        This is necessary to have also the default quantity of the relationship.
        """
        if self.is_variant() and not self.active_accessories:
            product = self.parent
        else:
            product = self

        pas = []
        for pa in ProductAccessories.objects.filter(product=product):
            if pa.accessory.is_active():
                pas.append(pa)

        return pas

    def has_accessories(self):
        """
        Returns True if the product has accessories.
        """
        return len(self.get_accessories()) > 0

    def get_attachments(self):
        """
        Returns the ProductAttachment relationship objects. If no attachments
        are found and the instance is a variant returns the parent's ones.
        """
        attachments = ProductAttachment.objects.filter(product=self)
        if not attachments and self.is_variant():
            attachments = ProductAttachment.objects.filter(product=self.parent)
        return attachments

    def has_attachments(self):
        """
        Returns True if the product has attachments.
        """
        return len(self.get_attachments()) > 0

    def get_amount_by_packages(self, quantity):
        """
        """
        packages = math.ceil(quantity / self.packing_unit)
        return packages * self.packing_unit

    def get_categories(self, with_parents=False):
        """
        Returns the categories of the product.
        """
        cache_key = "%s-product-categories-%s-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id, with_parents)
        categories = cache.get(cache_key)

        if categories is not None:
            return categories

        if self.is_variant():
            object = self.parent
        else:
            object = self

        if with_parents:
            categories = []
            for category in object.categories.all():
                while category:
                    categories.append(category)
                    category = category.parent
            categories = categories
        else:
            categories = object.categories.all()

        cache.set(cache_key, categories)
        return categories

    def get_category(self):
        """
        Returns the first category of a product.
        """
        if self.is_variant():
            object = self.parent
        else:
            object = self

        try:
            return object.get_categories()[0]
        except IndexError:
            return None

    def get_current_category(self, request):
        """
        Returns product category based on actual categories of the given product
        and the last visited category.

        This is needed if the category has more than one category to display
        breadcrumbs, selected menu points, etc. appropriately.
        """
        last_category = None
        category = None
        product_categories = self.get_categories()
        if len(product_categories) >= 1:
            try:
                if len(product_categories) == 1:
                    category = product_categories[0]
                    return category
                else:
                    last_category = request.session.get("last_category")

                if last_category is None:
                    return product_categories[0]

                category = None
                if last_category in product_categories:
                    category = last_category
                else:
                    children = last_category.get_all_children()
                    for product_category in product_categories:
                        if product_category in children:
                            category = product_category
                            break
                if category is None:
                    category = product_categories[0]
            except IndexError:
                category = None
        request.session["last_category"] = category
        return category

    def get_description(self):
        """
        Returns the description of the product. Takes care whether the product
        is a variant and description is active or not.
        """
        if self.is_variant():
            if self.active_description:
                description = self.description
                description = description.replace("%P", self.parent.description)
            else:
                description = self.parent.description
        else:
            description = self.description

        return description

    def get_base_price_amount(self):
        if self.is_variant() and self.active_base_price == CHOICES_STANDARD:
            return self.parent.base_price_amount
        else:
            return self.base_price_amount

    def get_base_price_unit(self):
        if self.is_variant() and self.active_base_price == CHOICES_STANDARD:
            return self.parent.base_price_unit
        else:
            return self.base_price_unit

    def get_active_base_price(self):
        """
        Returns true if the base price is supposed to be displayed. Takes care
        whether the product is a variant.
        """
        if self.is_variant():
            if self.active_base_price == CHOICES_STANDARD:
                return self.parent.active_base_price
            else:
                return self.active_base_price == CHOICES_YES
        else:
            return self.active_base_price

    def get_base_packing_price(self, request):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_base_packing_price(request)

    def get_base_packing_price_net(self, request):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_base_packing_price_net(request)

    def get_base_packing_price_gross(self, request):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_base_packing_price_gross(request)

    # TODO: Check whether there is a test case for that and write one if not.
    def get_for_sale(self):
        """
        Returns true if the product is for sale. Takes care whether the product
        is a variant.
        """
        if self.is_variant():
            if self.active_for_sale == CHOICES_STANDARD:
                return self.parent.for_sale
            elif self.active_for_sale == CHOICES_YES:
                return True
            else:
                return False
        else:
            return self.for_sale

    def get_short_description(self):
        """
        Returns the short description of the product. Takes care whether the
        product is a variant and short description is active or not.
        """
        if self.is_variant() and not self.active_short_description:
            return self.parent.short_description
        else:
            return self.short_description

    def get_image(self):
        """
        Returns the first image (the main image) of the product.
        """
        try:
            return self.get_images()[0]
        except IndexError:
            return None

    def get_images(self):
        """
        Returns all images of the product, including the main image.
        """
        cache_key = "%s-product-images-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)
        images = cache.get(cache_key)

        if images is None:
            images = []
            if self.is_variant() and not self.active_images:
                object = self.parent
            else:
                object = self

            images = object.images.all()
            cache.set(cache_key, images)

        return images

    def get_sub_images(self):
        """
        Returns all images of the product, except the main image.
        """
        return self.get_images()[1:]

    def get_meta_title(self):
        """
        Returns the meta title of the product. Takes care whether the product is
        a variant and meta title are active or not.
        """
        if self.is_variant() and not self.active_meta_title:
            mt = self.parent.meta_title
        else:
            mt = self.meta_title

        mt = mt.replace("<name>", self.get_name())
        return mt

    def get_meta_keywords(self):
        """
        Returns the meta keywords of the product. Takes care whether the product
        is a variant and meta keywords are active or not.
        """
        if self.is_variant() and not self.active_meta_keywords:
            mk = self.parent.meta_keywords
        else:
            mk = self.meta_keywords

        mk = mk.replace("<name>", self.get_name())
        mk = mk.replace("<short-description>", self.get_short_description())
        return mk

    def get_meta_description(self):
        """
        Returns the meta description of the product. Takes care whether the
        product is a variant and meta description are active or not.
        """
        if self.is_variant() and not self.active_meta_description:
            md = self.parent.meta_description
        else:
            md = self.meta_description

        md = md.replace("<name>", self.get_name())
        md = md.replace("<short-description>", self.get_short_description())
        return md

    # TODO: Check whether there is a test case for that and write one if not.
    def get_name(self):
        """
        Returns the name of the product. Takes care whether the product is a
        variant and name is active or not.
        """
        if self.is_variant():
            if self.active_name:
                name = self.name
                name = name.replace("%P", self.parent.name)
            else:
                name = self.parent.name
        else:
            name = self.name

        return name

    def get_option(self, property_id):
        """
        Returns the id of the selected option for property with passed id.
        """
        options = cache.get("%s-productpropertyvalue%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id))
        if options is None:
            options = {}
            for pvo in self.property_values.all():
                options[pvo.property_id] = pvo.value
            cache.set("%s-productpropertyvalue%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id), options)
        try:
            return options[property_id]
        except KeyError:
            return None

    def get_displayed_properties(self):
        """
        Returns properties with ``display_on_product`` is True.
        """
        cache_key = "%s-displayed-properties-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)

        properties = cache.get(cache_key)
        if properties:
            return properties

        properties = []
        for ppv in self.property_values.filter(property__display_on_product=True, type=PROPERTY_VALUE_TYPE_DISPLAY):
            if ppv.property.is_select_field:
                try:
                    po = PropertyOption.objects.get(pk=int(float(ppv.value)))
                except (PropertyOption.DoesNotExist, ValueError):
                    continue
                else:
                    value = po.name
                    position = po.position
            else:
                value = ppv.value
                position = 1

            properties.append({
                "name": ppv.property.name,
                "title": ppv.property.title,
                "value": value,
                "position": (ppv.property.position * 1000) + position,
                "unit": ppv.property.unit,
            })

        properties.sort(lambda a, b: cmp(a["position"], b["position"]))
        cache.set(cache_key, properties)
        return properties

    def get_variant_properties(self):
        """
        Returns the property value of a variant in the correct ordering of the
        properties.
        """
        cache_key = "%s-variant-properties-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)

        properties = cache.get(cache_key)
        if properties:
            return properties

        properties = []

        for ppv in self.property_values.filter(type=PROPERTY_VALUE_TYPE_VARIANT).order_by("property__position"):
            if ppv.property.is_select_field:
                try:
                    po = PropertyOption.objects.get(pk=int(float(ppv.value)))
                except PropertyOption.DoesNotExist:
                    continue
                else:
                    value = po.name
            else:
                value = ppv.value
            properties.append({
                "name": ppv.property.name,
                "title": ppv.property.title,
                "value": value,
                "unit": ppv.property.unit,
            })

        cache.set(cache_key, properties)

        return properties

    def has_option(self, property, option):
        """
        Returns True if the variant has the given property / option combination.
        """
        options = cache.get("%s-productpropertyvalue%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id))
        if options is None:
            options = {}
            for pvo in self.property_values.all():
                options[pvo.property_id] = pvo.value
            cache.set("%s-productpropertyvalue%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id), options)

        try:
            return options[property.id] == str(option.id)
        except KeyError:
            return False

    def get_default_properties_price(self):
        """
        Returns the total price of all default properties.
        """
        price = 0
        for property in self.get_configurable_properties():
            if property.add_price:
                # Try to get the default value of the property
                try:
                    ppv = ProductPropertyValue.objects.get(product=self, property=property, type=PROPERTY_VALUE_TYPE_DEFAULT)
                    po = PropertyOption.objects.get(pk=ppv.value)
                except (ObjectDoesNotExist, ValueError):
                    # If there is no explicit default value try to get the first
                    # option.
                    if property.required:
                        try:
                            po = property.options.all()[0]
                        except IndexError:
                            continue
                        else:
                            try:
                                price += po.price
                            except TypeError:
                                pass
                else:
                    try:
                        price += po.price
                    except TypeError:
                        pass

        return price

    def get_price_calculator(self, request):
        """
        Returns the price calculator class as defined in LFS_PRICE_CALCULATORS
        in settings.
        """
        if self.is_variant():
            obj = self.parent
        else:
            obj = self

        if obj.price_calculator is not None:
            price_calculator = obj.price_calculator
        else:
            price_calculator = lfs.core.utils.get_default_shop(request).price_calculator

        price_calculator_class = lfs.core.utils.import_symbol(price_calculator)
        return price_calculator_class(request, self)

    def get_price(self, request, with_properties=True):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_price(with_properties)

    def get_price_net(self, request, with_properties=True):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_price_net(with_properties)

    def get_price_gross(self, request, with_properties=True):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_price_gross(with_properties)

    def get_standard_price(self, request, with_properties=True):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_standard_price(with_properties)

    def get_standard_price_net(self, request, with_properties=True):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_standard_price_net(with_properties)

    def get_standard_price_gross(self, request, with_properties=True):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_standard_price_gross(with_properties)

    def get_for_sale_price(self, request, with_properties=True):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_for_sale_price(with_properties)

    def get_for_sale_price_net(self, request, with_properties=True):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_for_sale_price_net(with_properties)

    def get_for_sale_price_gross(self, request, with_properties=True):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_for_sale_price_gross(with_properties)

    def get_base_price(self, request, with_properties=True):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_base_price(with_properties)

    def get_base_price_net(self, request, with_properties=True):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_base_price_net(with_properties)

    def get_base_price_gross(self, request, with_properties=True):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_base_price_gross(with_properties)

    def get_product_tax_rate(self, request=None):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_product_tax_rate()

    def get_product_tax(self, request=None):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_product_tax()

    def get_tax_rate(self, request):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_customer_tax_rate()

    def get_tax(self, request):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.get_customer_tax()

    def price_includes_tax(self, request=None):
        """
        See lfs.plugins.PriceCalculator
        """
        pc = self.get_price_calculator(request)
        return pc.price_includes_tax()

    def get_price_unit(self):
        """
        Returns the price_unit of the product. Takes care whether the product is
        a variant or not.
        """
        if self.is_variant():
            return self.parent.price_unit
        else:
            return self.price_unit

    def get_unit(self):
        """
        Returns the unit of the product. Takes care whether the product is a
        variant or not.
        """
        if self.is_variant():
            return self.parent.unit
        else:
            return self.unit

    def get_global_properties(self):
        """
        Returns all global properties for the product.
        """
        properties = []
        for property_group in self.property_groups.all():
            properties.extend(property_group.properties.order_by("groupspropertiesrelation"))

        return properties

    def get_local_properties(self):
        """
        Returns local properties of the product
        """
        return self.properties.order_by("productspropertiesrelation")

    def get_properties(self):
        """
        Returns local and global properties
        """
        properties = self.get_global_properties()
        properties.extend(self.get_local_properties())

        properties.sort(lambda a, b: cmp(a.position, b.position))

        return properties

    def get_property_select_fields(self):
        """
        Returns all properties which are `select types`.
        """
        # global
        properties = []
        for property_group in self.property_groups.all():
            properties.extend(property_group.properties.filter(type=PROPERTY_SELECT_FIELD).order_by("groupspropertiesrelation"))

        # local
        for property in self.properties.filter(type=PROPERTY_SELECT_FIELD).order_by("productspropertiesrelation"):
            properties.append(property)

        return properties

    def get_configurable_properties(self):
        """
        Returns all properties which are configurable.
        """
        # global
        properties = []
        for property_group in self.property_groups.all():
            properties.extend(property_group.properties.filter(configurable=True).order_by("groupspropertiesrelation"))

        # local
        for property in self.properties.filter(configurable=True).order_by("productspropertiesrelation"):
            properties.append(property)

        return properties

    def get_sku(self):
        """
        Returns the sku of the product. Takes care whether the product is a
        variant and sku is active or not.
        """
        if self.is_variant() and not self.active_sku:
            return self.parent.sku
        else:
            return self.sku

    def get_manufacturer(self):
        """
        Always return parent manufacturer for variants.
        """
        if self.is_variant():
            return self.parent.manufacturer
        else:
            return self.manufacturer

    def has_related_products(self):
        """
        Returns True if the product has related products.
        """
        return len(self.get_related_products()) > 0

    def get_related_products(self):
        """
        Returns the related products of the product.
        """
        cache_key = "%s-related-products-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)
        related_products = cache.get(cache_key)

        if related_products is None:
            if self.is_variant() and not self.active_related_products:
                related_products = self.parent.related_products.all()
            else:
                related_products = self.related_products.all()

            cache.set(cache_key, related_products)

        return related_products

    def get_default_variant(self):
        """
        Returns the default variant, which is supposed to be displayed within
        the product view.

        This is either a selected variant or the first added variant. If the
        product has no variants it is None.
        """
        cache_key = "%s-default-variant-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)
        default_variant = cache.get(cache_key)

        if default_variant is not None:
            return default_variant

        if self.default_variant is not None:
            default_variant = self.default_variant
        else:
            try:
                default_variant = self.variants.filter(active=True)[0]
            except IndexError:
                return None

        cache.set(cache_key, default_variant)
        return default_variant

    def get_variant_for_category(self, request):
        """
        Returns the variant which is supposed to be displayed within category
        view.

        This is either the cheapest variant, the default variant, an explicitly
        selected one or None.
        """
        if self.category_variant == CATEGORY_VARIANT_CHEAPEST_PRICE:
            return self.get_cheapest_variant(request)
        elif self.category_variant == CATEGORY_VARIANT_CHEAPEST_BASE_PRICE:
            return self.get_cheapest_variant_by_base_price(request)
        elif self.category_variant == CATEGORY_VARIANT_CHEAPEST_PRICES:
            return self.get_default_variant()
        elif self.category_variant == CATEGORY_VARIANT_DEFAULT:
            return self.get_default_variant()
        else:
            try:
                return Product.objects.get(pk=self.category_variant)
            except Product.DoesNotExist:
                return self.get_default_variant()

    def get_cheapest_variant(self, request):
        """
        Returns the cheapest variant by gross price.
        """
        cheapest_variant = None
        min_price = None
        for variant in Product.objects.filter(parent=self):
            price = variant.get_price_gross(request)
            if price == 0:
                continue
            if (min_price is None) or (price < min_price):
                cheapest_variant = variant
                min_price = price

        return cheapest_variant

    def get_cheapest_variant_by_base_price(self, request):
        """
        Returns the cheapest variant by base gross price.
        """
        cheapest_variant = None
        min_price = None
        for variant in Product.objects.filter(parent=self):
            price = variant.get_base_price_gross(request)
            if price == 0:
                continue
            if (min_price is None) or (price < min_price):
                cheapest_variant = variant
                min_price = price

        return cheapest_variant

    def get_cheapest_for_sale_price_gross(self, request):
        """
        Returns the min price and min base price as dict.
        """
        if self.is_variant():
            product = self.parent
        else:
            product = self

        prices = []
        for variant in Product.objects.filter(parent=product, active=True):
            price = variant.get_for_sale_price_gross(request)
            if price not in prices:
                prices.append(price)

            return {
            "price": min(prices),
            "starting_from": len(prices) > 1,
        }

    def get_cheapest_standard_price_gross(self, request):
        """
        Returns the min price and min base price as dict.
        """
        prices = []
        for variant in Product.objects.filter(parent=self, active=True):
            price = variant.get_standard_price_gross(request)
            if price not in prices:
                prices.append(price)

        return {
            "price": min(prices),
            "starting_from": len(prices) > 1,
        }

    def get_cheapest_price_gross(self, request):
        """
        Returns the min price and min base price as dict.
        """
        prices = []
        for variant in Product.objects.filter(parent=self, active=True):
            price = variant.get_price_gross(request)
            if price not in prices:
                prices.append(price)

        return {
            "price": min(prices),
            "starting_from": len(prices) > 1,
        }

    def get_cheapest_base_price_gross(self, request):
        """
        Returns the min price and min base price as dict.
        """
        prices = []
        for variant in Product.objects.filter(parent=self, active=True):
            price = float("%.2f" % variant.get_base_price_gross(request))
            if price not in prices:
                prices.append(price)

        return {
            "price": min(prices),
            "starting_from": len(prices) > 1,
        }

    def get_static_block(self):
        """
        Returns the static block of the product. Takes care whether the product
        is a variant and meta description are active or not.
        """
        cache_key = "%s-product-static-block-%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, self.id)
        block = cache.get(cache_key)
        if block is not None:
            return block

        if self.is_variant() and not self.active_static_block:
            block = self.parent.static_block
        else:
            block = self.static_block

        cache.set(cache_key, block)

        return block

    def get_variants(self):
        """
        Returns the variants of the product.
        """
        return self.variants.filter(active=True).order_by("variant_position")

    def has_variants(self):
        """
        Returns True if the product has variants.
        """
        return len(self.get_variants()) > 0

    def get_variant(self, options):
        """
        Returns the variant with the given options or None.

        The format of the passed properties/options must be tuple as following:

            [property.id|option.id]
            [property.id|option.id]
            ...

        NOTE: These are strings as we get the properties/options pairs out of
        the request and it wouldn't make a lot of sense to convert them to
        objects and back to strings.
        """
        options.sort()
        options = "".join(options)
        for variant in self.variants.filter(active=True):
            temp = variant.property_values.filter(type=PROPERTY_VALUE_TYPE_VARIANT)
            temp = ["%s|%s" % (x.property.id, x.value) for x in temp]
            temp.sort()
            temp = "".join(temp)

            if temp == options:
                return variant

        return None

    def has_variant(self, options):
        """
        Returns true if a variant with given options already exists.
        """
        if self.get_variant(options) is None:
            return False
        else:
            return True

    # Dimensions
    def get_weight(self):
        """
        Returns weight of the product. Takes care whether the product is a
        variant and meta description are active or not.
        """
        if self.is_variant() and not self.active_dimensions:
            return self.parent.weight
        else:
            return self.weight

    def get_width(self):
        """
        Returns width of the product. Takes care whether the product is a
        variant and meta description are active or not.
        """
        if self.is_variant() and not self.active_dimensions:
            return self.parent.width
        else:
            return self.width

    def get_length(self):
        """
        Returns length of the product. Takes care whether the product is a
        variant and meta description are active or not.
        """
        if self.is_variant() and not self.active_dimensions:
            return self.parent.length
        else:
            return self.length

    def get_height(self):
        """
        Returns height of the product. Takes care whether the product is a
        variant and meta description are active or not.
        """
        if self.is_variant() and not self.active_dimensions:
            return self.parent.height
        else:
            return self.height

    def get_active_packing_unit(self):
        """
        Returns True if the packing unit is active. Takes variant into accounts.
        """
        if self.is_variant():
            if self.active_packing_unit == CHOICES_STANDARD:
                return self.parent.active_packing_unit
            else:
                return self.active_packing_unit == CHOICES_YES
        else:
            return self.active_packing_unit

    def get_packing_info(self):
        """
        Returns the packing info of the product as list. Takes variants into
        account.
        """
        if self.is_variant() and self.active_packing_unit == CHOICES_STANDARD:
            obj = self.parent
        else:
            obj = self

        return (obj.packing_unit, obj.packing_unit_unit)

    def is_standard(self):
        """
        Returns True if product is standard product.
        """
        return self.sub_type == STANDARD_PRODUCT

    def is_configurable_product(self):
        """
        Returns True if product is configurable product.
        """
        return self.sub_type == CONFIGURABLE_PRODUCT

    def is_product_with_variants(self):
        """
        Returns True if product is product with variants.
        """
        return self.sub_type == PRODUCT_WITH_VARIANTS

    def is_variant(self):
        """
        Returns True if product is variant.
        """
        return self.sub_type == VARIANT

    def is_active(self):
        """
        Returns the activity state of the product.
        """
        if self.is_variant():
            return self.active and self.parent.active
        else:
            return self.active

    def is_deliverable(self):
        """
        Returns the deliverable state of the product.
        """
        if self.manage_stock_amount and self.stock_amount <= 0 and not self.order_time:
            return False
        else:
            if self.is_variant():
                return self.deliverable and self.parent.deliverable
            else:
                return self.deliverable

    def get_manual_delivery_time(self):
        """
        Returns the manual delivery time of a product or None.
        """
        if self.manual_delivery_time:
            return self.delivery_time

        if self.is_variant() and self.parent.manual_delivery_time:
            return self.parent.delivery_time

        return None

    def get_clean_quantity(self, quantity=1):
        """
        Returns the correct formatted quantity based on the product's type of
        quantity field.
        """
        try:
            quantity = float(quantity)
        except (TypeError, ValueError):
            quantity = 1.0

        type_of_quantity_field = self.get_type_of_quantity_field()
        if type_of_quantity_field == QUANTITY_FIELD_INTEGER:
            quantity = int(quantity)
        elif type_of_quantity_field == QUANTITY_FIELD_DECIMAL_1:
            quantity = locale.format("%.1f", quantity)
        else:
            quantity = locale.format("%.2f", quantity)

        return quantity

    def get_type_of_quantity_field(self):
        """
        Returns the type of quantity field.
        """
        if self.is_variant():
            obj = self.parent
        else:
            obj = self

        if obj.type_of_quantity_field:
            return obj.type_of_quantity_field
        else:
            return QUANTITY_FIELD_INTEGER

    # 3rd party contracts
    def get_parent_for_portlets(self):
        """
        Returns the current category. This will add the portlets of the current
        category to the product portlets.
        """
        if self.is_variant():
            return self.parent
        else:
            # TODO Return the current category
            try:
                return self.categories.all()[0]
            except:
                return None

    def get_template_name(self):
        """
        Method to return the path of the product template
        """
        if self.template != None:
            id = int(self.template)
            return PRODUCT_TEMPLATES[id][1]["file"]
        return None


class ProductAccessories(models.Model):
    """
    Represents the relationship between products and accessories.

    An accessory is just another product which is displayed within a product and
    which can be added to the cart together with it.

    Using an explicit class here to store the position of an accessory within
    a product.

    **Attributes:**

    product
        The product of the relationship.

    accessory
        The accessory of the relationship (which is also a product)

    position
        The position of the accessory within the product.

    quantity
        The proposed amount of accessories for the product.
    """
    product = models.ForeignKey("Product", verbose_name=_(u"Product"), related_name="productaccessories_product")
    accessory = models.ForeignKey("Product", verbose_name=_(u"Accessory"), related_name="productaccessories_accessory")
    position = models.IntegerField(_(u"Position"), default=999)
    quantity = models.FloatField(_(u"Quantity"), default=1)

    class Meta:
        ordering = ("position", )
        verbose_name_plural = "Product accessories"

    def __unicode__(self):
        return "%s -> %s" % (self.product.name, self.accessory.name)

    def get_price(self, request):
        """
        Returns the total price of the accessory based on the product price and
        the quantity in which the accessory is offered.
        """
        return self.accessory.get_price(request) * self.quantity


class PropertyGroup(models.Model):
    """
    Groups product properties together.

    Can belong to several products, products can have several groups.

    **Attributes:**

    name
        The name of the property group.

    products
          The assigned products of the property group.
    """
    name = models.CharField(_(u"Name"), blank=True, max_length=50)
    products = models.ManyToManyField(Product, verbose_name=_(u"Products"), related_name="property_groups")

    class Meta:
        ordering = ("name", )

    def __unicode__(self):
        return self.name

    def get_configurable_properties(self):
        """
        Returns all configurable properties of the property group.
        """
        return self.properties.filter(configurable=True)

    def get_filterable_properties(self):
        """
        Returns all filterable properties of the property group.
        """
        return self.properties.filter(filterable=True)


class Property(models.Model):
    """
    Represents a property of a product like color or size.

    A property has several ``PropertyOptions`` from which the user can choose
    (like red, green, blue).

    A property belongs to exactly one group xor product.

    **Parameters**:

    groups, product:
        The group or product it belongs to. A property can belong to several
        groups and/or to one product.

    name:
        Internal name of the property.

    title:
        Displayed to the customer.

    position:
        The position of the property within the management interface.

    filterable:
        If True the property is used for filtered navigation.

    configurable
        if True the property is used for configurable product.

    display_no_results
        If True filter ranges with no products will be displayed. Otherwise
        they will be removed.

    display_on_product
        If True the property is displayed as an attribute on the product.

    unit:
        Something like cm, mm, m, etc.

    local
        If True the property belongs to exactly one product

    type
       char field, number field or select field

    step
       manuel step for filtering

    price
        The price of the property. Only used for configurable products.

    unit_min
        The minimal unit of the property the shop customer can enter.

    unit_max
        The maximal unit of the property the shop customer can enter.

    unit_step
        The step width the shop customer can edit.

    decimal_places
        The decimal places of a number field.

    required
        If True the field is required (for configurable properties).

    display_price
        If True the option price is displayed (for select field)

    add_price
        if True the option price is added to the product price (for select
        field)

    """
    name = models.CharField(_(u"Name"), max_length=100)
    title = models.CharField(_(u"Title"), max_length=100)
    groups = models.ManyToManyField(PropertyGroup, verbose_name=_(u"Group"), blank=True, null=True, through="GroupsPropertiesRelation", related_name="properties")
    products = models.ManyToManyField(Product, verbose_name=_(u"Products"), blank=True, null=True, through="ProductsPropertiesRelation", related_name="properties")
    position = models.IntegerField(_(u"Position"), blank=True, null=True)
    unit = models.CharField(_(u"Unit"), blank=True, max_length=15)
    display_on_product = models.BooleanField(_(u"Display on product"), default=True)
    local = models.BooleanField(_(u"Local"), default=False)
    filterable = models.BooleanField(_(u"Filterable"), default=True)
    display_no_results = models.BooleanField(_(u"Display no results"), default=False)
    configurable = models.BooleanField(_(u"Configurable"), default=False)
    type = models.PositiveSmallIntegerField(_(u"Type"), choices=PROPERTY_FIELD_CHOICES, default=PROPERTY_TEXT_FIELD)
    price = models.FloatField(_(u"Price"), blank=True, null=True)
    display_price = models.BooleanField(_(u"Display price"), default=True)
    add_price = models.BooleanField(_(u"Add price"), default=True)

    # Number input field
    unit_min = models.FloatField(_(u"Min"), blank=True, null=True)
    unit_max = models.FloatField(_(u"Max"), blank=True, null=True)
    unit_step = models.FloatField(_(u"Step"), blank=True, null=True)
    decimal_places = models.PositiveSmallIntegerField(_(u"Decimal places"), default=0)

    required = models.BooleanField(_(u"Required"), default=False)

    step_type = models.PositiveSmallIntegerField(_(u"Step type"), choices=PROPERTY_STEP_TYPE_CHOICES, default=PROPERTY_STEP_TYPE_AUTOMATIC)
    step = models.IntegerField(_(u"Step"), blank=True, null=True)

    uid = models.CharField(max_length=50, editable=False, unique=True, default=get_unique_id_str)

    class Meta:
        verbose_name_plural = _(u"Properties")
        ordering = ["position"]

    def __unicode__(self):
        return self.name

    @property
    def is_select_field(self):
        return self.type == PROPERTY_SELECT_FIELD

    @property
    def is_text_field(self):
        return self.type == PROPERTY_TEXT_FIELD

    @property
    def is_number_field(self):
        return self.type == PROPERTY_NUMBER_FIELD

    @property
    def is_range_step_type(self):
        return self.step_type == PROPERTY_STEP_TYPE_FIXED_STEP

    @property
    def is_automatic_step_type(self):
        return self.step_type == PROPERTY_STEP_TYPE_AUTOMATIC

    @property
    def is_steps_step_type(self):
        return self.step_type == PROPERTY_STEP_TYPE_MANUAL_STEPS

    def is_valid_value(self, value):
        """
        Returns True if given value is valid for this property.
        """
        if self.is_number_field:
            try:
                float(value)
            except ValueError:
                return False
        return True


class FilterStep(models.Model):
    """
    A step to build filter ranges for a property.

    **Parameters:**

    property
        The property the Step belongs to

    start
        The start of the range. The end will be calculated from the start of the
        next step
    """
    property = models.ForeignKey(Property, verbose_name=_(u"Property"), related_name="steps")
    start = models.FloatField()

    class Meta:
        ordering = ["start"]

    def __unicode__(self):
        return "%s %s" % (self.property.name, self.start)


class GroupsPropertiesRelation(models.Model):
    """
    Represents the m:n relationship between Groups and Properties.

    This is done via an explicit class to store the position of the property
    within the group.

    **Attributes:**

    group
        The property group the property belongs to.

    property
        The property of question of the relationship.

    position
        The position of the property within the group.
    """
    group = models.ForeignKey(PropertyGroup, verbose_name=_(u"Group"), related_name="groupproperties")
    property = models.ForeignKey(Property, verbose_name=_(u"Property"))
    position = models.IntegerField(_(u"Position"), default=999)

    class Meta:
        ordering = ("position", )
        unique_together = ("group", "property")


class ProductsPropertiesRelation(models.Model):
    """
    Represents the m:n relationship between Products and Properties.

    This is done via an explicit class to store the position of the property
    within the product.

    **Attributes:**

    product
        The product of the relationship.

    property
        The property of the relationship.

    position
        The position of the property within the product.

    """
    product = models.ForeignKey(Product, verbose_name=_(u"Product"), related_name="productsproperties")
    property = models.ForeignKey(Property, verbose_name=_(u"Property"))
    position = models.IntegerField(_(u"Position"), default=999)

    class Meta:
        ordering = ("position", )
        unique_together = ("product", "property")


class PropertyOption(models.Model):
    """
    Represents a choosable option of a ``Property`` like red, green, blue.

    A property option can have an optional price (which could change the total
    price of a product).

    **Attributes:**

    property
        The property to which the option belongs

    name
        The name of the option

    price (Not used at the moment)
        The price for the option. This might be used for ``configurable
        products``

    position
        The position of the option within the property

    """
    property = models.ForeignKey(Property, verbose_name=_(u"Property"), related_name="options")

    name = models.CharField(_(u"Name"), max_length=100)
    price = models.FloatField(_(u"Price"), blank=True, null=True, default=0.0)
    position = models.IntegerField(_(u"Position"), default=99)

    uid = models.CharField(max_length=50, editable=False, unique=True, default=get_unique_id_str)

    class Meta:
        ordering = ["position"]

    def __unicode__(self):
        return self.name


class ProductPropertyValue(models.Model):
    """
    Stores the value resp. selected option of a product/property combination.
    This is some kind of EAV.

    **Attributes:**

    product
        The product for which the value is stored.

    parent_id
        If the product is an variant this stores the parent id of it, if the
        product is no variant it stores the id of the product itself. This is
        just used to calculate the filters properly.

    property
        The property for which the value is stored.

    value
        The value for the product/property pair. Dependent of the property
        type the value is either a number, a text or an id of an option.

    type
        The type of the product value, which is on of "filter value",
        "default value", "display value", "variant value"
    """
    product = models.ForeignKey(Product, verbose_name=_(u"Product"), related_name="property_values")
    parent_id = models.IntegerField(_(u"Parent"), blank=True, null=True)
    property = models.ForeignKey("Property", verbose_name=_(u"Property"), related_name="property_values")
    value = models.CharField(_(u"Value"), blank=True, max_length=100)
    value_as_float = models.FloatField(_(u"Value as float"), blank=True, null=True)
    type = models.PositiveSmallIntegerField(_(u"Type"))

    class Meta:
        unique_together = ("product", "property", "value", "type")

    def __unicode__(self):
        return "%s/%s: %s" % (self.product.name, self.property.name, self.value)

    def save(self, *args, **kwargs):
        """
        Overwritten to save the parent id for variants. This is used to count
        the entries per filter. See catalog/utils/get_product_filters for more.
        """
        if self.product.is_variant():
            self.parent_id = self.product.parent.id
        else:
            self.parent_id = self.product.id

        try:
            float(self.value)
        except ValueError:
            pass
        else:
            self.value_as_float = self.value

        super(ProductPropertyValue, self).save(*args, **kwargs)


class Image(models.Model):
    """
    An image with a title and several sizes. Can be part of a product or
    category.

    **Attributes:**

    content
        The content object it belongs to.

    title
        The title of the image.

    image
        The image file.

    position
        The position of the image within the content object it belongs to.

    """
    content_type = models.ForeignKey(ContentType, verbose_name=_(u"Content type"), related_name="image", blank=True, null=True)
    content_id = models.PositiveIntegerField(_(u"Content id"), blank=True, null=True)
    content = generic.GenericForeignKey(ct_field="content_type", fk_field="content_id")

    title = models.CharField(_(u"Title"), blank=True, max_length=100)
    image = ImageWithThumbsField(_(u"Image"), upload_to="images", blank=True, null=True, sizes=THUMBNAIL_SIZES)
    position = models.PositiveSmallIntegerField(_(u"Position"), default=999)

    class Meta:
        ordering = ("position", )

    def __unicode__(self):
        return self.title


class File(models.Model):
    """
    A downloadable file.

    **Attributes:**

    title
        The title of the image. Used within the title tag of the file.

    slug
        The URL of the file.

    content
        The content object the file belongs to (optional).

    position
        The ordinal number within the content object. Used to order the files.

    description
        A long description of the file. Can be used within the content
        (optional).

    file
        The binary file.
    """
    title = models.CharField(blank=True, max_length=100)
    slug = models.SlugField()

    content_type = models.ForeignKey(ContentType, verbose_name=_(u"Content type"), related_name="files", blank=True, null=True)
    content_id = models.PositiveIntegerField(_(u"Content id"), blank=True, null=True)
    content = generic.GenericForeignKey(ct_field="content_type", fk_field="content_id")

    position = models.SmallIntegerField(default=999)
    description = models.CharField(blank=True, max_length=100)
    file = models.FileField(upload_to="files")

    class Meta:
        ordering = ("position", )

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("lfs_file", kwargs={"id": self.id})


class StaticBlock(models.Model):
    """
    A block of static HTML which can be assigned to content objects.

    **Attributes**:

    name
        The name of the static block.

    html
        The static HTML of the block.

    display_files
        If True the files are displayed for download within the static block.

    files
        The files of the static block.

    position
        Position to sort the static blocks
    """
    name = models.CharField(_(u"Name"), max_length=30)
    display_files = models.BooleanField(_(u"Display files"), default=True)
    html = models.TextField(_(u"HTML"), blank=True)
    files = generic.GenericRelation(File, verbose_name=_(u"Files"), object_id_field="content_id", content_type_field="content_type")
    position = models.SmallIntegerField(_(u"Position"), default=1000)

    class Meta:
        ordering = ("position", )

    def __unicode__(self):
        return self.name


class DeliveryTime(models.Model):
    """
    Selectable delivery times.

    **Attributes:**

    min
        The minimal lasting of the delivery date.

    max
        The maximal lasting of the delivery date.

    unit
        The unit of the delivery date, e.g. days, months.

    description
        A short description for internal uses.

    """
    min = models.FloatField(_(u"Min"))
    max = models.FloatField(_(u"Max"))
    unit = models.PositiveSmallIntegerField(_(u"Unit"), choices=DELIVERY_TIME_UNIT_CHOICES, default=DELIVERY_TIME_UNIT_DAYS)
    description = models.TextField(_(u"Description"), blank=True)

    class Meta:
        ordering = ("min", )

    def __unicode__(self):
        return self.round().as_string()

    def __gt__(self, other):
        if self.max > other.max:
            return True
        return False

    def __add__(self, other):
        """
        Adds to delivery times.
        """
        # If necessary we transform both delivery times to the same base (hours)
        if self.unit != other.unit:
            a = self.as_hours()
            b = other.as_hours()
            unit_new = DELIVERY_TIME_UNIT_HOURS
        else:
            a = self
            b = other
            unit_new = self.unit

        # Now we can add both
        min_new = a.min + b.min
        max_new = a.max + b.max
        unit_new = a.unit

        return DeliveryTime(min=min_new, max=max_new, unit=unit_new)

    @property
    def name(self):
        """
        Returns the name of the delivery time
        """
        return self.round().as_string()

    def subtract_days(self, days):
        """
        Substract the given days from delivery time's min and max. Takes the
        unit into account.
        """
        if self.unit == DELIVERY_TIME_UNIT_HOURS:
            max_new = self.max - (24 * days)
            min_new = self.min - (24 * days)
        elif self.unit == DELIVERY_TIME_UNIT_DAYS:
            max_new = self.max - days
            min_new = self.min - days
        elif self.unit == DELIVERY_TIME_UNIT_WEEKS:
            max_new = self.max - (days / 7.0)
            min_new = self.min - (days / 7.0)
        elif self.unit == DELIVERY_TIME_UNIT_MONTHS:
            max_new = self.max - (days / 30.0)
            min_new = self.min - (days / 30.0)

        if min_new < 0:
            min_new = 0
        if max_new < 0:
            max_new = 0

        return DeliveryTime(min=min_new, max=max_new, unit=self.unit)

    def as_hours(self):
        """
        Returns the delivery time in hours.
        """
        if self.unit == DELIVERY_TIME_UNIT_HOURS:
            max = self.max
            min = self.min
        elif self.unit == DELIVERY_TIME_UNIT_DAYS:
            max = self.max * 24
            min = self.min * 24
        elif self.unit == DELIVERY_TIME_UNIT_WEEKS:
            max = self.max * 24 * 7
            min = self.min * 24 * 7
        elif self.unit == DELIVERY_TIME_UNIT_MONTHS:
            max = self.max * 24 * 30
            min = self.min * 24 * 30

        return DeliveryTime(min=min, max=max, unit=DELIVERY_TIME_UNIT_HOURS)

    def as_days(self):
        """
        Returns the delivery time in days.
        """
        if self.unit == DELIVERY_TIME_UNIT_HOURS:
            min = self.min / 24
            max = self.max / 24
        elif self.unit == DELIVERY_TIME_UNIT_DAYS:
            max = self.max
            min = self.min
        elif self.unit == DELIVERY_TIME_UNIT_WEEKS:
            max = self.max * 7
            min = self.min * 7
        elif self.unit == DELIVERY_TIME_UNIT_MONTHS:
            max = self.max * 30
            min = self.min * 30

        return DeliveryTime(min=min, max=max, unit=DELIVERY_TIME_UNIT_DAYS)

    def as_weeks(self):
        """
        Returns the delivery time in weeks.
        """
        if self.unit == DELIVERY_TIME_UNIT_HOURS:
            min = self.min / (24 * 7)
            max = self.max / (24 * 7)
        elif self.unit == DELIVERY_TIME_UNIT_DAYS:
            max = self.max / 7
            min = self.min / 7
        elif self.unit == DELIVERY_TIME_UNIT_WEEKS:
            max = self.max
            min = self.min
        elif self.unit == DELIVERY_TIME_UNIT_MONTHS:
            max = self.max * 4
            min = self.min * 4

        return DeliveryTime(min=min, max=max, unit=DELIVERY_TIME_UNIT_WEEKS)

    def as_months(self):
        """
        Returns the delivery time in months.
        """
        if self.unit == DELIVERY_TIME_UNIT_HOURS:
            min = self.min / (24 * 30)
            max = self.max / (24 * 30)
        elif self.unit == DELIVERY_TIME_UNIT_DAYS:
            max = self.max / 30
            min = self.min / 30
        elif self.unit == DELIVERY_TIME_UNIT_WEEKS:
            max = self.max / 4
            min = self.min / 4
        elif self.unit == DELIVERY_TIME_UNIT_MONTHS:
            max = self.max
            min = self.min

        return DeliveryTime(min=min, max=max, unit=DELIVERY_TIME_UNIT_MONTHS)

    def as_reasonable_unit(self):
        """
        Returns the delivery time as reasonable unit based on the max hours.

        This is used to show the delivery time to the shop customer.
        """
        delivery_time = self.as_hours()

        if delivery_time.max > 1440:               # > 2 months
            return delivery_time.as_months()
        elif delivery_time.max > 168:              # > 1 week
            return delivery_time.as_weeks()
        elif delivery_time.max > 48:               # > 2 days
            return delivery_time.as_days()
        else:
            return delivery_time

    def as_string(self):
        """
        Returns the delivery time as string.
        """
        if self.min == 0:
            self.min = self.max

        if self.min == self.max:
            if self.min == 1:
                unit = DELIVERY_TIME_UNIT_SINGULAR[self.unit]
            else:
                unit = self.get_unit_display()

            return "%s %s" % (self.min, unit)
        else:
            return "%s-%s %s" % (self.min, self.max, self.get_unit_display())

    def round(self):
        """
        Rounds the min/max of the delivery time to an integer and returns a new
        DeliveryTime object.
        """
        min = int("%.0f" % (self.min + 0.001))
        max = int("%.0f" % (self.max + 0.001))

        return DeliveryTime(min=min, max=max, unit=self.unit)


class ProductAttachment(models.Model):
    """
    Represents a downloadable attachment of a product.

    **Attributes:**

    title
        The title of the attachment

    description
        The description of the attachment

    file
        The downloadable file of the attachment

    product
        The product the attachment belongs to

    position
        The position of the attachment within a product.
    """
    title = models.CharField(_(u"Title"), max_length=50)
    description = models.TextField(_(u"Description"), blank=True)
    file = models.FileField(upload_to="files")
    product = models.ForeignKey(Product, verbose_name=_(u"Product"), related_name="attachments")
    position = models.IntegerField(_(u"Position"), default=1)

    class Meta:
        ordering = ("position", )

    def get_url(self):
        if self.file.url:
            return self.file.url
        return None