branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>package com.mycompany.salestax.dao;
import com.mycompany.salestax.beans.Tax;
public interface TaxDao extends AbstractDao<Tax, Long> {
}
<file_sep>package com.mycompany.salestax.dao.hibernate;
import org.springframework.stereotype.Repository;
import com.mycompany.salestax.beans.Tax;
import com.mycompany.salestax.dao.TaxDao;
@Repository(value = "taxDaoHibernate")
public class TaxDaoHibernate extends AbstractDaoHibernate<Tax, Long> implements TaxDao {
}
<file_sep>package com.mycompany.salestax.services.impl;
import org.junit.Assert;
import org.springframework.test.util.ReflectionTestUtils;
import com.mycompany.salestax.beans.ProductType;
import com.mycompany.salestax.dao.mock.ProductTypeDaoMock;
import com.mycompany.salestax.services.ProductTypeService;
public class ProductTypeServiceImplTest extends AbstractServiceImplTest<ProductType> {
public ProductTypeServiceImplTest() {
super();
ProductTypeService mockService = new ProductTypeServiceImpl();
ReflectionTestUtils.setField(mockService, "dao", new ProductTypeDaoMock());
this.service = mockService;
}
@Override
protected void hookCheckLoadedObject(ProductType productType) {
Assert.assertNotNull(productType.getDescription());
Assert.assertNotNull(productType.getTax());
Assert.assertNotNull(productType.getId());
}
@Override
protected ProductType hookTestObjectModification(ProductType productType) {
productType.setDescription("another description");
return productType;
}
@Override
protected void hookCheckUpdatedObject(ProductType objectToUpdate, ProductType objectUpdated) {
Assert.assertEquals(objectToUpdate.getDescription(), objectUpdated.getDescription());
}
}
<file_sep>salestax.hibernate.dialect=org.hibernate.dialect.H2Dialect
salestax.hibernate.show_sql=true
salestax.hibernate.hbm2ddl.auto=validate<file_sep>package com.mycompany.salestax.rest.resources;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.mycompany.salestax.beans.Product;
import com.mycompany.salestax.services.ProductService;
@Component
@Path("/products")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ProductResource {
private final static Logger LOG = LoggerFactory.getLogger(ProductResource.class);
@Autowired
private ProductService service;
@GET
public List<Product> getProducts() {
List<Product> list = service.list();
LOG.debug("Products list: " + list.toString());
return list;
}
}
<file_sep>package com.mycompany.salestax.dao;
import java.io.Serializable;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.mycompany.salestax.beans.ModelBean;
@Transactional
public interface AbstractDao<T extends ModelBean<ID>, ID extends Serializable> {
T create(T object);
T read(ID id);
void update(T object);
void delete(ID id);
List<T> list();
}
<file_sep>package com.mycompany.salestax.services.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.mycompany.salestax.beans.ImportTax;
import com.mycompany.salestax.dao.ImportTaxDao;
import com.mycompany.salestax.services.ImportTaxService;
@Service("importTaxServiceImpl")
public class ImportTaxServiceImpl extends AbstractServiceImpl<ImportTax, Long> implements ImportTaxService {
@Resource(name = "importTaxDaoHibernate")
public void setDao(ImportTaxDao importTaxDao) {
this.dao = importTaxDao;
}
}
<file_sep>drop table Products if exists
drop table ProductTypes if exists
drop table Taxes if exists
drop table ImportTaxes if exists<file_sep>package com.mycompany.salestax.dao.constants;
public interface ContextPaths {
String HIBERNATE_TEST_CONTEXT = "file:src/main/resources/META-INF/hibernate.xml";
String MOCK_TEST_CONTEXT = "file:src/test/resources/META-INF/mock-test.xml";
}
<file_sep>package com.mycompany.salestax.services.impl;
import org.junit.Assert;
import org.springframework.test.util.ReflectionTestUtils;
import com.mycompany.salestax.beans.Product;
import com.mycompany.salestax.dao.mock.ProductDaoMock;
import com.mycompany.salestax.services.ProductService;
public class ProductServiceImplTest extends AbstractServiceImplTest<Product> {
public ProductServiceImplTest() {
super();
ProductService mockService = new ProductServiceImpl();
ReflectionTestUtils.setField(mockService, "dao", new ProductDaoMock());
this.service = mockService;
}
@Override
protected void hookCheckLoadedObject(Product product) {
Assert.assertNotNull(product.getDescription());
Assert.assertNotNull(product.getImportTax());
Assert.assertNotNull(product.getPrice());
Assert.assertNotNull(product.getType());
Assert.assertNotNull(product.getId());
}
@Override
protected Product hookTestObjectModification(Product product) {
product.setDescription("another description");
return product;
}
@Override
protected void hookCheckUpdatedObject(Product objectToUpdate, Product objectUpdated) {
Assert.assertEquals(objectToUpdate.getDescription(), objectUpdated.getDescription());
}
}
<file_sep>package com.mycompany.salestax.dao;
import com.mycompany.salestax.beans.ProductType;
public interface ProductTypeDao extends AbstractDao<ProductType, Long> {
}
<file_sep>package com.mycompany.salestax.beans;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.apache.commons.lang3.builder.ToStringBuilder;
@Entity
@Table(name = "ImportTaxes")
public class ImportTax implements Serializable, ModelBean<Long> {
private static final long serialVersionUID = -3015161145255023640L;
private Long id;
private BigDecimal value;
private String description;
public ImportTax() {
}
public ImportTax(String description) {
this.description = description;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "import_tax_id", unique = true, nullable = false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "import_tax_value", unique = true, nullable = false, precision = 20, scale = 2)
public BigDecimal getValue() {
return value;
}
public void setValue(BigDecimal value) {
this.value = value;
}
@Column(name = "description", unique = true, nullable = false, length = 255)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public int hashCode() {
int hash = 6;
hash = 24 * hash + ((getDescription() != null) ? getDescription().hashCode() : 0);
hash = 24 * hash + ((getValue() != null) ? getValue().hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof ImportTax))
return false;
return (this.getDescription().equals(((ImportTax) object).getDescription())) ? true : false;
}
}
<file_sep>var productsData, totalPrice = 0, totalSales = 0;
var fill_combo_box = (function() {
initialize = function() {
$.ajax({
type: 'GET',
url: "/salestaxrest/products",
contentType: "application/json",
dataType: "json",
success: function(data) {
productsData = data;
var options = $("#products");
options.append($("<option />").val("0").text("Select a product"));
$.each(data, function(info) {
options.append($("<option />").val(this.productId).text(this.description));
});
}
});
};
return {
initialize : initialize
};
})();
$(function(){
fill_combo_box.initialize();
});<file_sep>package com.mycompany.salestax.dao.hibernate;
import javax.annotation.Resource;
import org.springframework.test.context.ContextConfiguration;
import com.mycompany.salestax.beans.ImportTax;
import com.mycompany.salestax.dao.AbstractDao;
import com.mycompany.salestax.dao.ImportTaxDaoTest;
import com.mycompany.salestax.dao.constants.ContextPaths;
@ContextConfiguration(locations = ContextPaths.HIBERNATE_TEST_CONTEXT)
public class ImportTaxDaoHibernateTest extends ImportTaxDaoTest {
@Resource(name = "importTaxDaoHibernate")
@Override
protected void setAbstractDao(AbstractDao<ImportTax, Long> importTaxDao) {
this.abstractDao = importTaxDao;
}
}
<file_sep>package com.mycompany.salestax.dao;
import com.mycompany.salestax.beans.ImportTax;
public interface ImportTaxDao extends AbstractDao<ImportTax, Long> {
}
<file_sep>package com.mycompany.salestax.services.impl;
import java.io.Serializable;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.mycompany.salestax.beans.ModelBean;
import com.mycompany.salestax.dao.AbstractDao;
import com.mycompany.salestax.services.AbstractService;
@Transactional
public abstract class AbstractServiceImpl<T extends ModelBean<ID>, ID extends Serializable> implements AbstractService<T, ID> {
protected AbstractDao<T, ID> dao;
public T save(T objectToSave) {
return dao.create(objectToSave);
}
public T load(ID id) {
return dao.read(id);
}
public void update(T objectToUdpate) {
dao.update(objectToUdpate);
}
public void remove(ID id) {
dao.delete(id);
}
public List<T> list() {
return dao.list();
}
}
<file_sep>package com.mycompany.salestax.util;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.RandomStringUtils;
import com.mycompany.salestax.beans.ImportTax;
import com.mycompany.salestax.beans.ModelBean;
import com.mycompany.salestax.beans.Product;
import com.mycompany.salestax.beans.ProductType;
import com.mycompany.salestax.beans.Tax;
public abstract class MockBeanFactory {
@SuppressWarnings("unchecked")
public static <T extends ModelBean<Long>> T getMock(Class<T> beanClass) {
if (beanClass.equals(Product.class)) {
return (T) getProductMock();
} else if (beanClass.equals(ProductType.class)) {
return (T) getProductTypeMock();
} else if (beanClass.equals(Tax.class)) {
return (T) getTaxMock();
} else if (beanClass.equals(ImportTax.class)) {
return (T) getImportTaxMock();
}
return null;
}
public static <T extends ModelBean<Long>> List<T> getListMock(Class<T> beanClass, int length) {
List<T> list = new ArrayList<T>();
for (int i = 0; i < length; i++) {
list.add(getMock(beanClass));
}
return list;
}
private static ImportTax getImportTaxMock() {
ImportTax importTax = new ImportTax();
importTax.setDescription("description" + getRandomValue());
importTax.setValue(new BigDecimal(300));
return importTax;
}
private static Tax getTaxMock() {
Tax tax = new Tax();
tax.setDescription("description" + getRandomValue());
tax.setValue(new BigDecimal(200));
return tax;
}
private static ProductType getProductTypeMock() {
ProductType productType = new ProductType();
productType.setDescription("description" + getRandomValue());
productType.setTax((Tax) getTaxMock());
productType.getTax().setId(1l);
return productType;
}
private static Product getProductMock() {
Product product = new Product();
product.setDescription("description" + getRandomValue());
product.setImportTax((ImportTax) getImportTaxMock());
product.getImportTax().setId(1l);
product.setPrice(new BigDecimal(100));
product.setType((ProductType) getProductTypeMock());
product.getType().setId(1l);
return product;
}
private static String getRandomValue() {
return RandomStringUtils.random(100);
}
}
<file_sep>package com.mycompany.salestax.services.impl;
import org.junit.Assert;
import org.springframework.test.util.ReflectionTestUtils;
import com.mycompany.salestax.beans.Tax;
import com.mycompany.salestax.dao.mock.TaxDaoMock;
import com.mycompany.salestax.services.TaxService;
public class TaxServiceImplTest extends AbstractServiceImplTest<Tax> {
public TaxServiceImplTest() {
super();
TaxService mockService = new TaxServiceImpl();
ReflectionTestUtils.setField(mockService, "dao", new TaxDaoMock());
this.service = mockService;
}
@Override
protected void hookCheckLoadedObject(Tax tax) {
Assert.assertNotNull(tax.getDescription());
Assert.assertNotNull(tax.getValue());
Assert.assertNotNull(tax.getId());
}
@Override
protected Tax hookTestObjectModification(Tax tax) {
tax.setDescription("another description");
return tax;
}
@Override
protected void hookCheckUpdatedObject(Tax objectToUpdate, Tax objectUpdated) {
Assert.assertEquals(objectToUpdate.getDescription(), objectUpdated.getDescription());
}
}
<file_sep>salestax.script.inicializacion=classpath*:META-INF/salestax.h2.init.sql
salestax.script.finalizacion=classpath*:META-INF/salestax.h2.destroy.sql
salestax.script.datos=classpath*:META-INF/salestax.data.sql
<file_sep>package com.mycompany.salestax.dao.mock;
import javax.annotation.Resource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import com.mycompany.salestax.beans.Tax;
import com.mycompany.salestax.dao.AbstractDao;
import com.mycompany.salestax.dao.TaxDaoTest;
import com.mycompany.salestax.dao.constants.ContextPaths;
@ContextConfiguration(locations = ContextPaths.MOCK_TEST_CONTEXT)
@TestExecutionListeners(DependencyInjectionTestExecutionListener.class)
public class TaxDaoMockTest extends TaxDaoTest {
@Resource(name = "taxDaoMock")
@Override
protected void setAbstractDao(AbstractDao<Tax, Long> taxDao) {
this.abstractDao = taxDao;
}
}
<file_sep>package com.mycompany.salestax.services.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.mycompany.salestax.beans.ProductType;
import com.mycompany.salestax.dao.ProductTypeDao;
import com.mycompany.salestax.services.ProductTypeService;
@Service("productTypeServiceImpl")
public class ProductTypeServiceImpl extends AbstractServiceImpl<ProductType, Long> implements ProductTypeService {
@Resource(name = "productTypeDaoHibernate")
public void setDao(ProductTypeDao productTypeDao) {
this.dao = productTypeDao;
}
}
<file_sep>package com.mycompany.salestax.services.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.mycompany.salestax.beans.Product;
import com.mycompany.salestax.dao.ProductDao;
import com.mycompany.salestax.services.ProductService;
@Service("productServiceImpl")
public class ProductServiceImpl extends AbstractServiceImpl<Product, Long> implements ProductService {
@Resource(name = "productDaoHibernate")
public void setDao(ProductDao productDao) {
this.dao = productDao;
}
}
<file_sep>package com.mycompany.salestax.dao.hibernate;
import javax.annotation.Resource;
import org.springframework.test.context.ContextConfiguration;
import com.mycompany.salestax.beans.Tax;
import com.mycompany.salestax.dao.AbstractDao;
import com.mycompany.salestax.dao.TaxDaoTest;
import com.mycompany.salestax.dao.constants.ContextPaths;
@ContextConfiguration(locations = ContextPaths.HIBERNATE_TEST_CONTEXT)
public class TaxDaoHibernateTest extends TaxDaoTest {
@Resource(name = "taxDaoHibernate")
@Override
protected void setAbstractDao(AbstractDao<Tax, Long> productDao) {
this.abstractDao = productDao;
}
}
| 63915032417ab91f3b455a62d7f9712192e71769 | [
"JavaScript",
"Java",
"SQL",
"INI"
] | 23 | Java | juanma-cvega/salestax | a3a819e457440b6e2698f721ca8a42c136ae78f3 | 8de173f1c9b01f4319914478df4542677aaf37e7 | |
refs/heads/master | <file_sep>import re
from deck import Deck, deck_36_cards
from player import Player
# 36 карт
# ходят по очереди
# не вскрываемся
class BlackJack:
_deck = deck_36_cards()
_players: [Player]
_value_to_points = {
6: 6,
7: 7,
8: 8,
9: 9,
10: 10,
'J': 2,
'Q': 3,
'K': 4,
'A': 1,
}
def __init__(self):
self._deck = deck_36_cards()
self._deck.shuffle()
self._players = []
def add_player(self, player):
self._players.append(player)
def _count_players_score(self, player: Player):
points_total = 0
for card in player.cards:
value = card.value # 6 - 10, "J" ...
points = self._value_to_points[value]
points_total += points
return points_total
def _get_yes_or_no(self):
no_regexp = " *[нН][еЕ]?[тТ]?"
yes_regexp = " *[дД][аА]?"
take_card = None
while take_card is None:
answer = input("Берешь карту? <Да/Нет>")
if re.match(no_regexp, answer):
take_card = False
elif re.match(yes_regexp, answer):
take_card = True
else:
print("Неправильный ответ, повторите")
return take_card
def play(self):
# раздаем по 2 карты в начале игры
for player in self._players:
player.cards.append(self._deck.pop())
player.cards.append(self._deck.pop())
# игроки берут карты
for player in self._players:
self._player_turn(player)
# определяем победителя
best = 0, []
for player in self._players:
player_score = self._count_players_score(player)
if player_score > 21:
player_score = 0
if player_score == best[0]:
best[1].append(player)
elif player_score > best[0]:
best = player_score, [player]
print(f"Победители (набрали {best[0]} очков)")
for winner in best[1]:
print(player.name)
def _player_turn(self, player: Player):
print(f"Привет, {player.name}. Ходи.")
while self._count_players_score(player) < 21:
print(f"Очков: {self._count_players_score(player)}")
take_card = self._get_yes_or_no()
if take_card:
card_from_deck = self._deck.pop()
player.cards.append(card_from_deck)
print(card_from_deck)
else:
break
print(f"Хорошая игра, {player.name}. Ваш счет {self._count_players_score(player)}")
<file_sep>import random
from card import Card, Suits
class Deck:
def __init__(self):
self._cards = []
def add(self, card: Card):
self._cards.append(card)
def pop(self): #take card from top
if len(self._cards) == 0:
return None
return self._cards.pop()
@property
def size(self):
return len(self._cards)
@property
def empty(self):
return len(self._cards) == 0
def shuffle(self): #перетасовать колоду
for i in range(4):
random.shuffle(self._cards)
def __str__(self):
return f"Колода в которой {self.size} карт"
def deck_36_cards():
deck = Deck()
for value in [6,7,8,9,10,'J','Q','K','A']:
for suit in list(Suits):
deck.add(Card(value, suit))
return deck<file_sep>from enum import Enum
Suits = Enum("Suits", "Diamonds Hearts Spades Clubs")
_suit_to_picture = {
Suits.Diamonds: "♦",
Suits.Hearts : "♥",
Suits.Spades : "♠",
Suits.Clubs : "♣"
}
class Card:
def __init__(self, value, suit):
value_ok = (isinstance(value, int) and (6 <= value <= 10)
or isinstance(value, str) and (value in "JQKA"))
suit_ok = suit in list(Suits)
if not (value_ok and suit_ok):
raise TypeError("Карта создана с неправильным значением либо мастью")
self._value = value
self._suit = suit
@property
def value(self):
return self._value
@property
def suit(self):
return self._suit
def __str__(self):
suit_symbol = _suit_to_picture[self._suit]
return f"{self._value}{suit_symbol}"
<file_sep>from player import Player
from blackjack import BlackJack
game = BlackJack()
game.add_player(Player("Petya"))
game.add_player(Player("Vova"))
game.play()<file_sep>class Player:
def __init__(self, nickname):
self.name = nickname
self.cards = []
| a110a3c1115ab6333cd6367f360753fc4d489090 | [
"Python"
] | 5 | Python | SergeiShevtsov/cmd_cards | 8531f0d15c35504cada8f825f3a7eb7454222212 | 14143c1ff4e7e974111f1a51a7d6f7e461543bd3 | |
refs/heads/master | <repo_name>fgulan/ios-infinum-academy-2019<file_sep>/TVShows/Modules/ShowDetails/ShowDetailsViewController.swift
//
// ShowDetailsViewController.swift
// TVShows
//
// Created by <NAME> on 30/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import RxSwift
import RxCocoa
final class ShowDetailsViewController: UIViewController {
private let disposeBag = DisposeBag()
// MARK: - Public properties -
var presenter: ShowDetailsPresenterInterface!
// MARK: - Lifecycle -
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
}
// MARK: - Extensions -
extension ShowDetailsViewController: ShowDetailsViewInterface {
}
private extension ShowDetailsViewController {
func setupView() {
let output = ShowDetailsViewOutput()
_ = presenter.setup(with: output)
}
}
<file_sep>/TVShows/Common/Networking/Routers/ShowRouter.swift
//
// HomeRouter.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import Alamofire
extension Router {
enum Show {
static func getShows() -> Router {
return Router(
path: "/shows",
method: .get,
encoding: JSONEncoding.default
)
}
}
}
<file_sep>/TVShows/Modules/Home/Cell/TVShowTableViewCell.swift
//
// TVShowTableViewCell.swift
// TVShows
//
// Created by <NAME> on 24/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import Kingfisher
class TVShowTableViewCell: UITableViewCell {
@IBOutlet private weak var _titleLabel: UILabel!
@IBOutlet private weak var _imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
_setupImageView()
}
func configure(with item: Show) {
_titleLabel.text = item.title
if let imageUrl = item.imageUrl {
let url = URL(string: "https://api.infinum.academy/")?
.appendingPathComponent(imageUrl)
_imageView.kf.setImage(with: url)
} else {
_imageView.image = nil
}
}
// MARK: - Private functions -
private func _setupImageView() {
_imageView.layer.shadowColor = UIColor.black.cgColor
_imageView.layer.shadowOffset = CGSize(width: 0, height: 1)
_imageView.layer.shadowOpacity = 1
_imageView.layer.shadowRadius = 2.0
_imageView.clipsToBounds = false
}
}
<file_sep>/TVShows/Modules/Home/HomeInterfaces.swift
//
// HomeInterfaces.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import RxSwift
import RxCocoa
enum Home {
struct ViewOutput {
let refresh: Driver<Void>
let logoutPressed: Driver<Void>
}
struct ViewInput {
let items: Driver<[CollectionCellItem]>
}
enum NavigationOption {
case showDetails(showId: String)
}
}
protocol HomeWireframeInterface: WireframeInterface {
func navigate(to option: Home.NavigationOption)
}
protocol HomeViewInterface: ViewInterface, Refreshable {
}
protocol HomePresenterInterface: PresenterInterface {
func setup(with output: Home.ViewOutput) -> Home.ViewInput
}
protocol HomeInteractorInterface: InteractorInterface {
func loadShows() -> Single<[Show]>
}
<file_sep>/TVShows/Modules/ShowDetails/ShowDetailsInterfaces.swift
//
// ShowDetailsInterfaces.swift
// TVShows
//
// Created by <NAME> on 30/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import RxSwift
import RxCocoa
enum ShowDetailsNavigationOption {
}
protocol ShowDetailsWireframeInterface: WireframeInterface {
func navigate(to option: ShowDetailsNavigationOption)
}
protocol ShowDetailsViewInterface: ViewInterface {
}
protocol ShowDetailsPresenterInterface: PresenterInterface {
func setup(with output: ShowDetailsViewOutput) -> ShowDetailsViewInput
}
protocol ShowDetailsInteractorInterface: InteractorInterface {
}
struct ShowDetailsInput {
}
struct ShowDetailsViewInput {
}
struct ShowDetailsViewOutput {
}
<file_sep>/TVShows/Application/Initializers/LoggieInitializer.swift
//
// LoggieInitializer.swift
// TVShows
//
// Created by <NAME> on 28/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
#if DEV
import Loggie
#endif
final class LoggieInitializer: Initializable {
func initialize() {
#if DEV
URLProtocol.registerClass(LoggieURLProtocol.self)
#endif
}
}
<file_sep>/TVShows/Common/Networking/Services/ShowsSessionManager.swift
//
// ShowsSessionManager.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import Alamofire
import RxCocoa
import RxSwift
#if DEV
import Loggie
#endif
class ShowsSessionManager {
static var session: SessionManager = {
#if DEV
let configuration = URLSessionConfiguration.loggie
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
#else
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
#endif
}()
private init() {}
}
class TokenAdapter: RequestAdapter {
private let _token: String
init(token: String) {
_token = token
}
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
var urlRequest = urlRequest
urlRequest.setValue(_token, forHTTPHeaderField: "Authorization")
return urlRequest
}
}
<file_sep>/TVShows/Modules/ShowDetails/ShowDetailsPresenter.swift
//
// ShowDetailsPresenter.swift
// TVShows
//
// Created by <NAME> on 30/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import RxSwift
import RxCocoa
final class ShowDetailsPresenter {
// MARK: - Private properties -
private unowned let view: ShowDetailsViewInterface
private let interactor: ShowDetailsInteractorInterface
private let wireframe: ShowDetailsWireframeInterface
// MARK: - Lifecycle -
init(view: ShowDetailsViewInterface, interactor: ShowDetailsInteractorInterface, wireframe: ShowDetailsWireframeInterface) {
self.view = view
self.interactor = interactor
self.wireframe = wireframe
}
}
// MARK: - Extensions -
extension ShowDetailsPresenter: ShowDetailsPresenterInterface {
func setup(with output: ShowDetailsViewOutput) -> ShowDetailsViewInput {
return ShowDetailsViewInput()
}
}
<file_sep>/TVShows/Common/UI/Controller/ShowsViewController.swift
//
// ShowsViewController.swift
// TVShows
//
// Created by <NAME> on 28/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import RxSwift
class ShowsViewController: UIViewController {
#if DEBUG
private let startResourceCount = Resources.total
#endif
// MARK: - Lifecycle -
override func viewDidLoad() {
super.viewDidLoad()
#if DEBUG
let logString = "⚠️ Number of start resources = \(Resources.total) ⚠️"
log.info(logString)
#endif
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .`default`
}
deinit {
#if DEBUG
let mainQueue = DispatchQueue.main
let when = DispatchTime.now() + DispatchTimeInterval.milliseconds(300)
mainQueue.asyncAfter(deadline: when) {
let logString = "⚠️ Number of resources after dispose = \(Resources.total) ⚠️"
log.info(logString)
}
/*
!!! This cleanup logic is adapted for example app use case. !!!
It is being used to detect memory leaks during pre release tests.
!!! In case you want to have some resource leak detection logic, the simplest
method is just printing out `RxSwift.Resources.total` periodically to output. !!!
/* add somewhere in
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
*/
_ = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.subscribe(onNext: { _ in
print("Resource count \(RxSwift.Resources.total)")
})
Most efficient way to test for memory leaks is:
* navigate to your screen and use it
* navigate back
* observe initial resource count
* navigate second time to your screen and use it
* navigate back
* observe final resource count
In case there is a difference in resource count between initial and final resource counts, there might be a memory
leak somewhere.
The reason why 2 navigations are suggested is because first navigation forces loading of lazy resources.
*/
#endif
}
}
<file_sep>/TVShows/Common/Extensions/Rx/DataRequest+Rx.swift
//
// DataRequest+Rx.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import RxSwift
import Alamofire
import CodableAlamofire
extension DataRequest: ReactiveCompatible {}
extension Reactive where Base == DataRequest {
func responseDecodableObject<T: Decodable>(
queue: DispatchQueue? = nil,
keyPath: String? = nil,
decoder: JSONDecoder = JSONDecoder())
-> Single<T> {
return Single<T>.create { [weak base] (single) -> Disposable in
let request = base?.responseDecodableObject(
queue: queue,
keyPath: keyPath,
decoder: decoder,
completionHandler: { (response: DataResponse<T>) in
switch response.result {
case .success(let value): single(.success(value))
case .failure(let error): single(.error(error))
}
})
return Disposables.create {
request?.cancel()
}
}
}
func response(queue: DispatchQueue? = nil) -> Completable {
return Completable.create(subscribe: { [weak base] (completable) -> Disposable in
let request = base?.response(
queue: queue,
completionHandler: { (response) in
if let error = response.error {
completable(.error(error))
} else {
completable(.completed)
}
})
return Disposables.create {
request?.cancel()
}
})
}
}
extension SessionManager: ReactiveCompatible {}
extension Reactive where Base == SessionManager {
var manager: Single<SessionManager> {
return Single.just(base)
}
}
<file_sep>/Podfile
platform :ios, '11.0'
inhibit_all_warnings!
use_frameworks!
def reactive
pod 'RxSwift'
pod 'RxCocoa'
end
def networking
pod 'Alamofire'
pod 'AlamofireNetworkActivityIndicator'
pod 'AlamofireNetworkActivityLogger'
pod 'Kingfisher'
pod 'Loggie'
pod 'CodableAlamofire'
end
def ui
pod 'SnapKit'
pod 'SwiftI18n/I18n+Case'
pod 'PKHUD'
pod 'AHKNavigationController'
end
def other
pod 'SwiftyBeaver'
end
def shared
reactive
networking
ui
other
end
target 'TVShows' do
shared
end
post_install do |installer|
installer.pods_project.targets.each do |target|
if target.name == 'RxSwift'
target.build_configurations.each do |config|
if config.name == 'AppStore_Debug' || config.name == 'Development_Debug'
config.build_settings['OTHER_SWIFT_FLAGS'] ||= ['$(inherited)', '-D', 'TRACE_RESOURCES']
end
end
end
end
end
<file_sep>/TVShows/Common/UI/Keyboard/KeyboardHandler.swift
//
// KeyboardHandler.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class KeyboardHandler {
private init() {}
struct PresentingParams {
let keyboardSize: CGSize
let animationDuration: Double
let state: State
enum State {
case show
case hide
}
}
enum Insets {
case forShown(inset: CGFloat)
case forHidden(inset: CGFloat)
case always(inset: CGFloat)
case never
func add(to value: CGFloat, with state: PresentingParams.State) -> CGFloat {
switch (self, state) {
case (.always(let inset), _):
return value + inset
case (.forShown(let inset), .show):
return value + inset
case (.forHidden(let inset), .hide):
return value + inset
default:
return value
}
}
}
}
extension KeyboardHandler {
static private(set) var keyboardPresenting: Observable<PresentingParams> = {
let show = NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification).map { (notification) -> PresentingParams? in
guard let userInfo = notification.userInfo,
let keyboardSize = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
let animationDuration = ((userInfo[UIResponder.keyboardAnimationDurationUserInfoKey]) as? NSNumber)?.doubleValue
else { return nil }
return PresentingParams(
keyboardSize: keyboardSize.size,
animationDuration: animationDuration,
state: .show
)
}
let hide = NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification).map { (notification) -> PresentingParams? in
guard let userInfo = notification.userInfo,
let animationDuration = ((userInfo[UIResponder.keyboardAnimationDurationUserInfoKey]) as? NSNumber)?.doubleValue
else { return nil }
return PresentingParams(
keyboardSize: CGSize.zero,
animationDuration: animationDuration,
state: .hide
)
}
return Observable
.merge([show, hide])
.share(replay: 1, scope: .forever)
.compactMap { $0 }
}()
static func registerDidShow(animatedHandler: @escaping ()->()) -> Disposable {
return NotificationCenter.default.rx
.notification(UIResponder.keyboardDidShowNotification)
.observeOn(MainScheduler.instance)
.subscribe(onNext: { _ in animatedHandler() })
}
static func register(handler: @escaping (_ params: PresentingParams) -> ()) -> Disposable {
return keyboardPresenting
.observeOn(MainScheduler.instance)
.subscribe(onNext: { handler($0) })
}
static func register(animatedHandler: @escaping (_ params: PresentingParams) -> ()) -> Disposable {
return KeyboardHandler.register(handler: { (params) in
UIView.animate(withDuration: params.animationDuration, animations: {
animatedHandler(params)
})
})
}
static func register(scrollView: UIScrollView, additionalInsets: Insets = .never) -> Disposable {
return KeyboardHandler.register(animatedHandler: { (params) in
let height = params.keyboardSize.height
scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: height, right: 0)
scrollView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: height, right: 0)
})
}
static func register(constraint: NSLayoutConstraint, additionalInsets: Insets = .never, aditionalAnimationBlock: (() -> ())? = nil) -> Disposable {
return KeyboardHandler.register(animatedHandler: { (params) in
let height = additionalInsets.add(to: params.keyboardSize.height, with: params.state)
constraint.constant = height
aditionalAnimationBlock?()
})
}
}
<file_sep>/TVShows/Common/UI/CellsAndItems/Cells/TV Show/TVShowCollectionViewCell.swift
//
// TVShowCollectionViewCell.swift
// TVShows
//
// Created by <NAME> on 24/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
struct ShowCollectionCellItem {
let title: String
let imageUrl: URL?
let didSelectAction: () -> ()
}
extension ShowCollectionCellItem: CollectionCellItem {
func cell(from collectionView: UICollectionView, at indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(ofType: TVShowCollectionViewCell.self,
for: indexPath)
cell.configure(with: self)
return cell
}
func didSelect(at indexPath: IndexPath) {
didSelectAction()
}
}
class TVShowCollectionViewCell: UICollectionViewCell {
@IBOutlet private weak var _titleLabel: UILabel!
@IBOutlet private weak var _imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
_setupImageView()
}
func configure(with item: ShowCollectionCellItem) {
_titleLabel.text = item.title
_imageView.kf.setImage(with: item.imageUrl)
}
// MARK: - Private functions -
private func _setupImageView() {
_imageView.layer.shadowColor = UIColor.black.cgColor
_imageView.layer.shadowOffset = CGSize(width: 0, height: 1)
_imageView.layer.shadowOpacity = 1
_imageView.layer.shadowRadius = 2.0
_imageView.clipsToBounds = false
}
}
<file_sep>/TVShows/Common/Extensions/Rx/Single+General.swift
//
// Single+Utility.swift
//
// Created by <NAME> on 03/02/2019.
// Copyright © 2019 Infinum. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
extension Single {
/// Converts current Single sequence to Driver, completing on error event.
///
/// - Returns: Driver - completing on error event
func asDriverOnErrorComplete() -> Driver<Element> {
return asDriver(onErrorDriveWith: .empty())
}
}
extension PrimitiveSequenceType where Trait == SingleTrait {
/// Maps sequence element to given value.
///
/// - Parameter value: Value to map
/// - Returns: Sequence where element is given value.
func mapTo<T>(_ value: T) -> Single<T> {
return map { _ in value }
}
/// Maps sequence element to Void type.
///
/// - Returns: Sequence where element is of Void type.
func mapToVoid() -> Single<Void> {
return mapTo(())
}
}
extension PrimitiveSequenceType where Trait == SingleTrait {
/// Shows loading on subscribe event.
func handleShowLoading(with progressable: Progressable) -> Single<Element> {
return self
.do(onSubscribe: { [unowned progressable] in progressable.showLoading() })
}
/// Hides loading on success event or error event.
func handleHideLoading(with progressable: Progressable) -> Single<Element> {
return self
.do(onSuccess: { [unowned progressable] _ in progressable.hideLoading() })
.do(onError: { [unowned progressable] _ in progressable.hideLoading() })
}
/// Shows loading on subscribe event and hides loading on success event or error event.
func handleLoading(with progressable: Progressable) -> Single<Element> {
return self
.handleShowLoading(with: progressable)
.handleHideLoading(with: progressable)
}
/// Shows failure on error event.
func handleShowFailure(with progressable: Progressable) -> Single<Element> {
return self
.do(onError: { [unowned progressable] in progressable.showFailure(with: $0) })
}
/// Shows loading on subscribe event, hides loading on success
/// event or error event and shows failure on error event.
func handleLoadingAndError(with progressable: Progressable) -> Single<Element> {
return self
.handleLoading(with: progressable)
.handleShowFailure(with: progressable)
}
}
<file_sep>/TVShows/Modules/Home/HomeInteractor.swift
//
// HomeInteractor.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import Foundation
import Alamofire
import RxSwift
import RxCocoa
final class HomeInteractor {
private let _service: Service
private let _sessionManager: SessionManager
init(service: Service = .instance, sessionManager: SessionManager = ShowsSessionManager.session) {
_service = service
_sessionManager = sessionManager
}
}
// MARK: - Extensions -
extension HomeInteractor: HomeInteractorInterface {
func loadShows() -> Single<[Show]> {
return _service
.request([Show].self, router: Router.Show.getShows())
}
}
<file_sep>/TVShows/Modules/Login_StandardVIPER_NonRx/LoginSInterfaces.swift
//
// LoginSInterfaces.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import Alamofire
enum LoginSNavigationOption {
case home
}
protocol LoginSWireframeInterface: WireframeInterface {
func navigate(to option: LoginSNavigationOption)
}
protocol LoginSViewInterface: ViewInterface {
}
protocol LoginSPresenterInterface: PresenterInterface {
func didSelectLoginWith(email: String, password: String)
func didSelectRegisterWith(email: String, password: String)
}
protocol LoginSInteractorInterface: InteractorInterface {
func login(email: String, password: String, completion: @escaping (Result<LoginData>) -> ())
func register(email: String, password: String, completion: @escaping (Result<User>) -> ())
}
<file_sep>/TVShows/Common/Networking/Routers/UserRouter.swift
//
// UserRouter.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import Alamofire
extension Router {
enum User {
static func loginWith(email: String, password: String) -> Router {
let params = [
"email": email,
"password": <PASSWORD>
]
return Router(
path: "/users/sessions",
method: .post,
params: params,
encoding: JSONEncoding.default
)
}
static func registerWith(email: String, password: String) -> Router {
let params = [
"email": email,
"password": <PASSWORD>
]
return Router(
path: "/users",
method: .post,
params: params,
encoding: JSONEncoding.default
)
}
}
}
<file_sep>/README.md
# Infinum Academy - iOS 2019
<file_sep>/TVShows/Application/Initializers/AlamofireInitializer.swift
//
// AlamofireInitializer.swift
// TVShows
//
// Created by <NAME> on 28/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import AlamofireNetworkActivityLogger
import AlamofireNetworkActivityIndicator
final class AlamofireInitializer: Initializable {
func initialize() {
#if DEBUG
NetworkActivityLogger.shared.startLogging()
NetworkActivityLogger.shared.level = .debug
#endif
NetworkActivityIndicatorManager.shared.isEnabled = true
}
}
<file_sep>/TVShows/Application/AppDelegate.swift
//
// AppDelegate.swift
// TVShows
//
// Created by <NAME> on 11/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
initializeInitializers()
window = createAndSetupWindow()
return true
}
}
// MARK: - Private methods -
// MARK: - Initializers
private extension AppDelegate {
func initializeInitializers() {
let initializers: [Initializable] = [
LoggingInitializer(),
AlamofireInitializer(),
LoggieInitializer()
]
initializers.forEach { $0.initialize() }
}
}
// MARK: - UI Setup
private extension AppDelegate {
func createAndSetupWindow() -> UIWindow {
let window = UIWindow(frame: UIScreen.main.bounds)
let navigationController = ShowsNavigationController()
navigationController.setRootWireframe(LoginWireframe())
window.rootViewController = navigationController
window.makeKeyAndVisible()
return window
}
}
<file_sep>/TVShows/Modules/Login/LoginViewController.swift
//
// LoginViewController.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import RxSwift
import RxCocoa
final class LoginViewController: ShowsViewController {
// MARK: - Private properties -
private let _disposeBag = DisposeBag()
// MARK: - IBOutlets
@IBOutlet private weak var _scrollView: UIScrollView!
@IBOutlet private weak var _loginButton: UIButton!
@IBOutlet private weak var _registerButton: UIButton!
@IBOutlet private weak var _checkmarkButton: UIButton!
@IBOutlet private weak var _emailField: UITextField!
@IBOutlet private weak var _passwordField: UITextField!
// MARK: - Public properties -
var presenter: LoginPresenterInterface!
// MARK: - Lifecycle -
override func viewDidLoad() {
super.viewDidLoad()
_setupView()
_setupUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
}
// MARK: - Extensions -
extension LoginViewController: LoginViewInterface {
}
private extension LoginViewController {
func _setupView() {
let toggleRememberMe = _checkmarkButton.rx.tap.asDriver()
.scan(false) { state, _ in !state }
.startWith(false)
toggleRememberMe
.drive(_checkmarkButton.rx.isSelected)
.disposed(by: _disposeBag)
let output = Login.ViewOutput(email: _emailField.rx.text.asDriver().unwrap(),
password: _passwordField.rx.text.asDriver().unwrap(),
rememberMe: toggleRememberMe,
loginPressed: _loginButton.rx.tap.asDriver(),
registerPressed: _registerButton.rx.tap.asDriver())
let input = presenter.setupBinding(with: output)
input
.loginEnabled
.drive(_loginButton.rx.isEnabled)
.disposed(by: _disposeBag)
input
.registerEnabled
.drive(_registerButton.rx.isEnabled)
.disposed(by: _disposeBag)
}
func _setupUI() {
_loginButton.layer.cornerRadius = 6.0
_loginButton.setBackgroundImage(.from(color: UIColor.TVShows.pink), for: .normal)
_loginButton.setBackgroundImage(.from(color: UIColor.TVShows.pink.withAlphaComponent(0.5)),
for: .disabled)
KeyboardHandler
.register(scrollView: _scrollView)
.disposed(by: _disposeBag)
}
}
<file_sep>/TVShows/Modules/Login/LoginPresenter.swift
//
// LoginPresenter.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import RxSwift
import RxCocoa
final class LoginPresenter {
// MARK: - Private properties -
private unowned let _view: LoginViewInterface
private let _interactor: LoginInteractorInterface
private let _wireframe: LoginWireframeInterface
// MARK: - Lifecycle -
init(view: LoginViewInterface, interactor: LoginInteractorInterface, wireframe: LoginWireframeInterface) {
_view = view
_interactor = interactor
_wireframe = wireframe
}
}
// MARK: - Extensions -
extension LoginPresenter: LoginPresenterInterface {
func setupBinding(with output: Login.ViewOutput) -> Login.ViewInput {
let loginModel = Driver
.combineLatest(output.email, output.password, output.rememberMe)
.map(Login.Model.init)
let hasEmailAndPassword = loginModel
.map { !$0.email.isEmpty && !$0.password.isEmpty }
output
.loginPressed
.withLatestFrom(loginModel)
.pipe(to: loginWith(loginModel:))
output
.registerPressed
.withLatestFrom(loginModel)
.pipe(to: _registerWith(loginModel:))
return Login.ViewInput(loginEnabled: hasEmailAndPassword,
registerEnabled: hasEmailAndPassword)
}
}
private extension LoginPresenter {
func _registerWith(loginModel: Driver<Login.Model>) {
loginModel
.flatMapLatest { [unowned _interactor, unowned _wireframe] model -> Driver<Login.Model> in
return _interactor
.registerWith(email: model.email, password: model.password)
.handleLoadingAndError(with: _wireframe)
.asDriverOnErrorComplete()
.mapTo(model)
}
.pipe(to: loginWith(loginModel:))
}
func loginWith(loginModel: Driver<Login.Model>) {
loginModel
.flatMapLatest { [unowned _interactor, unowned _wireframe] model -> Driver<Void> in
return _interactor
.loginWith(email: model.email, password: model.password)
.handleLoadingAndError(with: _wireframe)
.asDriverOnErrorComplete()
}
.mapTo(Login.NavigationOption.home)
.pipe(to: handle(navigation:))
}
func handle(navigation: Driver<Login.NavigationOption>) {
navigation.pipe(to: _wireframe.navigate(using: ))
}
}
<file_sep>/TVShows/Common/Extensions/UI/UIColor+Inits.swift
//
// UIColor+Inits.swift
// TVShows
//
// Created by <NAME> on 28/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(rgbHex: Int, alpha: CGFloat = 1) {
let r = (rgbHex >> 16) & 0xFF
let g = (rgbHex >> 8) & 0xFF
let b = rgbHex & 0xFF
self.init(
red: CGFloat(r) / 255.0,
green: CGFloat(g) / 255.0,
blue: CGFloat(b) / 255.0,
alpha: alpha
)
}
convenience init?(rgbHex: String, alpha: CGFloat = 1) {
let string = rgbHex
.trimmingCharacters(in: .whitespacesAndNewlines)
.uppercased()
guard
string.count == 6,
let int = Int(string, radix: 16)
else {
return nil
}
self.init(rgbHex: int, alpha: alpha)
}
}
<file_sep>/TVShows/Modules/Login_StandardVIPER_NonRx/LoginSInteractor.swift
//
// LoginSInteractor.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import Foundation
import Alamofire
import CodableAlamofire
final class LoginSInteractor {
private let _sessionManager: SessionManager
init(sessionManager: SessionManager = ShowsSessionManager.session) {
_sessionManager = sessionManager
}
}
// MARK: - Extensions -
extension LoginSInteractor: LoginSInteractorInterface {
func login(email: String, password: String, completion: @escaping (Result<LoginData>) -> ()) {
let sessionManager = _sessionManager
let request = Router.User.loginWith(email: email, password: <PASSWORD>)
sessionManager
.request(request)
.validate()
.responseDecodableObject(keyPath: "data") { (response: DataResponse<LoginData>) in
if let token = response.result.value?.token {
sessionManager.adapter = TokenAdapter(token: token)
}
completion(response.result)
}
}
func register(email: String, password: String, completion: @escaping (Result<User>) -> ()) {
let request = Router.User.registerWith(email: email, password: <PASSWORD>)
_sessionManager
.request(request)
.validate()
.responseDecodableObject(keyPath: "data") { (response: DataResponse<User>) in
completion(response.result)
}
}
}
<file_sep>/TVShows/Common/Networking/Services/Service.swift
//
// Service.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import Alamofire
import RxSwift
final class Service {
static var instance = Service()
}
extension Service {
func request<T: Decodable>(router: Router, keyPath: String = "data") -> Single<T> {
return Single.just(ShowsSessionManager.session)
.map { $0.request(router) }
.map { $0.validate() }
.flatMap { $0.rx.responseDecodableObject(keyPath: keyPath) }
}
func request<T: Decodable>(_: T.Type, router: Router) -> Single<T> {
return request(router: router)
}
func requestCompletion(router: Router) -> Single<Void> {
return Single.just(ShowsSessionManager.session)
.map { $0.request(router) }
.map { $0.validate() }
.flatMap { $0.rx.response().andThen(Single.just(())) }
}
}
<file_sep>/TVShows/Common/UI/CellsAndItems/Basic/Reactive/ReactiveDataSourceDelegates.swift
//
// ReactiveDataSourceDelegates.swift
//
//
import UIKit
import RxSwift
import RxCocoa
extension Reactive where Base: TableDataSourceDelegate {
var items: Binder<[TableCellItem]?> {
return Binder(self.base) { dataSourceDelegate, items in
dataSourceDelegate.items = items
}
}
var sections: Binder<[TableSectionItem]?> {
return Binder(self.base) { dataSourceDelegate, sections in
dataSourceDelegate.sections = sections
}
}
}
extension Reactive where Base: CollectionDataSourceDelegate {
var items: Binder<[CollectionCellItem]?> {
return Binder(self.base) { dataSourceDelegate, items in
dataSourceDelegate.items = items
}
}
var sections: Binder<[CollectionSectionItem]?> {
return Binder(self.base) { dataSourceDelegate, sections in
dataSourceDelegate.sections = sections
}
}
}
<file_sep>/TVShows/Common/Extensions/UI/UIBarButtonItem+General.swift
//
// UIBarButtonItem+General.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import RxSwift
extension UIBarButtonItem {
convenience init(barButtonSystemItem: UIBarButtonItem.SystemItem, action: (()->())? = nil) {
self.init(barButtonSystemItem: barButtonSystemItem, target: nil, action: nil)
self.rx.tap
.asDriver()
.drive(onNext: { action?() })
.disposed(by: disposeBag)
}
convenience init(title: String?, style: UIBarButtonItem.Style = .plain, action: (()->())? = nil) {
self.init(title: title, style: style, target: nil, action: nil)
self.rx.tap
.asDriver()
.drive(onNext: { action?() })
.disposed(by: disposeBag)
}
convenience init(image: UIImage?, style: UIBarButtonItem.Style = .plain, action: (()->())? = nil) {
self.init(image: image, style: style, target: nil, action: nil)
self.rx.tap
.asDriver()
.drive(onNext: { action?() })
.disposed(by: disposeBag)
}
private var disposeBag: DisposeBag {
let lookup = objc_getAssociatedObject(self, associatedKeysDisposeBag) as? DisposeBag
if let lookup = lookup {
return lookup
}
let newDisposeBag = DisposeBag()
objc_setAssociatedObject(self, associatedKeysDisposeBag, newDisposeBag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return newDisposeBag
}
private var associatedKeysDisposeBag: String {
return "UIBarButtonItem.rx.disposeBag"
}
}
<file_sep>/TVShows/Common/UI/CellsAndItems/Basic/Protocols/CollectionViewReloader.swift
//
// CollectionViewReloader.swift
//
//
import UIKit
protocol CollectionViewReloader {
func reload(_ collectionView: UICollectionView, oldSections: [CollectionSectionItem]?, newSections: [CollectionSectionItem]?)
}
struct DefaultCollectionViewReloader: CollectionViewReloader {
func reload(_ collectionView: UICollectionView, oldSections: [CollectionSectionItem]?, newSections: [CollectionSectionItem]?) {
collectionView.reloadData()
}
}
<file_sep>/TVShows/Modules/Login/LoginInterfaces.swift
//
// LoginInterfaces.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import RxSwift
import RxCocoa
enum Login {
struct ViewOutput {
let email: Driver<String>
let password: Driver<String>
let rememberMe: Driver<Bool>
let loginPressed: Driver<Void>
let registerPressed: Driver<Void>
}
struct ViewInput {
let loginEnabled: Driver<Bool>
let registerEnabled: Driver<Bool>
}
struct Model {
let email: String
let password: String
let rememberMe: Bool
}
enum NavigationOption {
case home
}
}
protocol LoginWireframeInterface: WireframeInterface {
func navigate(to option: Login.NavigationOption)
func navigate(using option: Driver<Login.NavigationOption>)
}
protocol LoginViewInterface: ViewInterface {
}
protocol LoginPresenterInterface: PresenterInterface {
func setupBinding(with output: Login.ViewOutput) -> Login.ViewInput
}
protocol LoginInteractorInterface: InteractorInterface {
func loginWith(email: String, password: String) -> Single<Void>
func registerWith(email: String, password: String) -> Single<Void>
}
<file_sep>/TVShows/Common/UI/Other/OnePixelConstraint.swift
//
// OnePixelConstraint.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class OnePixelConstraint: NSLayoutConstraint {
override func awakeFromNib() {
super.awakeFromNib()
constant = 1 / UIScreen.main.scale
}
}
<file_sep>/TVShows/Modules/Login_StandardVIPER_NonRx/LoginSPresenter.swift
//
// LoginSPresenter.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import Foundation
final class LoginSPresenter {
// MARK: - Private properties -
private unowned let _view: LoginSViewInterface
private let _interactor: LoginSInteractorInterface
private let _wireframe: LoginSWireframeInterface
// MARK: - Lifecycle -
init(wireframe: LoginSWireframeInterface, view: LoginSViewInterface, interactor: LoginSInteractorInterface) {
_wireframe = wireframe
_view = view
_interactor = interactor
}
}
// MARK: - Extensions -
extension LoginSPresenter: LoginSPresenterInterface {
func didSelectLoginWith(email: String, password: String) {
_wireframe.showLoading()
_interactor.login(email: email, password: <PASSWORD>) { [weak _wireframe] result in
_wireframe?.hideLoading()
switch result {
case .success:
_wireframe?.navigate(to: .home)
case .failure(let error):
_wireframe?.showFailure(with: error)
}
}
}
func didSelectRegisterWith(email: String, password: String) {
_wireframe.showLoading()
_interactor.register(email: email, password: <PASSWORD>) { [weak _wireframe, weak self] result in
_wireframe?.hideLoading()
switch result {
case .success:
self?.didSelectLoginWith(email: email, password: <PASSWORD>)
case .failure(let error):
_wireframe?.showFailure(with: error)
}
}
}
}
<file_sep>/TVShows/Application/Constants.swift
//
// Constants.swift
// TVShows
//
// Created by <NAME> on 28/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
enum Constants {
enum URL {
static let baseDomainUrl = "https://api.infinum.academy"
static let baseUrl = baseDomainUrl + "/api"
}
}
<file_sep>/TVShows/Modules/Home/HomeViewController.swift
//
// HomeViewController.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import RxSwift
import RxCocoa
final class HomeViewController: UIViewController {
// MARK: - Private properties -
private let _disposeBag = DisposeBag()
private lazy var _dataSourceDelegate: CollectionDataSourceDelegate = {
return CollectionDataSourceDelegate(collectionView: _collectionView)
}()
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
_collectionView.refreshControl = refreshControl
return refreshControl
}()
// MARK: - IBOutlets
@IBOutlet private weak var _collectionView: UICollectionView!
// MARK: - Public properties -
var presenter: HomePresenterInterface!
// MARK: - Lifecycle -
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupUI()
_collectionView.collectionViewLayout.invalidateLayout()
_collectionView.setCollectionViewLayout(ShowsGridFlowLayout(), animated: false)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
_collectionView.refreshControl?.endRefreshing()
}
}
// MARK: - Extensions -
extension HomeViewController: HomeViewInterface {
}
private extension HomeViewController {
func setupView() {
let logoutButton = UIBarButtonItem(image: #imageLiteral(resourceName: "ic-logout"))
navigationItem.leftBarButtonItem = logoutButton
let refresh = refreshControl.rx
.controlEvent(.valueChanged)
.asDriver()
let output = Home.ViewOutput(refresh: refresh,
logoutPressed: logoutButton.rx.tap.asDriver())
let input = presenter.setup(with: output)
input.items
.drive(_dataSourceDelegate.rx.items)
.disposed(by: _disposeBag)
input.items
.mapTo(false)
.drive(refreshControl.rx.isRefreshing)
.disposed(by: _disposeBag)
}
func setupUI() {
title = "Shows"
}
}
<file_sep>/TVShows/Common/UI/Controller/ShowsNavigationController.swift
//
// ShowsNavigationController.swift
// TVShows
//
// Created by <NAME> on 28/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import AHKNavigationController
class ShowsNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 11.0, *) {
navigationBar.prefersLargeTitles = false
}
navigationBar.backgroundColor = .white
navigationBar.tintColor = UIColor.TVShows.gray
navigationBar.isTranslucent = false
}
}
<file_sep>/TVShows/Common/UI/CellsAndItems/Basic/DataSourceDelegates/TableDataSourceDelegate.swift
//
// TableDataSourceDelegate.swift
//
//
import UIKit
import RxSwift
class EmptyTableSection: TableSectionItem {
var tableItems: [TableCellItem]
init(tableItems: [TableCellItem]) {
self.tableItems = tableItems
}
convenience init?(tableItems: [TableCellItem]?) {
if let item = tableItems {
self.init(tableItems: item)
return
}
return nil
}
var headerHeight: CGFloat {
if #available(iOS 11.0, *) {
return .leastNonzeroMagnitude
} else {
return 1
}
}
var estimatedHeaderHeight: CGFloat {
return headerHeight
}
var footerHeight: CGFloat {
if #available(iOS 11.0, *) {
return .leastNonzeroMagnitude
} else {
return 1
}
}
var estimatedFooterHeight: CGFloat {
return footerHeight
}
}
class TableDataSourceDelegate: NSObject {
private let tableView: UITableView
private let reloader: TableViewReloader
private let disposeBag = DisposeBag()
var sections: [TableSectionItem]? {
didSet(oldValue) { reloader.reload(tableView, oldSections: oldValue, newSections: sections) }
}
var items: [TableCellItem]? {
get { return sections?.map({ $0.tableItems }).reduce([TableCellItem](), +) }
set {
guard let tableItems = newValue else { return }
sections = [EmptyTableSection(tableItems: tableItems) as TableSectionItem]
}
}
init(tableView: UITableView, reloader: TableViewReloader = DefaultTableViewReloader()) {
self.tableView = tableView
self.reloader = reloader
super.init()
tableView.dataSource = self
tableView.rx
.setDelegate(self)
.disposed(by: disposeBag)
}
}
extension TableDataSourceDelegate: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return sections?.count ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections?[section].tableItems.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return sections![indexPath].cell(from: tableView, at: indexPath)
}
// func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// return sections![section].titleForHeader(from: tableView, at: section)
// }
//
// func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
// return sections![section].titleForFooter(from: tableView, at: section)
// }
}
extension TableDataSourceDelegate: UITableViewDelegate {
func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return sections![section].estimatedHeaderHeight
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return sections![section].headerHeight
}
func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
return sections![section].estimatedFooterHeight
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return sections![section].footerHeight
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return sections![indexPath].estimatedHeight
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return sections![indexPath].height
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return sections?[section].headerView(from:tableView, at:section)
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return sections?[section].footerView(from:tableView, at:section)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
return sections![indexPath].didSelect(at: indexPath)
}
}
<file_sep>/TVShows/Common/UI/CellsAndItems/Basic/Protocols/SectionItem.swift
//
// SectionItem.swift
//
//
import UIKit
protocol SectionItem {
}
protocol TableSectionItem: SectionItem {
//Requred
var tableItems: [TableCellItem] { get }
//Optional
var headerHeight: CGFloat { get }
var estimatedHeaderHeight: CGFloat { get }
var footerHeight: CGFloat { get }
var estimatedFooterHeight: CGFloat { get }
func headerView(from tableView: UITableView, at index: Int) -> UIView?
func titleForHeader(from tableView: UITableView, at index: Int) -> String?
func footerView(from tableView: UITableView, at index: Int) -> UIView?
func titleForFooter(from tableView: UITableView, at index: Int) -> String?
}
protocol CollectionSectionItem: SectionItem {
//Requred
var collectionItems: [CollectionCellItem] { get }
//Optional
}
extension TableSectionItem {
var headerHeight: CGFloat {
return UITableView.automaticDimension
}
var estimatedHeaderHeight: CGFloat {
return 0
}
var footerHeight: CGFloat {
return UITableView.automaticDimension
}
var estimatedFooterHeight: CGFloat {
return 0
}
func headerView(from tableView: UITableView, at index: Int) -> UIView? {
return nil
}
func titleForHeader(from tableView: UITableView, at index: Int) -> String? {
return nil
}
func footerView(from tableView: UITableView, at index: Int) -> UIView? {
return nil
}
func titleForFooter(from tableView: UITableView, at index: Int) -> String? {
return nil
}
}
extension Array where Element: TableSectionItem {
subscript(indexPath: IndexPath) -> TableCellItem {
return self[indexPath.section].tableItems[indexPath.row]
}
}
extension Array where Element == TableSectionItem {
subscript(indexPath: IndexPath) -> TableCellItem {
return self[indexPath.section].tableItems[indexPath.row]
}
}
extension Array where Element: CollectionSectionItem {
subscript(indexPath: IndexPath) -> CollectionCellItem {
return self[indexPath.section].collectionItems[indexPath.row]
}
}
extension Array where Element == CollectionSectionItem {
subscript(indexPath: IndexPath) -> CollectionCellItem {
return self[indexPath.section].collectionItems[indexPath.row]
}
}
<file_sep>/TVShows/Application/Initializers/Initializable.swift
//
// Initializable.swift
// TVShows
//
// Created by <NAME> on 28/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
protocol Initializable {
func initialize()
}
<file_sep>/TVShows/Modules/Home/HomeWireframe.swift
//
// HomeWireframe.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import RxSwift
import RxCocoa
final class HomeWireframe: BaseWireframe {
// MARK: - Private properties -
private let storyboard = UIStoryboard(name: "Home", bundle: nil)
// MARK: - Module setup -
init() {
let moduleViewController = storyboard.instantiateViewController(ofType: HomeViewController.self)
super.init(viewController: moduleViewController)
let interactor = HomeInteractor()
let presenter = HomePresenter(view: moduleViewController, interactor: interactor, wireframe: self)
moduleViewController.presenter = presenter
}
}
// MARK: - Extensions -
extension HomeWireframe: HomeWireframeInterface {
func navigate(to option: Home.NavigationOption) {
switch option {
case .showDetails(showId: let id):
navigationController?.pushWireframe(ShowDetailsWireframe(showId: id))
}
}
}
<file_sep>/TVShows/Common/Extensions/UI/UICollectionView+General.swift
//
// UICollectionView+General.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
extension UICollectionView {
func dequeueReusableCell<T: UICollectionViewCell>(ofType _: T.Type, withReuseIdentifier identifier: String? = nil, for indexPath: IndexPath) -> T {
let identifier = identifier ?? String(describing: T.self)
return dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! T
}
func register<T>(cellOfType _: T.Type, withReuseIdentifier identifier: String? = nil) {
let cellName = String(describing: T.self)
let identifier = identifier ?? cellName
let nib = UINib(nibName: cellName, bundle: nil)
register(nib, forCellWithReuseIdentifier: identifier)
}
}
<file_sep>/TVShows/Modules/Login/LoginWireframe.swift
//
// LoginWireframe.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import RxSwift
import RxCocoa
final class LoginWireframe: BaseWireframe {
// MARK: - Private properties -
private let storyboard = UIStoryboard(name: "Login", bundle: nil)
// MARK: - Module setup -
init() {
let moduleViewController = storyboard.instantiateViewController(ofType: LoginViewController.self)
super.init(viewController: moduleViewController)
let interactor = LoginInteractor()
let presenter = LoginPresenter(view: moduleViewController, interactor: interactor, wireframe: self)
moduleViewController.presenter = presenter
}
}
// MARK: - Extensions -
extension LoginWireframe: LoginWireframeInterface {
func navigate(using option: Driver<Login.NavigationOption>) {
subscribe(to: option, unowning: self, navigationBlock: LoginWireframe.navigate(to: ))
}
func navigate(to option: Login.NavigationOption) {
switch option {
case .home:
navigationController?.pushWireframe(HomeWireframe())
}
}
}
<file_sep>/TVShows/Common/UI/CellsAndItems/Basic/DataSourceDelegates/CollectionDataSourceDelegate.swift
//
// CollectionDataSourceDelegate.swift
//
//
import UIKit
import RxSwift
class EmptyCollectionSection: CollectionSectionItem {
var collectionItems: [CollectionCellItem]
init(collectionItems: [CollectionCellItem]) {
self.collectionItems = collectionItems
}
convenience init?(collectionItems: [CollectionCellItem]?) {
if let item = collectionItems {
self.init(collectionItems: item)
return
}
return nil
}
}
class CollectionDataSourceDelegate: NSObject {
private let collectionView: UICollectionView
private let reloader: CollectionViewReloader
private let disposeBag = DisposeBag()
var sections: [CollectionSectionItem]? {
didSet { reloader.reload(collectionView, oldSections: oldValue, newSections: sections) }
}
var items: [CollectionCellItem]? {
get { return sections?.map({ $0.collectionItems }).reduce([CollectionCellItem](), +) }
set {
guard let tableItems = newValue else { return }
sections = [EmptyCollectionSection(collectionItems: tableItems) as CollectionSectionItem]
}
}
init(collectionView: UICollectionView, reloader: CollectionViewReloader = DefaultCollectionViewReloader()) {
self.collectionView = collectionView
self.reloader = reloader
super.init()
collectionView.dataSource = self
collectionView.rx
.setDelegate(self)
.disposed(by: disposeBag)
}
}
extension CollectionDataSourceDelegate: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return sections?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sections?[section].collectionItems.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return sections![indexPath].cell(from: collectionView, at: indexPath)
}
}
extension CollectionDataSourceDelegate: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
sections![indexPath].didSelect(at: indexPath)
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
sections![indexPath].willDisplay(cell: cell, at: indexPath)
}
}
extension CollectionDataSourceDelegate: UIScrollViewDelegate {
}
<file_sep>/TVShows/Common/UI/CellsAndItems/Basic/Protocols/CellItem.swift
//
// CellItem.swift
//
//
import UIKit
protocol CellItem {
}
protocol TableCellItem: CellItem {
//Required
func cell(from tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell
//Optional
var height: CGFloat { get }
var estimatedHeight: CGFloat { get }
func didSelect(at indexPath: IndexPath)
}
protocol CollectionCellItem: CellItem {
//Required
func cell(from collectionView: UICollectionView, at indexPath: IndexPath) -> UICollectionViewCell
//Optional
func sizeWithCollectionView(size: CGSize, numOfImtemsInSection: Int) -> CGSize
func willDisplay(cell: UICollectionViewCell, at indexPath: IndexPath)
func didSelect(at indexPath: IndexPath)
}
extension TableCellItem {
var height: CGFloat {
return UITableView.automaticDimension
}
var estimatedHeight: CGFloat {
return 44
}
func didSelect(at indexPath: IndexPath) {
//pass
}
}
extension CollectionCellItem {
func sizeWithCollectionView(size: CGSize, numOfImtemsInSection: Int) -> CGSize {
return UICollectionViewFlowLayout.automaticSize
}
func willDisplay(cell: UICollectionViewCell, at indexPath: IndexPath) {
//pass
}
func didSelect(at indexPath: IndexPath) {
//pass
}
}
<file_sep>/TVShows/Modules/Login_StandardVIPER_NonRx/LoginSWireframe.swift
//
// LoginSWireframe.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
final class LoginSWireframe: BaseWireframe {
// MARK: - Private properties -
private let _storyboard = UIStoryboard(name: "LoginS", bundle: nil)
// MARK: - Module setup -
init() {
let moduleViewController = _storyboard.instantiateViewController(ofType: LoginSViewController.self)
super.init(viewController: moduleViewController)
let interactor = LoginSInteractor()
let presenter = LoginSPresenter(wireframe: self, view: moduleViewController, interactor: interactor)
moduleViewController.presenter = presenter
}
}
// MARK: - Extensions -
extension LoginSWireframe: LoginSWireframeInterface {
func navigate(to option: LoginSNavigationOption) {
switch option {
case .home:
navigationController?.pushWireframe(HomeWireframe())
}
}
}
<file_sep>/TVShows/Common/Networking/Routers/Router.swift
//
// Router.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import Alamofire
struct Router: URLRequestConvertible {
private static let base = Constants.URL.baseUrl
private let base: String
private let path: String
private let method: HTTPMethod
private let params: Parameters?
private let headers: HTTPHeaders?
private let encoding: ParameterEncoding
private init(base: String, path: String, method: HTTPMethod, params: Parameters?, headers: HTTPHeaders?, encoding: ParameterEncoding) {
self.base = base
self.path = path
self.method = method
self.params = params
self.headers = headers
self.encoding = encoding
}
init(path: String, method: HTTPMethod = .get, params: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil) {
self.init(base: Router.base,
path: path, method: method,
params: params,
headers: headers,
encoding: encoding)
}
private func pathURL() throws -> URL {
if path.starts(with: "http") {
return try path.asURL()
}
return try base.asURL()
.appendingPathComponent(path)
}
func asURLRequest() throws -> URLRequest {
let url = try pathURL()
let originalRequest = try URLRequest(url: url, method: method, headers: headers)
return try encoding.encode(originalRequest, with: params)
}
}
<file_sep>/TVShows/Common/Extensions/UI/UIColor+AppColors.swift
//
// UIColor+AppColors.swift
// TVShows
//
// Created by <NAME> on 28/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
extension UIColor {
enum TVShows {
static var gray = UIColor(rgbHex: 0x505050)
static var pink = UIColor(rgbHex: 0xFF758C)
}
}
<file_sep>/TVShows/Modules/ShowDetails/ShowDetailsWireframe.swift
//
// ShowDetailsWireframe.swift
// TVShows
//
// Created by <NAME> on 30/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import RxSwift
import RxCocoa
final class ShowDetailsWireframe: BaseWireframe {
// MARK: - Private properties -
private let storyboard = UIStoryboard(name: "ShowDetails", bundle: nil)
// MARK: - Module setup -
init(showId: String) {
let moduleViewController = storyboard.instantiateViewController(ofType: ShowDetailsViewController.self)
super.init(viewController: moduleViewController)
let interactor = ShowDetailsInteractor(showId: showId)
let presenter = ShowDetailsPresenter(view: moduleViewController, interactor: interactor, wireframe: self)
moduleViewController.presenter = presenter
}
}
// MARK: - Extensions -
extension ShowDetailsWireframe: ShowDetailsWireframeInterface {
func navigate(to option: ShowDetailsNavigationOption) {
}
}
<file_sep>/TVShows/Modules/Login_StandardVIPER_NonRx/LoginSViewController.swift
//
// LoginSViewController.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
final class LoginSViewController: UIViewController {
// MARK: - Private properties -
// MARK: - IBOutlets
@IBOutlet private weak var _scrollView: UIScrollView!
@IBOutlet private weak var _loginButton: UIButton!
@IBOutlet private weak var _registerButton: UIButton!
@IBOutlet private weak var _checkmarkButton: UIButton!
@IBOutlet private weak var _emailField: UITextField!
@IBOutlet private weak var _passwordField: UITextField!
// MARK: - Public properties -
var presenter: LoginSPresenterInterface!
// MARK: - Public methods -
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
_setupUI()
_setupKeyboardObservers()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
// MARK: - Private methods -
// MARK: - UI Setup
private func _setupUI() {
_loginButton.layer.cornerRadius = 6.0
_loginButton.setBackgroundImage(.from(color: UIColor.TVShows.pink), for: .normal)
_loginButton.setBackgroundImage(.from(color: UIColor.TVShows.pink.withAlphaComponent(0.5)),
for: .disabled)
}
}
// MARK: - Extensions -
extension LoginSViewController: LoginSViewInterface {
}
// MARK: - IBActions
private extension LoginSViewController {
@IBAction func _checkmarkButtonActionHandler() {
_checkmarkButton.isSelected = !_checkmarkButton.isSelected
}
@IBAction private func _loginButtonActionHandler() {
guard
let email = _emailField.text,
let password = _passwordField.text,
!email.isEmpty, !password.isEmpty
else {
return
}
view.endEditing(true)
presenter.didSelectLoginWith(email: email, password: <PASSWORD>)
}
@IBAction private func _registerButtonActionHandler() {
guard
let email = _emailField.text,
let password = _passwordField.text,
!email.isEmpty, !password.isEmpty
else {
return
}
view.endEditing(true)
presenter.didSelectRegisterWith(email: email, password: password)
}
}
// MARK: UITextFieldDelegate
extension LoginSViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
view.endEditing(true)
return true
}
}
// MARK: - Keyboard handling
private extension LoginSViewController {
private func _setupKeyboardObservers() {
NotificationCenter.default.addObserver(self,
selector: #selector(_keyboardWillShow(_:)),
name: UIResponder.keyboardWillShowNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(_keyboardWillHide(_:)),
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
@objc func _keyboardWillShow(_ notification: Notification) {
guard
let userInfo = notification.userInfo,
let keyboardSize = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
else { return }
_scrollView.contentInset.bottom = keyboardSize.size.height
}
@objc func _keyboardWillHide(_ notification: Notification) {
_scrollView.contentInset = .zero
}
}
<file_sep>/TVShows/Common/Base VIPER/Progressable.swift
//
// Progressable.swift
// TVShows
//
// Created by <NAME> on 28/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import PKHUD
protocol Progressable: class {
func showLoading()
func showLoadingInView()
func hideLoading()
func hideLoadingInView()
func showSuccess()
func showFailure(with error: Error)
}
protocol Refreshable {
var refreshControl: UIRefreshControl { get }
}
extension Refreshable {
func endRefreshing() {
refreshControl.endRefreshing()
}
}
extension Progressable where Self: WireframeInterface {
func showLoading() {
guard shouldShowSpinner() else { return }
PKHUD.sharedHUD.dimsBackground = false
HUD.show(.progress)
}
func showLoadingInView() {
guard shouldShowSpinner() else { return }
PKHUD.sharedHUD.contentView = PKHUDProgressView()
PKHUD.sharedHUD.dimsBackground = false
PKHUD.sharedHUD.show(onView: viewController.view)
}
func hideLoading() {
(viewController as? Refreshable)?.endRefreshing()
HUD.hide()
}
func hideLoadingInView() {
(viewController as? Refreshable)?.endRefreshing()
HUD.hide()
}
func showSuccess() {
HUD.flash(.success, delay: 0.7)
}
func showFailure(with error: Error) {
log.error((error as CustomDebugStringConvertible).debugDescription)
let alertView = UIAlertController(title: nil, message: error.localizedDescription, preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
viewController.present(alertView, animated: true, completion: nil)
}
private func shouldShowSpinner() -> Bool {
if
let refreshable = viewController as? Refreshable,
refreshable.refreshControl.isRefreshing
{
return false
}
return true
}
}
<file_sep>/TVShows/Modules/Login/LoginInteractor.swift
//
// LoginInteractor.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import Foundation
import Alamofire
import RxSwift
final class LoginInteractor {
private let _service: Service
private let _sessionManager: SessionManager
init(service: Service = .instance, sessionManager: SessionManager = ShowsSessionManager.session) {
_service = service
_sessionManager = sessionManager
}
}
// MARK: - Extensions -
extension LoginInteractor: LoginInteractorInterface {
func loginWith(email: String, password: String) -> Single<Void> {
let service = _service
let sessionManager = _sessionManager
return Single.just(())
.map { Router.User.loginWith(email: email, password: <PASSWORD>) }
.flatMap { service.request(LoginData.self, router: $0) }
.do(onSuccess: { sessionManager.adapter = TokenAdapter(token: $0.token) })
.mapToVoid()
}
func registerWith(email: String, password: String) -> Single<Void> {
let service = _service
return Single.just(())
.map { Router.User.registerWith(email: email, password: <PASSWORD>) }
.flatMap { service.request(User.self, router: $0) }
.mapToVoid()
}
}
<file_sep>/TVShows/Application/Initializers/LoggingInitializer.swift
//
// LoggingInitializer.swift
// TVShows
//
// Created by <NAME> on 28/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import SwiftyBeaver
let log = SwiftyBeaver.self
class LoggingInitializer: Initializable {
func initialize() {
let console = ConsoleDestination()
#if DEBUG
log.addDestination(console)
#endif
}
}
<file_sep>/TVShows/Common/Base VIPER/BaseWireframe.swift
import UIKit
import RxSwift
import RxCocoa
protocol WireframeInterface: Progressable {
var viewController: UIViewController { get }
func open(url: URL)
func open(stringUrl: String)
func dismiss()
func exit()
func pop()
}
class BaseWireframe {
let disposeBag = DisposeBag()
private unowned var _viewController: UIViewController
// To retain view controller reference upon first access
private var _temporaryStoredViewController: UIViewController?
init(viewController: UIViewController) {
_temporaryStoredViewController = viewController
_viewController = viewController
}
}
extension BaseWireframe: WireframeInterface {
func open(url: URL) {
UIApplication.shared.open(url)
}
func open(stringUrl: String) {
guard let url = URL(string: stringUrl) else { return }
open(url: url)
}
func dismiss() {
viewController.dismiss(animated: true)
}
func pop() {
navigationController?.popViewController(animated: true)
}
func exit() {
guard let navigationController = navigationController else {
dismiss()
return
}
if navigationController.viewControllers.count > 1 {
pop()
} else {
dismiss()
}
}
}
extension BaseWireframe {
var viewController: UIViewController {
defer { _temporaryStoredViewController = nil }
return _viewController
}
var navigationController: UINavigationController? {
return viewController.navigationController
}
}
extension BaseWireframe {
func subscribe<W: BaseWireframe, T>(to navigationOptionDriver: Driver<T>, unowning object: W, navigationBlock: @escaping (W) -> ((T) -> ())) {
navigationOptionDriver
.drive(onNext: { [unowned object] in navigationBlock(object)($0) })
.disposed(by: disposeBag)
}
}
extension UIViewController {
func presentWireframe(_ wireframe: BaseWireframe, animated: Bool = true, completion: (()->())? = nil) {
present(wireframe.viewController, animated: animated, completion: completion)
}
}
extension UINavigationController {
func pushWireframe(_ wireframe: BaseWireframe, animated: Bool = true) {
pushViewController(wireframe.viewController, animated: animated)
}
func setRootWireframe(_ wireframe: BaseWireframe, animated: Bool = true) {
setViewControllers([wireframe.viewController], animated: animated)
}
}
<file_sep>/TVShows/Modules/Home/HomePresenter.swift
//
// HomePresenter.swift
// TVShows
//
// Created by <NAME> on 29/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
import RxSwift
import RxCocoa
final class HomePresenter {
// MARK: - Private properties -
private unowned let view: HomeViewInterface
private let interactor: HomeInteractorInterface
private let wireframe: HomeWireframeInterface
private let _disposeBag = DisposeBag()
// MARK: - Lifecycle -
init(view: HomeViewInterface, interactor: HomeInteractorInterface, wireframe: HomeWireframeInterface) {
self.view = view
self.interactor = interactor
self.wireframe = wireframe
}
}
// MARK: - Extensions -
extension HomePresenter: HomePresenterInterface {
func setup(with output: Home.ViewOutput) -> Home.ViewInput {
output
.logoutPressed
.drive(onNext: { [unowned wireframe] in
wireframe.pop()
})
.disposed(by: _disposeBag)
let items = interactor
.loadShows()
.handleLoadingAndError(with: wireframe)
.map { [unowned self] shows -> [CollectionCellItem] in
return self.setupItems(shows)
}
.asDriverOnErrorComplete()
let itemsReloader = output
.refresh
.startWith(()) // Manually invoke call at start
.flatMapLatest { items }
return Home.ViewInput(items: itemsReloader)
}
}
private extension HomePresenter {
func setupItems(_ shows: [Show]) -> [CollectionCellItem] {
let items = shows.map { show -> ShowCollectionCellItem in
var imageUrl: URL? = nil
if let imageId = show.imageUrl {
imageUrl = URL(string: "https://api.infinum.academy" + imageId)
}
let item = ShowCollectionCellItem(title: show.title, imageUrl: imageUrl) { [unowned wireframe] in
wireframe.navigate(to: .showDetails(showId: show.id))
}
return item
}
return items
}
}
<file_sep>/TVShows/Common/Networking/Models/User.swift
//
// User.swift
// TVShows
//
// Created by <NAME> on 11/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
struct User: Codable { /* typealias Codable = Encodable & Decodable */
let email: String
let type: String
let id: String
enum CodingKeys: String, CodingKey {
case email
case type
case id = "_id"
}
}
struct LoginData: Codable {
let token: String
}
<file_sep>/TVShows/Modules/ShowDetails/ShowDetailsInteractor.swift
//
// ShowDetailsInteractor.swift
// TVShows
//
// Created by <NAME> on 30/07/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import Foundation
import Alamofire
import RxSwift
final class ShowDetailsInteractor {
private let _service: Service
private let _sessionManager: SessionManager
init(showId: String, service: Service = .instance, sessionManager: SessionManager = ShowsSessionManager.session) {
_service = service
_sessionManager = sessionManager
}
}
// MARK: - Extensions -
extension ShowDetailsInteractor: ShowDetailsInteractorInterface {
}
<file_sep>/TVShows/Common/UI/CellsAndItems/Common/DataSourceDelegate/AnimatedSelectionCollectionDataSourceDelegate.swift
//
// AnimatedCollectionViewDataSourceDelegate.swift
//
import UIKit
import RxSwift
class AnimatedSelectionCollectionDataSourceDelegate: CollectionDataSourceDelegate {
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) else { return }
UIView.animate(withDuration: 0.1) {
cell.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
}
}
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) else { return }
UIView.animate(withDuration: 0.1) {
cell.transform = .identity
}
}
}
<file_sep>/TVShows/Common/Networking/Models/Episode.swift
//
// Episode.swift
// TVShows
//
// Created by <NAME> on 24/07/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
struct Episode: Codable {
let showId: String
let mediaId: String?
let title: String
let description: String
let episodeNumber: String
let season: String
let type: String
let imageUrl: String?
let id: String
enum CodingKeys: String, CodingKey {
case showId
case mediaId
case title
case description
case episodeNumber
case season
case type
case imageUrl
case id = "_id"
}
}
<file_sep>/TVShows/Common/UI/CellsAndItems/Common/DataSourceDelegate/IndexTitleTableDataSourceDelegate.swift
//
// IndexTitleTableDataSourceDelegate.swift
//
//
import UIKit
protocol IndexTitleTableSectionItem {
var title: String { get }
}
class IndexTitleTableDataSourceDelegate: TableDataSourceDelegate {
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
let sections = self.sections?.compactMap { $0 as? IndexTitleTableSectionItem }
if sections?.count != self.sections?.count { return nil }
return sections?.map { $0.title }
}
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
let sections = self.sections?.map { $0 as? IndexTitleTableSectionItem }
let index = sections?.firstIndex { title == $0?.title }
return index ?? 0
}
}
| fe6ab54910c4a242be9fbf4aa86f809e1aa690ae | [
"Swift",
"Ruby",
"Markdown"
] | 57 | Swift | fgulan/ios-infinum-academy-2019 | 15c99d794921afdf87634097c6b1293f92e5bd4f | 3ee2da60fdee4b56b43f3cb4539573576e4040c3 | |
refs/heads/master | <file_sep>template <class T>
class stackmin
{
class Node
{
private:
T data;
public:
Node(T t)
{
data = t;
}
T GetData()
{
return data;
}
Node* next;
};
private:
Node* top;
Node* min;
public:
stackmin()
{
top = nullptr;
min = nullptr;
}
void push(T t)
{
Node* p = new Node(t);
if (p == nullptr)
throw "No memory!";
p->next = top;
top = p;
if (min == nullptr || t < min->GetData())
min = p;
}
T pop()
{
if (top == nullptr)
throw "empty stack";
T tmp = top->GetData();
Node* tmpptr = top;
top = top->next;
if (min == tmpptr)
{ // we need to iterate through the list to find the min
min = FindMin();
}
delete tmpptr;
return tmp;
}
T getMin()
{
if (min == nullptr)
throw "empty stack";
return min->GetData ();
}
Node* FindMin()
{
Node* pMin = top;
Node* tmp = top;
while (tmp != nullptr)
{
if (tmp->GetData() >= pMin->GetData())
{
tmp = tmp->next;
}
else
{
pMin = tmp;
}
}
return pMin;
}
};<file_sep>#include "stackmin.h"
#include <iostream>
#include <cassert>
const int testConst = 100;
void main()
{
stackmin<int> testStack;
for (int i = 0; i < testConst; ++i)
testStack.push(i);
assert (testStack.getMin() == 0);
for (int i = testConst-1; i >=0; --i)
assert (testStack.pop() == i);
for (int i = 0; i < testConst; ++i)
testStack.push(testConst - i);
for (int i = 1; i < testConst; ++i)
{
assert(testStack.getMin() == i);
assert(testStack.pop() == i);
}
std::cout << "End" << std::endl;
}<file_sep>#include <deque>
#include <vector>
class Animal
{
public:
virtual void hello() {};
};
class Dog : public Animal {};
class Cat : public Animal {};
template <class U>
class Shelter
{
private:
std::deque<U*> m_animalQueue;
public:
void enqueue(U* p)
{
m_animalQueue.push_back(p);
}
U* dequeueAny()
{
if (m_animalQueue.empty())
return nullptr;
U* p = m_animalQueue.front();
m_animalQueue.pop_front();
return p;
}
template <class T> T* dequeue()
{
std::vector<U*> vTmp;
T* pFound = nullptr;
while (!m_animalQueue.empty())
{
Animal* pAnimal = dequeueAny();
if (dynamic_cast<T*> (pAnimal) != nullptr)
{
pFound = static_cast<T*> (pAnimal);
break;
}
else
vTmp.push_back(pAnimal);
}
for (auto& it = vTmp.rbegin(); it != vTmp.rend(); ++it)
{
m_animalQueue.push_front(*it);
}
return pFound;
}
};
<file_sep>#include "AnimalShelter.h"
void Shelter::enqueue(Animal* p)
{
m_animalQueue.push_back(p);
}
Animal* Shelter::dequeueAny()
{
if (m_animalQueue.empty())
return nullptr;
Animal* p = m_animalQueue.front();
m_animalQueue.pop_front();
return p;
}
<file_sep>#include <stack>
#include <cassert>
#include <iostream>
void sort(std::stack<int>& st)
{
std::stack<int> tmpStack;
while (!st.empty())
{
int nTmp = st.top();
st.pop();
while (!tmpStack.empty () && tmpStack.top() > nTmp)
{
int n = tmpStack.top();
tmpStack.pop();
st.push(n);
}
tmpStack.push(nTmp);
}
while (!tmpStack.empty())
{
int n = tmpStack.top();
tmpStack.pop();
st.push(n);
}
}
void main()
{
std::stack<int> stack;
stack.push(100);
stack.push(101);
stack.push(99);
stack.push(88);
stack.push(200);
sort(stack);
assert(stack.top() == 88);
stack.pop();
assert(stack.top() == 99);
stack.pop();
assert(stack.top() == 100);
stack.pop();
assert(stack.top() == 101);
stack.pop();
assert(stack.top() == 200);
stack.pop();
std::cout << "End!" << std::endl;
}<file_sep>#pragma once
#include <vector>
#include <stack>
template <class T,std::size_t N>
class StackPlate
{
private: std::vector <std::stack<T>> m_vPlates;
public:
void push(T t)
{
if (m_vPlates.empty())
{
std::stack<T> mystack;
mystack.push(t);
m_vPlates.push_back(mystack);
}
else
{
std::stack<T>& currentStack = m_vPlates[m_vPlates.size() - 1];
if (currentStack.size() == N)
{
std::stack<T> mystack;
mystack.push(t);
m_vPlates.push_back(mystack);
}
else
{
currentStack.push(t);
}
}
}
T pop()
{
if (m_vPlates.empty())
{
throw "Empty stack!";
}
else
{
std::stack<T>& currentStack = m_vPlates[m_vPlates.size() - 1];
T t = currentStack.top();
currentStack.pop();
if (currentStack.empty())
m_vPlates.pop_back();
return t;
}
}
T popAt(int index)
{
if (m_vPlates.size() < index)
throw "No such index!";
std::stack<T>& currentStack = m_vPlates[index];
T t = currentStack.top();
currentStack.pop();
if (currentStack.empty())
m_vPlates.erase(m_vPlates.begin() + index);
return t;
}
int numOfStack()
{
return m_vPlates.size();
}
};
<file_sep>#include "AnimalShelter.h"
#include <iostream>
void main()
{
Shelter<Animal> TheShelter;
Dog one;
Dog a;
Cat b;
Dog c;
Dog d;
TheShelter.enqueue(&one);
TheShelter.enqueue(&a);
TheShelter.enqueue(&b);
TheShelter.enqueue(&c);
TheShelter.enqueue(&d);
Cat* p = TheShelter.dequeue<Cat>();
if (p == &b)
{
std::cout << "Great!" << std::endl;
}
else
{
std::cout << "OOPS!" << std::endl;
}
Dog* pDog = TheShelter.dequeue<Dog>();
if (pDog == &one)
{
std::cout << "Great!" << std::endl;
}
std::cout << "End!" << std::endl;
}<file_sep>#include "StackPlate.h"
#include <iostream>
#include <cassert>
void main()
{
StackPlate<int, 2> plate;
for (int i = 0; i < 100; ++i)
{
plate.push(i);
}
assert(plate.numOfStack() == 50);
assert(plate.pop() == 99);
assert(plate.numOfStack() == 50);
assert(plate.pop() == 98);
assert(plate.numOfStack() == 49);
assert(plate.pop() == 97);
assert(plate.numOfStack() == 49);
assert(plate.popAt(0) == 1);
assert(plate.numOfStack() == 49);
std::cout << "Test" << std::endl;
}<file_sep>// testrange.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <algorithm>
template <class T>
class num_iterator
{
T i;
public:
explicit num_iterator(T position = 0) : i{ position } {}
T operator*() const { return i; }
num_iterator& operator++()
{
++i;
return *this;
}
bool operator!=(const num_iterator &other) const
{
return i != other.i;
}
bool operator==(const num_iterator &other) const { return !(*this != other); }
};
template <class T>
class num_range
{
T a;
T b;
public:
num_range(T from, T to)
: a{ from }, b{ to }
{}
num_iterator<T> begin() const { return num_iterator<T>{ a }; }
num_iterator<T> end() const { return num_iterator<T>{ b }; }
};
namespace std
{
template <class T>
struct iterator_traits<num_iterator<T>>
{
using iterator_category = std::forward_iterator_tag;
using value_type = T;
using difference_type = T;
};
}
int main()
{
auto x = num_range<long long> { 1, 100000 };
long long goal = 10000;
auto it = std::lower_bound(std::begin(x), std::end(x), goal, [](const auto& item,const long long& goal) {
auto result = item * item;
return result < goal;
});
std::cout << *it << std::endl;
}
<file_sep>#include "stdafx.h"
#include <optional>
#include <vector>
#include <utility>
#include <array>
#include <string>
#include <iostream>
#include <cassert>
template <class T, int DefaultSize = 1024>
class SampleQueue
{
public:
SampleQueue(): tailIndex (0),headIndex (0)
{
}
bool push (const T& val)
{
if (isFull())
return false;
else
{
vStorage[tailIndex++] = val;
return true;
}
}
std::optional<T> pop()
{
if (isEmpty())
return std::nullopt;
else
{
auto item = vStorage[headIndex];
headIndex ++;
return item;
}
}
std::optional<T> top()
{
if (isEmpty())
return std::nullopt;
else
return vStorage[headIndex];
}
unsigned int size()
{
if (tailIndex > headIndex)
return tailIndex - headIndex;
else
return tailIndex - headIndex + DefaultSize;
}
bool isEmpty()
{
return headIndex == tailIndex;
}
bool isFull()
{
return tailIndex == headIndex - 1;
}
private:
std::array<T,DefaultSize> vStorage;
int headIndex;
int tailIndex;
};
int main()
{
SampleQueue <std::string> stringQ;
std::string s1 = "This is a hash table for testing!";
std::string s2 = "another test";
std::string s3 = "latest test";
stringQ.push(s1);
stringQ.push(s2);
stringQ.push(s3);
assert(stringQ.size() == 3);
assert(stringQ.top() == s1);
assert(stringQ.size() == 3);
assert(stringQ.pop() == s1);
assert(stringQ.size() == 2);
stringQ.pop();
stringQ.pop();
assert(stringQ.pop() == std::nullopt);
return 0;
}
<file_sep>#include "stdafx.h"
#include <optional>
#include <vector>
#include <utility>
#include <array>
#include <string>
#include <iostream>
#include <cassert>
template <class T>
class SampleStack
{
public:
SampleStack()
{
vStorage.reserve(1024);
}
void push(const T& val)
{
vStorage.push_back(val);
}
std::optional<T> pop()
{
if (isEmpty())
return std::nullopt;
else
{
auto item = vStorage[vStorage.size() -1];
vStorage.pop_back();
return item;
}
}
std::optional<T> top()
{
if (isEmpty())
return std::nullopt;
else
return vStorage[vStorage.size() - 1];
}
unsigned int size()
{
return vStorage.size();
}
bool isEmpty()
{
return vStorage.size() == 0;
}
private:
std::vector<T> vStorage;
};
int main()
{
SampleStack <std::string> stringQ;
std::string s1 = "This is a hash table for testing!";
std::string s2 = "another test";
std::string s3 = "latest test";
stringQ.push(s1);
stringQ.push(s2);
stringQ.push(s3);
assert(stringQ.size() == 3);
assert(stringQ.top() == s3);
assert(stringQ.size() == 3);
assert(stringQ.pop() == s3);
assert(stringQ.size() == 2);
stringQ.pop();
stringQ.pop();
assert(stringQ.pop() == std::nullopt);
return 0;
}
<file_sep>#include "stdafx.h"
#include <optional>
#include <vector>
#include <utility>
#include <array>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
template <class T, class Compare>
class SamplePQueue
{
public:
SamplePQueue()
{
vStorage.reserve(1024);
}
SamplePQueue(const std::vector<T>& q)
{
vStorage = q;
std::make_heap(vStorage.begin(), vStorage.end());
}
void push(const T& val)
{
vStorage.push_back(val);
std::push_heap(vStorage.begin(), vStorage.end(), func);
}
std::optional<T> pop()
{
if (isEmpty())
return std::nullopt;
else
{
std::pop_heap(vStorage.begin(), vStorage.end(),func);
auto item = vStorage.back();
vStorage.pop_back();
return item;
}
}
std::optional<T> top()
{
if (isEmpty())
return std::nullopt;
else
return vStorage.front();
}
unsigned int size()
{
return vStorage.size();
}
bool isEmpty()
{
return vStorage.size() == 0;
}
private:
std::vector<T> vStorage;
Compare func;
};
template<class T>
struct SampleLess
{
bool operator()(const T& a, const T& b)
{
if (a.size() > b.size())
return true;
else
return false;
}
};
int main()
{
//auto anotherLess = [](const std::string& a, const std::string& b)
//{
// if (a.length() > b.length())
// return true;
// else
// return false;
//};
SamplePQueue <std::string, SampleLess<std::string>> stringQ;
std::string s1 = "This is a hash table for testing!";
std::string s2 = "I am the third";
std::string s3 = "first";
std::string s4 = "The second";
stringQ.push(s1);
stringQ.push(s2);
stringQ.push(s3);
stringQ.push(s4);
assert(stringQ.size() == 4);
assert(stringQ.top() == s3);
assert(stringQ.size() == 4);
assert(stringQ.pop() == s3);
assert(stringQ.size() == 3);
assert(stringQ.pop() == s4);
assert(stringQ.pop() == s2);
assert(stringQ.pop() == s1);
assert(stringQ.pop() == std::nullopt);
std::vector<std::string> vTest;
vTest.push_back(s1);
vTest.push_back(s2);
vTest.push_back(s3);
vTest.push_back(s4);
SamplePQueue <std::string, SampleLess<std::string>> Q2(vTest);
assert(Q2.top() == s3);
return 0;
}
| 58c050c55ef0a04e58aef892ca4eb5ab33e81493 | [
"C++"
] | 12 | C++ | zhiweicai/new_repo | e9a00d6820ba7fee3dfd632f8153611e6f9257bc | b3d0b811377d69aa1a8f22038f4995307e05b037 | |
refs/heads/main | <repo_name>anibalsilva1/ACO-TSP<file_sep>/ACO_TSP/aux_functions.py
import numpy as np
def transition_prob(pheromones,alpha,beta,city_i,city_j,tabu_list,points):
allowed_cities = tabu_list
numerator = (visibility(city_i,city_j,points))**beta * (pheromones[city_i,city_j]) ** alpha
denominator = np.sum([pheromones[city_i,city_k]**alpha * visibility(city_i,city_k,points)**beta for city_k in allowed_cities])
return numerator/denominator
def length(tabu_list,points):
cities = tabu_list
n_cities = len(cities)
if n_cities <= 1:
return 0
else:
i = 0
dist = 0
while i < n_cities-1:
dist += distance(cities[i],cities[i+1],points)
i +=1
return dist
def distance(city_i,city_j,points):
return np.sqrt((points[city_i][1]-points[city_j][1])**2 + (points[city_i][2]-points[city_j][2])**2)
def visibility(city_i,city_j,points):
return 1/distance(city_i,city_j,points)
def ant_pheromone(Q,tabu_list,points):
cities = tabu_list
return Q / length(cities,points)<file_sep>/ACO_TSP/main.py
import numpy as np
import pandas as pd
import random
#from aux_functions import *
from plot import plot_path
from aux_functions import transition_prob,length,visibility,ant_pheromone,distance
df = pd.read_csv("data/chn31.csv",header=None,delimiter=" ",names=["city","x","y"])
#Reshape city index and convert to numpy array
df["city"] = df["city"] - 1
points = np.array(df)
#print(points)
def main():
'''
:param alpha: relative importance of trail
:param beta: relative importance of visibility
:param rho: trail evaporation
:param Q: visibility constant
:param NMAX: number of tours over all the cities (AKA ant generations)
'''
ncity = points.shape[0]
n_ants = ncity
shortest_tour = []
ants = np.arange(0,n_ants)
tabu_list = [[] for _ in range(len(ants))]
pheromones = np.full([ncity,ncity],0.0001)
## Parameters
Q = 1
rho = 0.2
alpha = .8
beta = 0.7
max_error = 0.05
NMAX = 50
delta_pheromones = np.zeros([ncity,ncity])
NC = 0
while NC < NMAX:
print("Going through the cycle: ", NC)
allowed_cities = []
cities = points[:,0]
[tabu.append(random.randint(0,ncity-1)) for tabu in tabu_list]
for ant in ants:
start_city = tabu_list[ant][0]
tabu_list_size = len(tabu_list[ant])
while tabu_list_size < ncity:
'''
Choose the town to transit to: calculate the transition probability for
each pair and select the one where the probability is highest
'''
current_city = tabu_list[ant][tabu_list_size-1]
allowed_cities = [city for city in cities if city not in tabu_list[ant]]
probs = [(transition_prob(pheromones,alpha,beta,current_city,city_j,allowed_cities,points),city_j) for city_j in allowed_cities] # Returns a tuple with all the
#print(probs)
next_city = max(probs,key=lambda item:item[0])[1]
tabu_list[ant].append(next_city)
tabu_list_size += 1
tabu_list[ant].append(start_city) # Finally place the ant in the initial city
tot_dist = [(length(tabu_list[ant],points),ant) for ant in ants]
best_ant_per_cycle = min(tot_dist, key = lambda t: t[0])[1]
best_path_per_cycle = tabu_list[best_ant_per_cycle]
shortest_tour.append([best_ant_per_cycle,length(best_path_per_cycle,points),best_path_per_cycle])
print("\t Shortest tour in cycle :", NC ," was done by ant", best_ant_per_cycle, "with a tour of ", shortest_tour[NC][1], "and a path \n\t", shortest_tour[NC][2], "\n")
error = (shortest_tour[NC][1] - shortest_tour[NC-1][1])/shortest_tour[NC][1]
print(error)
if error > max_error:
'''
Stagnation behavior: if the last tour is worse than
the previous one times an error factor epsilon,
we stop the search.
'''
print("The last run had a tour of length ",shortest_tour[NC][1], "which is higher than the previous one: ",shortest_tour[NC-1][1], "so we are stopping")
print("Plotting best path...")
plot_path(points,shortest_tour[NC-1][2])
break
else:
#### UPDATES BEGIN ####
for ant in ants:
cities = tabu_list[ant]
for city in range(len(cities)-1):
delta_pheromones[cities[city],cities[city+1]] = ant_pheromone(Q,cities,points)
pheromones = rho*pheromones + delta_pheromones
#### UPDATES END ####
if NC == NMAX - 1:
print("Plotting best path...")
plot_path(points,best_path_per_cycle)
#print(best_path_per_cycle)
delta_pheromones = np.zeros([ncity,ncity])
[tabu.clear() for tabu in tabu_list]
NC +=1
#print(shortest_tour)
#print("Plotting best path...")
#plot_path(points,best_path_per_cycle)
if __name__ == '__main__':
main()
<file_sep>/README.md
# ACO-TSP
Author: <NAME>
The logic behind the main.py was followed by the original article:
https://ieeexplore.ieee.org/document/484436
NOTE: Stagnation behavior is defined in a different fashion from the paper: In here, it was defined an error,
which is the difference between the best tour in the iteration **NC** and **NC-1** divided by the best tour in
iteration **NC** in order to normalize the error between [0,1].
The best path is then controlled by the parameter **max_error** between iterations, i.e., above
this threshold we stop searching for more paths.
*How to run the code:* python main.py in a terminal.
<file_sep>/ACO_TSP/plot.py
import matplotlib.pyplot as plt
def plot_path(points,cities):
city_x = points[:,1]
city_y = points[:,2]
# Reshape the coordinates with the repective ordered tour
city_x = city_x[cities]
city_y = city_y[cities]
plt.scatter(city_x,city_y)
plt.plot(city_x,city_y,"-o")
for x,y,city in zip(city_x,city_y,cities):
label = "{}".format(city)
plt.annotate(label,(x,y), ha="center",textcoords="offset points",xytext=(0,10))
plt.show() | 848ab7f394f329f4230d41472d0e7c881e89e9ba | [
"Markdown",
"Python"
] | 4 | Python | anibalsilva1/ACO-TSP | 4df2bd81bb4fbde432b520a291e66e11dc219e7e | 43ae7e589555000f355d604ea1fe2252691fa1ca | |
refs/heads/master | <repo_name>awi2017-option1group1/Prello-auth<file_sep>/src/util/login.ts
import * as express from 'express'
import { config } from '../config'
import { UserFacade } from '../bl/userFacade'
export const login = async (userId: number, res: express.Response) => {
const token = await UserFacade.authenticate(userId)
res.cookie(config.loginCookieName, token, {
httpOnly: true,
sameSite: true,
secure: config.env !== 'development'
})
}
<file_sep>/src/util/oauthMiddlewares.ts
import * as Oauth2Server from 'oauth2-server'
import { AccessTokenFacade } from '../bl/accessTokenFacade'
import { AuthorizationCodeFacade } from '../bl/authorizationCodeFacade'
import { ClientFacade } from '../bl/clientFacade'
const model = {
getAuthorizationCode: AuthorizationCodeFacade.getById,
saveAuthorizationCode: AuthorizationCodeFacade.getOrCreate,
revokeAuthorizationCode: AuthorizationCodeFacade.delete,
getAccessToken: AccessTokenFacade.getById,
saveToken: AccessTokenFacade.create,
getClient: ClientFacade.getByIdAndSecret,
verifyScope: () => Promise.resolve(true)
}
const oauth = new Oauth2Server({ model })
const Request = Oauth2Server.Request
const Response = Oauth2Server.Response
export const tokenMiddleware = (req, res, next) => {
const request = new Request(req)
const response = new Response(res)
oauth.token(request, response)
.then((token) => {
res.set(response.headers).json(response.body)
})
.catch(err => {
console.log(err)
res.status(err.status).json({ message: err.message })
})
}
export const authorizeMiddleware = (req, res, next) => {
const request = new Request(req)
const response = new Response(res)
const options = {
authenticateHandler: {
handle: (data) => {
return req.user
}
},
allowEmptyState: true
}
if (req.body.cancel) {
return res.redirect(req.query.redirect_uri)
}
oauth.authorize(request, response, options).then((authorizationCode) => {
res.status(response.status).set(response.headers).end()
})
.catch(err => {
res.status(err.status).json({ message: err.message })
})
}
export const authenticateMiddleware = (req, res, next) => {
const request = new Request(req)
const response = new Response(res)
oauth.authenticate(request, response)
.then((token) => {
Object.assign(req, { token })
next()
})
.catch(err => {
res.status(err.status).json({ message: err.message })
})
}
<file_sep>/README.md
# Prello-auth
Prello's authentification application.
[](https://circleci.com/gh/awi2017-option1group1/Prello-auth/tree/master)
- - - - - - - - -
## Installation
Before installing Prello-auth, you need to have Prello-back installed.
- Clone the github repository.
`git clone https://github.com/awi2017-option1group1/Prello-auth`
- Install the dependencies for development mode
`npm install`
## Execution
- Complete and update the `.env.dev` file then source it
`source .env`
- To run the application in development mode
`npm run start:dev`
- To run the application in production mode
`npm run build && npm start`
- To run the tests
`npm test`
- - - - - - - - -
## Dependencies
- Prello back end application is written in `Typescript`.
- It is built with `Express`.
- We use `TypeORM` as ORM for the application.
- To test the application we use `Jest`.
- - - - - - - - -
## Contributing
Please follow the Google Angular guidelines:
[Guidelines](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md#-git-commit-guidelines)
## Useful links to look at before contributing
- [TypeORM documentation](http://typeorm.io/#/)
<file_sep>/copyStaticAssets.js
var shell = require('shelljs');
shell.cp('-R', 'src/views/', 'dist/views/');
<file_sep>/src/routes/user.ts
import * as express from 'express'
import { AccessTokenFacade } from '../bl/accessTokenFacade'
import { UserFacade } from '../bl/userFacade'
export class UserController {
static async getTokens(req: express.Request, res: express.Response) {
const tokens = await AccessTokenFacade.getAllByUser(req.token.user.id)
return res.json({ tokens })
}
static async getTokenData(req: express.Request, res: express.Response) {
switch (req.params.type) {
case 'header':
const accessToken = await AccessTokenFacade.getById(req.params.token)
if (accessToken) {
res.status(200).send({ user: { uid: accessToken.user.uid } })
}
res.status(404).json({ error: 'Invalid token' })
break
case 'cookie':
const user = await UserFacade.getByToken(req.params.token)
if (user) {
res.status(200).send({ user: { uid: user.uid } })
}
res.status(404).json({ error: 'Invalid token' })
break
default:
res.status(400).json({ error: 'Invalid token type' })
break
}
}
static async getMe(req: express.Request, res: express.Response) {
return res.json({
me: {
username: req.user.username,
email: req.user.email,
uid: req.user.uid,
avatarColor: req.user.avatarColor
}
})
}
static async getMyUser(req: express.Request, res: express.Response) {
req.user = req.token.user
return UserController.getMe(req, res)
}
}
<file_sep>/src/util/passport.ts
import * as passport from 'passport'
import { config } from '../config'
import { fullUrlFromString, AUTH_HOST } from './url'
import { UserFacade } from '../bl/userFacade'
const CookieStrategy = require('passport-cookie').Strategy
passport.use(new CookieStrategy({ cookieName: config.loginCookieName }, (token, done) => {
UserFacade.getByToken(token).then(
user => done(null, user),
error => done(error)
)
}))
export default passport
interface EnsureLoginOptions {
redirect?: boolean
}
const redirectToLogin = (req, res) => {
return res
.cookie(config.redirectCookieName, `/${config.server.authSuffix}${req.url}`, {
httpOnly: true,
sameSite: true,
secure: config.env !== 'development',
maxAge: 300000
})
.redirect(fullUrlFromString(`/login`, AUTH_HOST))
}
export const ensureLogin = (options?: EnsureLoginOptions) => (req, res, next) => {
passport.authenticate('cookie', { session: false }, (authErr, user, infos) => {
if (authErr || !user) {
if (options && options.redirect) {
redirectToLogin(req, res)
} else {
res.status(401).json({ error: 'Unauthorized' })
}
} else {
req.user = user
next()
}
})(req, res, next)
}
<file_sep>/src/routes/oauth.ts
import * as express from 'express'
import { fullUrlFromReq, AUTH_HOST } from '../util/url'
import { tokenMiddleware, authorizeMiddleware } from '../util/oauthMiddlewares'
import { AccessTokenFacade } from '../bl/accessTokenFacade'
import { ClientFacade } from '../bl/clientFacade'
export class OauthController {
static async getAuthorize(req: express.Request, res: express.Response, next: express.NextFunction) {
const client = await ClientFacade.getById(req.query.client_id)
// Bypass the user confirmation for trusted apps
if (client) {
if (client.isTrusted) {
return authorizeMiddleware(req, res, next)
} else {
const token = await AccessTokenFacade.getByClientAndUser(client.id, req.user.id)
if (token) {
return authorizeMiddleware(req, res, next)
}
}
}
return res.render('authorize', {
user: req.user,
client,
redirect_uri: fullUrlFromReq(req, AUTH_HOST)
})
}
static postAuthorize(req: express.Request, res: express.Response, next: express.NextFunction) {
return authorizeMiddleware(req, res, next)
}
static postToken(req: express.Request, res: express.Response, next: express.NextFunction) {
return tokenMiddleware(req, res, next)
}
static getDone(req: express.Request, res: express.Response) {
return res.render('done', { // views: done
type: 'authorization_code',
code: req.query.code,
state: req.query.state,
to: req.query.to || '*'
})
}
}
<file_sep>/Dockerfile
FROM node:8.7.0
# Create app directory
RUN mkdir -p /src/app
WORKDIR /src/app
# Install app dependencies
COPY package.json /src/app/
RUN npm install
# Bundle app source
COPY . /src/app
# Build and optimize react app
RUN npm run build
# Set the command to start the node server.
CMD npm start
<file_sep>/src/util/oauth.ts
import { config } from '../config'
const Oauth2Service = require('oauth').OAuth2
export const GithubService = new Oauth2Service(
config.github.clientID,
config.github.clientSecret,
'https://github.com/',
'login/oauth/authorize',
'login/oauth/access_token'
)
<file_sep>/src/server.ts
import { createConnection } from 'typeorm'
import { fromConfig } from './database'
import { app } from './app'
createConnection(fromConfig())
.then(async connection => {
app.listen(app.get('port'), () => {
console.log(('App is running at http://localhost:%d in %s mode'), app.get('port'), app.get('env'))
console.log('Press CTRL-C to stop\n')
})
}).catch(error => console.log(error))
<file_sep>/src/bl/authorizationCodeFacade.ts
import { getRepository } from 'typeorm'
import { AuthorizationCode } from 'oauth2-server'
import { OAuth2AuthorizationCode } from '../entities/AuthorizationCode'
import { OAuth2Client } from '../entities/Client'
import { OAuth2User } from '../entities/User'
export class AuthorizationCodeFacade {
static async getById(id: string) {
return await getRepository(OAuth2AuthorizationCode).findOne({
relations: ['client', 'user'],
where: {
authorizationCode: id
}
}).then(code => {
if (code) {
const localCode = code!
localCode.expiresAt = new Date(localCode.expiresAt)
return localCode
}
return code!
})
}
static async getOrCreate(code: AuthorizationCode, client: OAuth2Client, user: OAuth2User) {
const localCode = await AuthorizationCodeFacade.getByClientAndUser(client.id, user.id)
if (localCode) {
return localCode
} else {
code.client = client
code.user = user
code.expiresAt = new Date(2048, 1)
return await getRepository(OAuth2AuthorizationCode).save(code)
}
}
static async getByClientAndUser(clientId: string, userId: string) {
return await getRepository(OAuth2AuthorizationCode)
.createQueryBuilder('code')
.leftJoin('code.user', 'user')
.leftJoin('code.client', 'client')
.where('user.id = :userId', { userId })
.where('client.id = :clientId', { clientId })
.getOne()
.then(code => code!)
}
static async delete(code: AuthorizationCode) {
await getRepository(OAuth2AuthorizationCode).deleteById(code.authorizationCode)
return true
}
}
<file_sep>/.circleci/setup-heroku.sh
#!/bin/bash
git remote add heroku https://git.heroku.com/prello-auth.git
git config --global user.email "<EMAIL>"
git config --global user.name "<NAME>"
wget https://cli-assets.heroku.com/branches/stable/heroku-linux-amd64.tar.gz
sudo mkdir -p /usr/local/lib /usr/local/bin
sudo tar -xvzf heroku-linux-amd64.tar.gz -C /usr/local/lib
sudo ln -s /usr/local/lib/heroku/bin/heroku /usr/local/bin/heroku
cat > ~/.netrc << STOP
machine api.heroku.com
login $HEROKU_LOGIN
password $HEROKU_API_KEY
machine git.heroku.com
login $HEROKU_LOGIN
password $HEROKU_API_KEY
STOP
# Add heroku.com to the list of known hosts
mkdir -p ~/.ssh
ssh-keyscan -H heroku.com >> ~/.ssh/known_hosts
<file_sep>/src/database.ts
import { ConnectionOptions } from 'typeorm'
import { config } from './config'
export const fromConfig = (): ConnectionOptions => ({
...config.database,
synchronize: false,
entities: [
`${__dirname}/entities/*.js`
],
migrations: [
`${__dirname}/migrations/*.js`
],
logging: ['query', 'error']
})
<file_sep>/src/util/internalMiddleware.ts
import { config } from '../config'
export const ensureInternal = () => (req, res, next) => {
const authHeader = req.get('authorization')
if (authHeader) {
if (authHeader.substring('Bearer '.length) === config.internalToken) {
return next()
}
}
res.status(403).json({ error: 'Forbidden' })
}
<file_sep>/src/entities/User.ts
import { Entity, Column, Generated, PrimaryGeneratedColumn } from 'typeorm'
@Entity('user')
export class OAuth2User {
@PrimaryGeneratedColumn({
name: 'id'
})
uid: number
@Column({
name: 'uuid',
type: 'varchar',
unique: true
})
@Generated('uuid')
id: string
@Column({
name: 'email',
type: 'varchar',
unique: true
})
email: string
@Column({
name: 'password',
type: 'varchar'
})
password: string
@Column({
name: 'username',
type: 'varchar'
})
username: string
@Column({
type: 'varchar'
})
avatarColor: string
@Column({
type: 'boolean',
default: false
})
confirmed: boolean
@Column({
name: 'token',
type: 'varchar',
nullable: true
})
token?: string
}
<file_sep>/src/bl/refreshTokenFacade.ts
import { getRepository } from 'typeorm'
import { OAuth2RefreshToken } from '../entities/RefreshToken'
export class RefreshTokenFacade {
static async getById(id: string) {
return await getRepository(OAuth2RefreshToken).findOne({
refreshToken: id
}).then(token => token!)
}
}
<file_sep>/src/routes/github.ts
import * as express from 'express'
import * as rq from 'request'
import { config } from '../config'
import { GithubService } from '../util/oauth'
import { login } from '../util/login'
import { fullUrlFromString, API_HOST, AUTH_HOST } from '../util/url'
import { LoginController } from './login'
import { UserFacade } from '../bl/userFacade'
import { OAuth2User } from '../entities/User'
interface GithubProfile {
login: string
avatar_url: string
id: number,
name: string
}
interface GithubEmail {
email: string
}
export class GithubController {
static async getGithubLogin(req: express.Request, res: express.Response) {
res.redirect(GithubService.getAuthorizeUrl({
redirect_uri: config.github.callbackURL,
scope: 'user:email'
}))
}
static async getGithubLoginCallback(req: express.Request, res: express.Response) {
const code = req.query.code
GithubService.getOAuthAccessToken(code, {}, async (tokenErr, accessToken, refreshToken) => {
if (tokenErr || !accessToken) {
res.redirect(fullUrlFromString('/login?oauth_error=Github', AUTH_HOST))
}
try {
const [ profile, emails ] = await Promise.all([
GithubController.getUserProfile(accessToken),
GithubController.getUserEmails(accessToken)
])
const primaryEmail = emails[0].email
let user = await UserFacade.getByEmail(primaryEmail)
if (!user) {
user = await GithubController.createUser(primaryEmail, profile.login)
}
await login(user!.uid, res)
return LoginController.redirectLogin(req, res)
} catch (e) {
console.log(e)
res.redirect(fullUrlFromString('/login?oauth_error=Github', AUTH_HOST))
}
res.end()
})
}
private static createUser(email: string, username: string): Promise<OAuth2User> {
return new Promise((resolve, reject) => {
rq.post(
fullUrlFromString('/register', API_HOST),
{
json: true,
body: {
email,
username
}
},
(reqErr, response, body) => {
if (reqErr) {
reject(reqErr)
} else {
if (response.statusCode === 400) {
reject(body)
}
body.uid = body.id
resolve(body)
}
}
)
})
}
private static getUserProfile(accessToken: string): Promise<GithubProfile> {
return new Promise((resolve, reject) => {
rq.get(
'https://api.github.com/user',
{
auth: {
bearer: accessToken
},
headers: {
'User-Agent': config.github.userAgent
}
},
(reqErr, response, body) => {
if (reqErr) {
reject(reqErr)
} else {
resolve(JSON.parse(body))
}
}
)
})
}
private static getUserEmails(accessToken: string): Promise<GithubEmail[]> {
return new Promise((resolve, reject) => {
rq.get(
'https://api.github.com/user/emails',
{
auth: {
bearer: accessToken
},
headers: {
'User-Agent': config.github.userAgent
}
},
(reqErr, response, body) => {
if (reqErr) {
reject(reqErr)
} else {
resolve(JSON.parse(body))
}
}
)
})
}
}
<file_sep>/src/routes/login.ts
import * as express from 'express'
import { config } from '../config'
import { fullUrlFromReq, fullUrlFromString, AUTH_HOST } from '../util/url'
import { login } from '../util/login'
import { UserFacade } from '../bl/userFacade'
export class LoginController {
static getLogin(req: express.Request, res: express.Response) {
if (req.cookies[config.loginCookieName]) {
return LoginController.redirectLogin(req, res)
}
let errors: string[] = []
if (req.query.oauth_error) {
errors.push(`Error during ${req.query.oauth_error} authentication process`)
}
if (req.query.redirect) {
res.cookie(config.redirectCookieName, req.query.redirect)
}
return res.render('login', { // views: login
redirect_uri: fullUrlFromReq(req, AUTH_HOST),
email: '',
errors,
github_login_url: fullUrlFromString('/github', AUTH_HOST)
})
}
static async postLogin(req: express.Request, res: express.Response) {
const user = await UserFacade.getByEmailAndPassword(req.body.email, req.body.password)
if (user && user.confirmed) {
await login(user.uid, res)
return LoginController.redirectLogin(req, res)
} else {
return res.render('login', { // views: login
redirect_uri: fullUrlFromReq(req, AUTH_HOST),
email: req.body.email || '',
errors: ['Invalid credentials or not confirmed account'],
github_login_url: fullUrlFromString('/github', AUTH_HOST)
})
}
}
static getLogout(req: express.Request, res: express.Response) {
req.logout()
res.clearCookie(config.loginCookieName)
res.redirect('/')
}
static redirectLogin(req: express.Request, res: express.Response) {
let redirect = req.cookies[config.redirectCookieName] || req.query.redirect
if (redirect) {
if (!redirect.startsWith('/')) {
redirect = `/${redirect}`
}
return res.clearCookie(config.redirectCookieName).redirect(redirect)
} else {
return res.redirect(`/${config.loginDefaultRedirect}`)
}
}
}
<file_sep>/src/entities/Client.ts
import { Entity, Column, Generated, PrimaryGeneratedColumn } from 'typeorm'
@Entity('client')
export class OAuth2Client {
@PrimaryGeneratedColumn({
name: 'id'
})
cid: number
@Column({
name: 'client_id',
type: 'varchar',
unique: true
})
@Generated('uuid')
id: string
@Column({
type: 'varchar'
})
name: string
@Column({
name: 'client_secret',
type: 'varchar'
})
@Generated('uuid')
clientSecret: string
@Column({
name: 'redirect_uris',
type: 'simple-array'
})
redirectUris: string[]
grants: string[] = ['authorization_code', 'refresh_token']
@Column({
name: 'is_trusted',
type: 'boolean'
})
isTrusted: boolean
}
<file_sep>/src/entities/RefreshToken.ts
import { Entity, Column, PrimaryColumn, ManyToOne } from 'typeorm'
import { OAuth2Client } from './Client'
import { OAuth2User } from './User'
@Entity('oauth_refresh_token')
export class OAuth2RefreshToken {
@PrimaryColumn({
name: 'refresh_token',
type: 'varchar'
})
refreshToken: string
@Column({
name: 'refresh_token_expires_at',
type: 'date'
})
refreshTokenExpiresAt: Date
@Column({
name: 'scope',
type: 'varchar',
nullable: true
})
scope: string
@ManyToOne(type => OAuth2User)
user: OAuth2User
@ManyToOne(type => OAuth2Client)
client: OAuth2Client
}
<file_sep>/src/routes/callback.ts
import * as express from 'express'
import * as rq from 'request'
import { InternalOAuth, config } from '../config'
import { fullUrlFromString, AUTH_HOST } from '../util/url'
export class CallbackController {
static async getZendeskToken(req: express.Request, res: express.Response) {
try {
const token = await CallbackController.retrieveAccessToken(req.query.code, config.zendesk)
return res.status(200).json(token)
} catch (e) {
return res.status(400).json({ error: e })
}
}
static async getElectronToken(req: express.Request, res: express.Response) {
try {
const token = await CallbackController.retrieveAccessToken(req.query.code, config.electron)
return res.status(200).json(token)
} catch (e) {
return res.status(400).json({ error: e })
}
}
private static retrieveAccessToken(code: string, client: InternalOAuth): Promise<{}> {
return new Promise((resolve, reject) => {
rq.post(
fullUrlFromString(`/oauth/token` , AUTH_HOST),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `client_id=${client.clientId}`
+ `&client_secret=${client.clientSecret}`
+ `&grant_type=authorization_code&code=${code}`
+ `&redirect_uri=${client.redirectUri}`
},
(reqErr, response, body) => {
if (reqErr) {
reject(reqErr)
} else {
if (response.statusCode === 200) {
resolve(JSON.parse(body))
} else {
reject(JSON.parse(body))
}
}
}
)
})
}
}
<file_sep>/src/config.ts
import { ConnectionOptions } from 'typeorm'
export interface GithubConfig {
clientID: string
clientSecret: string
callbackURL: string
userAgent: string
}
export interface ServerConfig {
host: string
port: number
apiSuffix: string
authSuffix: string
}
export interface InternalOAuth {
clientId: string
clientSecret: string
redirectUri: string
}
export interface Config {
env: 'development' | 'production' | 'test'
loginCookieName: string
loginDefaultRedirect: string
internalToken: string
redirectCookieName: string
github: GithubConfig
server: ServerConfig
database: ConnectionOptions
electron: InternalOAuth
zendesk: InternalOAuth
}
export const config: Config = {
env: process.env.NODE_ENV || 'development',
loginCookieName: process.env.LOGIN_COOKIE_NAME || 'photon',
loginDefaultRedirect: process.env.LOGIN_DEFAULT_REDIRECT || 'overview',
internalToken: process.env.INTERNAL_TOKEN || '<PASSWORD>',
redirectCookieName: 'redirect',
github: {
clientID: process.env.GITHUB_CLIENT_ID || '8515ee45647519a537bd',
clientSecret: process.env.GITHUB_CLIENT_SECRET || '9399ae2120cab4a95d1890de32a8c64ab82dc19a',
callbackURL: process.env.GITHUB_CALLBACK_URL || 'http://localhost/auth/github/callback',
userAgent: process.env.GITHUB_CLIENT_NAME || 'Prello-dev'
},
server: {
host: process.env.SERVER_HOST || 'http://localhost',
port: process.env.PORT || 8000,
apiSuffix: process.env.API_SUFFIX || 'api',
authSuffix: process.env.AUTH_SUFFIX || 'auth'
},
database: {
type: process.env.DATABASE_TYPE || 'postgres',
ssl: process.env.DATABASE_SSL === 'true',
url: process.env.DATABASE_URL || 'postgres://postgres:root@localhost:5434/dev_prello'
},
electron: {
clientId: process.env.INTERNAL_OAUTH_ELECTRON_CLIENT_ID || 'e70919f4-b7f3-466b-b326-9faa7f7290f0',
clientSecret: process.env.INTERNAL_OAUTH_ELECTRON_CLIENT_SECRET || '0927e397-8be8-4216-935b-53e3e4424261',
redirectUri: process.env.INTERNAL_OAUTH_ELECTRON_CLIENT_REDIRECT_URI || 'http://localhost:3000/oauth'
}
zendesk: {
clientId: process.env.INTERNAL_OAUTH_ZENDESK_CLIENT_ID || '9fc19d15-4a3a-4373-8f50-c1b478a8051b',
clientSecret: process.env.INTERNAL_OAUTH_ZENDESK_CLIENT_SECRET || '0927e397-8be8-4216-935b-53e3e4424261',
redirectUri: process.env.INTERNAL_OAUTH_ZENDESK_CLIENT_REDIRECT_URI || 'http://localhost:4567/oauth.html'
}
}
<file_sep>/src/bl/clientFacade.ts
import { getRepository } from 'typeorm'
import { OAuth2Client } from '../entities/Client'
export class ClientFacade {
static async getById(id: string) {
return await getRepository(OAuth2Client).findOne({
id
})
}
static async getByIdAndSecret(id: string, secret: string) {
if (secret) {
return await getRepository(OAuth2Client).findOne({
id,
clientSecret: secret
})
} else {
return await ClientFacade.getById(id)
}
}
}
<file_sep>/src/bl/userFacade.ts
import { getRepository } from 'typeorm'
import { v4 as uuid } from 'uuid'
import { compareSync } from 'bcrypt'
import { OAuth2User } from '../entities/User'
export class UserFacade {
static async getById(id: string) {
return await getRepository(OAuth2User).findOne({
id
})
}
static async getByEmail(email: string) {
return await getRepository(OAuth2User).findOne({
email
})
}
static async getByEmailAndPassword(email: string, password: string) {
const user = await UserFacade.getByEmail(email)
if (user && compareSync(password, user.password)) {
return user
} else {
return false
}
}
static async getByToken(token: string) {
return await getRepository(OAuth2User).findOne({
token
})
}
static async authenticate(uid: number) {
const token = uuid()
await getRepository(OAuth2User).update({ uid }, { token })
return token
}
}
<file_sep>/src/util/url.ts
import * as express from 'express'
import { config } from '../config'
export const HOST = config.server.host
export const API_HOST = `${HOST}/${config.server.apiSuffix}`
export const AUTH_HOST = `${HOST}/${config.server.authSuffix}`
export const fullUrlFromString = (originalUrl: string, host: string) => {
return `${host}${originalUrl}`
}
export const fullUrlFromReq = (req: express.Request, host: string) => {
return fullUrlFromString(req.originalUrl, host)
}
<file_sep>/src/bl/accessTokenFacade.ts
import { getRepository } from 'typeorm'
import { Token } from 'oauth2-server'
import { OAuth2AccessToken } from '../entities/AccessToken'
import { OAuth2Client } from '../entities/Client'
import { OAuth2User } from '../entities/User'
export class AccessTokenFacade {
static async getById(id: string) {
return await getRepository(OAuth2AccessToken).findOne({
relations: ['client', 'user'],
where: {
accessToken: id
}
}).then(token => {
if (token) {
const localToken = token!
localToken.accessTokenExpiresAt = new Date(localToken.accessTokenExpiresAt)
return localToken
}
return token!
})
}
static async getByClientAndUser(clientId: string, userId: string) {
return await getRepository(OAuth2AccessToken)
.createQueryBuilder('token')
.leftJoin('token.user', 'user')
.leftJoin('token.client', 'client')
.where('user.id = :userId', { userId })
.where('client.id = :clientId', { clientId })
.getOne()
.then(token => token!)
}
static async getAllByUser(userId: string) {
return await getRepository(OAuth2AccessToken)
.createQueryBuilder('token')
.leftJoin('token.user', 'user')
.leftJoin('token.client', 'client')
.where('user.id = :userId', { userId })
.select([
'token.accessTokenExpiresAt',
'token.scope',
'client.id',
'client.name',
'client.cid',
'user.id',
'user.uid'
])
.getMany()
}
static async create(token: Token, client: OAuth2Client, user: OAuth2User) {
token.client = client
token.user = user
token.accessTokenExpiresAt = new Date(2048, 1)
return await getRepository(OAuth2AccessToken).save(token)
}
// static async deleteByClientAndUser(clientId: string, userId: string) {
// return await getRepository(OAuth2AccessToken).save(token)
// }
}
<file_sep>/src/app.ts
import * as express from 'express'
import * as bodyParser from 'body-parser'
import * as cookieParser from 'cookie-parser'
import * as cors from 'cors'
import { config } from './config'
import { authenticateMiddleware } from './util/oauthMiddlewares'
import { CallbackController } from './routes/callback'
import { GithubController } from './routes/github'
import { LoginController } from './routes/login'
import { OauthController } from './routes/oauth'
import { UserController } from './routes/user'
import passport, { ensureLogin } from './util/passport'
import { ensureInternal } from './util/internalMiddleware'
export const app = express()
// Set up Express and Oauth2-Node
app.set('port', config.server.port)
app.engine('ejs', require('ejs-locals'))
app.set('views', `${__dirname}/views`)
app.set('view engine', 'ejs')
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(passport.initialize())
// Define routes
app.get('/', (req, res) => {
res.json({ healthcheck: 'ok' })
})
app.get('/login', LoginController.getLogin)
app.post('/login', LoginController.postLogin)
app.get('/logout', LoginController.getLogout)
app.get('/github', GithubController.getGithubLogin)
app.get('/github/callback', GithubController.getGithubLoginCallback)
app.get('/me', ensureLogin(), UserController.getMe)
app.use('/myUser', cors())
app.get('/myUser', authenticateMiddleware, UserController.getMyUser)
app.get('/data/token/:token/:type', ensureInternal(), UserController.getTokenData)
app.get('/tokens', authenticateMiddleware, UserController.getTokens)
// app.get('/tokens', authenticateMiddleware, UserController.getTokens) get data about the requester
// app.delete('/users/tokens/:clientId', LoginController.getLogin) revoke the token
app.use('/token/zendesk', cors({
origin: 'https://d3v-prello.zendesk.com'
}))
app.get('/token/zendesk', CallbackController.getZendeskToken)
app.use('/token/electron', cors({
origin: 'http://localhost:3000'
}))
app.get('/token/electron', CallbackController.getElectronToken)
app.get('/oauth/authorize', ensureLogin({ redirect: true }), OauthController.getAuthorize)
app.post('/oauth/authorize', ensureLogin({ redirect: true }), OauthController.postAuthorize)
app.post('/oauth/token', OauthController.postToken)
<file_sep>/src/entities/AuthorizationCode.ts
import { Entity, Column, PrimaryColumn, ManyToOne } from 'typeorm'
import { OAuth2Client } from './Client'
import { OAuth2User } from './User'
@Entity('oauth_authorization_code')
export class OAuth2AuthorizationCode {
@PrimaryColumn({
name: 'authorization_code',
type: 'varchar'
})
authorizationCode: string
@Column({
name: 'authorization_code_expires_at',
type: 'date'
})
expiresAt: Date
@Column({
name: 'redirect_uri',
type: 'varchar'
})
redirectUri: string
@Column({
name: 'scope',
type: 'varchar',
nullable: true
})
scope: string
@ManyToOne(type => OAuth2User)
user: OAuth2User
@ManyToOne(type => OAuth2Client)
client: OAuth2Client
}
<file_sep>/src/entities/AccessToken.ts
import { Entity, Column, PrimaryColumn, ManyToOne } from 'typeorm'
import { OAuth2Client } from './Client'
import { OAuth2User } from './User'
@Entity('oauth_access_token')
export class OAuth2AccessToken {
@PrimaryColumn({
name: 'access_token',
type: 'varchar'
})
accessToken: string
@Column({
name: 'access_token_expires_at',
type: 'date'
})
accessTokenExpiresAt: Date
@Column({
name: 'scope',
type: 'varchar',
nullable: true
})
scope: string
@ManyToOne(type => OAuth2User)
user: OAuth2User
@ManyToOne(type => OAuth2Client)
client: OAuth2Client
}
| 181afe0310434dca3652eb277f008965caf3d778 | [
"Markdown",
"JavaScript",
"TypeScript",
"Dockerfile",
"Shell"
] | 29 | TypeScript | awi2017-option1group1/Prello-auth | 11a61c7039eda5f20f75699b59aed6969a5b009a | d7197f36dd20a8546a94a0037f131715445e283e | |
refs/heads/main | <repo_name>IvanDilberovic/commander-app<file_sep>/src/App.js
import {Home} from './components/Home';
import {Command} from './components/Command';
import {Navigation} from './navigation/Navigation';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<div className="container">
<h3 className="m-3 d-flex justify-content-center">
Commander App
</h3>
<Navigation/>
<Switch>
<Route path="/" component={Home} exact></Route>
<Route path='/command' component={Command}></Route>
</Switch>
</div>
</BrowserRouter>
);
}
export default App;
<file_sep>/README.md
Commander App React REST API
<file_sep>/src/components/Command.js
import React, {Component} from 'react';
export class Command extends Component{
render(){
return(
<div className="mt-5 d-flex justify-content-left">
This is Command page.
</div>
)
}
} | fa6085fd40473af96fc3a124494f6fd2629bdee4 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | IvanDilberovic/commander-app | f284a84b8bf698a7fde813442ba418f6d3e29a5f | 0e03daeeb7bc3a33cd7159c84894b2126cf7b0a4 | |
refs/heads/master | <file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "base.h"
#include "record.h"
// Function: print_all_records()
// Input: record - array of Records; this may contain empty elements in the middle
// Output: none
// - Leave a brief information about the function
/*void print_all_records(Participant participants[]){
// TODO: Modify this function as you need
}*/
void create_pcp(linkedList *my_list,Participant *pcp,int *number_to_add)
{
char flat;
//Participant* kpcp;
while(flat!='Q'){
printf("Choose input methods or option to quit (K-keyboard, D-data file, Q-quit) ");
scanf(" %c",&flat);
if(flat == 'K')
{
add_pcp_from_k(pcp);
(*number_to_add)++;
create_new_node(my_list, pcp);
}
else if (flat == 'D')
{
add_pcp_from_d(my_list,pcp);
(*number_to_add)++;
//create_new_node(my_list, pcp);
}
else if (flat == 'Q')
{
break;
}
else{
printf("You enetered the invalid option.");
continue;
}
}
//return (*number_to_add);
}
void add_pcp_from_k(Participant *pcp)
{
char buffer[20];
printf("create a new pcp data from a keyboard\n");
printf("Enter the name \n(c.p. name format; if name is <NAME>, Enter like this->Kim_You_Jin) : ");
scanf("%s",buffer);
strncpy(pcp->name,buffer,sizeof(buffer));
printf("Enter the phone number : ");
scanf("%s",buffer);
strncpy(pcp->phone_num,buffer,sizeof(buffer));
printf("Enter the age : ");
scanf("%d",&pcp->age);
printf("Enter the name of high school : ");
scanf("%s", buffer);
strncpy(pcp->n_highsch,buffer,sizeof(buffer));
printf("Enter the number of group : ");
scanf(" %d",&pcp->gr_num);
printf("The below infromaiton is added!\n");
printf("%s\n%s\n%d\n%s\n%d\n",pcp->name,pcp->phone_num,pcp->age,pcp->n_highsch,pcp->gr_num);
}
void add_pcp_from_d(linkedList *my_list,Participant* pcp)
{
char filename[10];
char buffer[20];
int i=0;
printf("Enter the file name : ");
scanf("%s",filename);
FILE * fp= fopen(filename,"rt");
if(fp==NULL){
puts("Fail to open the file!");
}
else{
while(!feof(fp)){
fscanf(fp,"%s\n%s\n%d\n%s\n%d",pcp->name,pcp->phone_num,&pcp->age,pcp->n_highsch,&pcp->gr_num);
i++;
}
printf("The below infromaiton is added!\n");
printf("%s\n%s\n%d\n%s\n%d\n",pcp->name,pcp->phone_num,pcp->age,pcp->n_highsch,pcp->gr_num);
create_new_node(my_list, pcp);
fclose(fp);
}
}
void create_new_node(linkedList *my_list,Participant *tpcp)
{
node *new_node = (node *)malloc(sizeof(node));
new_node->pcp = *tpcp;
new_node->link=NULL;
if(my_list->head == NULL && my_list->tail == NULL)
my_list->head = my_list->tail = new_node;
else
{
my_list->tail->link = new_node;
my_list -> tail = new_node;
}
}
void print_nodes(linkedList *my_list)
{
char flat;
char buffer;
int o=0;
printf("A- It prints out all participants,\n");
printf("B- It only prints out the participant of the name you entered\n");
printf("C- It only prints out the participant of the phone number you enetered\n");
printf("D- It only prints out the participants of the age you entered\n");
printf("E- It only prints out the participants of the name for high school you entered\n");
printf("F- It only prints out the participant of the group number you enetered\n");
printf("Q - if you want to quit, enter Q.\n");
while(flat!='Q'){
if(o>0){
buffer =getchar();
}
printf("Choose the print condition you want : ");
scanf("%c",&flat);
if(flat == 'A')
{
print_all_nodes(my_list);
}
else if(flat == 'B')
{
print_name_nodes(my_list);
}
else if(flat == 'C')
{
print_phone_num_nodes(my_list);
}
else if(flat == 'D')
{
print_age_nodes(my_list);
}
else if(flat == 'E')
{
print_school_nodes(my_list);
}
else if(flat == 'F')
{
print_group_num_nodes(my_list);
}
else if(flat == 'Q')
{
break;
}
else{
printf("You enetered the invalid option.");
continue;
}
}
}
void print_all_nodes(linkedList *my_list)
{
node *p = my_list->head;
int k = 0;
printf("All prints out the list of participants\n");
while(p!=NULL)
{
printf("=======================================\n");
printf("=================No.%d==================\n",++k);
printf("\tName : %s\n\tPhone_number : %s\n\tAge : %d\n\tHigh School : %s\n\tGroup Number : %d\n",p->pcp.name,p->pcp.phone_num,p->pcp.age,p->pcp.n_highsch,p->pcp.gr_num);
p=p->link;
}
}
void print_name_nodes(linkedList *my_list)
{
node *p;
char yw[20];
int k = 0;
printf("Enter the name of the participant you want: ");
scanf("%s",yw);
for(p=my_list->head; p!=NULL; p=p->link)
{
if(!strncmp(p->pcp.name,yw,sizeof(yw)))
{
printf("=======================================\n");
printf("=================No.%d==================\n",++k);
printf("\tName : %s\n\tPhone_number : %s\n\tAge : %d\n\tHigh School : %s\n\tGroup Number : %d\n",p->pcp.name,p->pcp.phone_num,p->pcp.age,p->pcp.n_highsch,p->pcp.gr_num);
}
}
}
void print_phone_num_nodes(linkedList *my_list)
{
node *p;
char yw[20];
int k = 0;
printf("Enter the phone number of the participant you want: ");
scanf("%s",yw);
for(p=my_list->head; p!=NULL; p=p->link)
{
if(!strncmp(p->pcp.phone_num,yw,sizeof(yw)))
{
printf("=======================================\n");
printf("=================No.%d==================\n",++k);
printf("\tName : %s\n\tPhone_number : %s\n\tAge : %d\n\tHigh School : %s\n\tGroup Number : %d\n",p->pcp.name,p->pcp.phone_num,p->pcp.age,p->pcp.n_highsch,p->pcp.gr_num);
}
}
}
void print_age_nodes(linkedList *my_list)
{
node *p;
int num_yw=0;
int k = 0;
printf("Enter the age of the participant you want: ");
scanf("%d",&num_yw);
for(p=my_list->head; p!=NULL; p=p->link)
{
if(p->pcp.age == num_yw){
printf("=======================================\n");
printf("=================No.%d==================\n",++k);
printf("\tName : %s\n\tPhone_number : %s\n\tAge : %d\n\tHigh School : %s\n\tGroup Number : %d\n",p->pcp.name,p->pcp.phone_num,p->pcp.age,p->pcp.n_highsch,p->pcp.gr_num);
}
}
}
void print_school_nodes(linkedList *my_list)
{
node *p;
char yw[20];
int k = 0;
printf("Enter the school name of the participant you want: ");
scanf("%s",yw);
for(p=my_list->head; p!=NULL; p=p->link)
{
if(!strncmp(p->pcp.n_highsch,yw,sizeof(yw)))
{
printf("=======================================\n");
printf("=================No.%d==================\n",++k);
printf("\tName : %s\n\tPhone_number : %s\n\tAge : %d\n\tHigh School : %s\n\tGroup Number : %d\n",p->pcp.name,p->pcp.phone_num,p->pcp.age,p->pcp.n_highsch,p->pcp.gr_num);
}
}
}
void print_group_num_nodes(linkedList *my_list)
{
node *p;
int num_yw=0;
int k=0;
printf("Enter the group number you want: ");
scanf("%d",&num_yw);
for(p=my_list->head; p!=NULL; p=p->link)
{
if(p->pcp.gr_num == num_yw){
printf("=======================================\n");
printf("=================No.%d==================\n",++k);
printf("\tName : %s\n\tPhone_number : %s\n\tAge : %d\n\tHigh School : %s\n\tGroup Number : %d\n",p->pcp.name,p->pcp.phone_num,p->pcp.age,p->pcp.n_highsch,p->pcp.gr_num);
}
}
}
void export_entire_data_in_report(linkedList *my_list)
{
char filename[20];
node *p;
int k=1;
printf("We will export the entire data in a report format.\n");
printf("Please keep the below rule of naming the file.\n");
printf("1. Files should be named consistently.\n");
printf("2. Use capitals and underscores instead of periods or spaces or slashes.\n");
printf("3. Avoid special characters or spaces in a file name.\n");
printf("Enter the file name you want to make : ");
scanf("%s",filename);
FILE *fp= fopen(filename,"wt");
fprintf(fp,"=======================================\n");
fprintf(fp,"========The Report Of Paricipant=======\n");
fprintf(fp,"=======================================\n");
for(p=my_list->head; p!=NULL; p=p->link)
{
fprintf(fp,"=================No.%d==================\n",k++);
//name
fprintf(fp,"\tName : %s\n",p->pcp.name);
//phone_num
fprintf(fp,"\tPhone Number : %s\n",p->pcp.phone_num);
//age
fprintf(fp,"\tAge : %d\n",p->pcp.age);
//high school name
fprintf(fp,"\tHigh school : %s\n",p->pcp.n_highsch);
//group number
fprintf(fp,"\tGroup Number : %d\n",p->pcp.gr_num);
fprintf(fp,"=======================================\n");
}
fclose(fp);
}
void read_entire_data_from_file(linkedList *my_list)
{
char filename[25];
Participant buffer_pcp;
printf("We will read the entire data in the list of participants from the file you want.\n");
printf("Enter the file name you want to read : ");
scanf("%s",filename);
FILE * fp= fopen(filename,"rt");
if(fp==NULL){
printf("Fail to read the file!");
}
while(!feof(fp)){
fscanf(fp,"%s\n%s\n%d\n%s\n%d\n",buffer_pcp.name,buffer_pcp.phone_num,&buffer_pcp.age,buffer_pcp.n_highsch,&buffer_pcp.gr_num);
printf("%s\n%s\n%d\n%s\n%d\n",buffer_pcp.name,buffer_pcp.phone_num,buffer_pcp.age,buffer_pcp.n_highsch,buffer_pcp.gr_num);
}
fclose(fp);
}
void write_entire_data_to_file(linkedList *my_list)
{
char filename[25];
node *p;
printf("We will write the entire data in the list of participants.\n");
printf("Please keep the below rule of naming the file.\n");
printf("1. Files should be named consistently.\n");
printf("2. Use capitals and underscores instead of periods or spaces or slashes.\n");
printf("3. Avoid special characters or spaces in a file name.\n");
printf("Enter the file name you want to make : ");
scanf("%s",filename);
FILE * fp= fopen(filename,"wt");
for(p=my_list->head; p!=NULL; p=p->link)
{
fprintf(fp,"%s\n%s\n%d\n%s\n%d\n",p->pcp.name,p->pcp.phone_num,p->pcp.age,p->pcp.n_highsch,p->pcp.gr_num);
}
fclose(fp);
}
void find_node_to_update(linkedList *my_list)
{
char tname[20];
node *p;
printf("We will update the speific information of the participants you want.\n");
printf("Enter the name of participant you want to update the specific information without space. replace space with '_'.: ");
scanf("%s",tname);
getchar();
for(p=my_list->head; p!=NULL;p=p->link){
if(!strncmp(p->pcp.name,tname,sizeof(tname)))
{
update_the_node(my_list,&p->pcp);
//printf(" Update! Check the below data : )\n");
// printf("\tName : %s\n\tPhone_number : %s\n\tAge : %d\n\tHigh School : %s\n\tGroup Number : %d\n",p->pcp.name,p->pcp.phone_num,p->pcp.age,p->pcp.n_highsch,p->pcp.gr_num);
}
}
}
void update_the_node(linkedList *my_list,Participant *pcp)
{
char flat;
char tname[20];
char buffer[20];
int buffer_num;
while(flat!='Q')
{
printf("A- Update the name\n");
printf("B- Update the phone number\n");
printf("C- Update the age\n");
printf("D- Update the name of high school\n");
printf("E- Update the number of group\n");
printf("Q- Quit\n");
printf("Enter the option you want: ");
scanf("%c",&flat);
if(flat=='A'){
printf("Enter the new name to update without space. Replace space with '_' : ");
scanf("%s",buffer);
getchar();
strcpy(pcp->name, buffer);
print_update_data(pcp);
}
else if(flat=='B'){
printf("Enter the new phone number to update and keep the format=XXX-XXXX-XXXX : ");
scanf("%s",buffer);
getchar();
strcpy(pcp->phone_num,buffer);
print_update_data(pcp);
}
else if(flat=='C'){
printf("Enter the new age to update");
scanf("%d",&buffer_num);
getchar();
pcp->age = buffer_num;
print_update_data(pcp);
}
else if(flat=='D'){
printf("Enter the new name of the high school without space. Replace space with '_'.");
scanf("%s",buffer);
getchar();
strcpy(pcp->n_highsch,buffer);
print_update_data(pcp);
}
else if(flat=='E'){
printf("Enter the new group number to update");
scanf("%d",&buffer_num);
getchar();
pcp->gr_num = buffer_num;
print_update_data(pcp);
}
else if(flat=='Q'){
break;
}
}
}
void print_update_data(Participant *pcp)
{
printf(" Update! Check the below data : )\n");
printf("\tName : %s\n\tPhone_number : %s\n\tAge : %d\n\tHigh School : %s\n\tGroup Number : %d\n",pcp->name,pcp->phone_num,pcp->age,pcp->n_highsch,pcp->gr_num);
}
void find_node_to_delete(linkedList *my_list)
{
char tname[20];
node *p;
printf("We will delete the information of the participants you want.\n");
printf("Enter the name of participant you want to delete without space. replace space with '_'.: ");
scanf("%s",tname);
getchar();
for(p=my_list->head; p!=NULL;p=p->link){
if(!strncmp(p->pcp.name,tname,sizeof(tname)))
{
delete_the_node(my_list,&p->pcp);
printf(" Delete! Print to see if it has been deleted.\n");
print_name_nodes(my_list);
}
else{
printf("Participant information with the name you entered does not exist.");
break;
}
}
}
void delete_the_node(linkedList *my_list,Participant *pcp)
{
strcpy(pcp->name, "\0");
strcpy(pcp->phone_num, "\0");
pcp->age = 0;
strcpy(pcp->n_highsch, "\0");
pcp->gr_num = 0;
}
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "base.h"
#include "extra.h"
#include "record.h"
// function prototypes
void input_handler(char input[], linkedList *my_list,Participant* pcp,int * number_to_add);
void show_menu();
// main function
int main(){
Participant pcp;
linkedList *my_list = (linkedList *)malloc(sizeof(linkedList));
my_list->head = NULL;
my_list->tail = NULL;
int number_to_add=0;
int i=0;
char c;
char user_input[2] = "";
while(strcmp(user_input, "99") != 0){
if(i>0){
c=getchar();
}
show_menu();
printf("\nSelect a menu> ");
fgets(user_input, 2, stdin);
input_handler(user_input,my_list, &pcp,&number_to_add);
i++;
}
return 0;
}
// Function: input_handler()
// Input: record - array of Records; this may contain empty elements in the middle
// Output: none
// - Handles the user input and invokes functions that correspond to the user input
void input_handler(char input[], linkedList *my_list,Participant* pcp,int * number_to_add){
// TODO: Modify this function as you need
if(!strcmp(input, "1"))
create_pcp(my_list,pcp,number_to_add);
else if(!strcmp(input, "2"))
print_nodes(my_list);
else if(!strcmp(input, "3"))
export_entire_data_in_report(my_list);
else if(!strcmp(input, "4"))
read_entire_data_from_file(my_list);
else if(!strcmp(input, "5"))
write_entire_data_to_file(my_list);
else if(!strcmp(input, "6"))
find_node_to_update(my_list);
else if(!strcmp(input, "7"))
find_node_to_delete(my_list);
else if(!strcmp(input, "8"))
advanced_search(my_list);
else if(!strcmp(input, "99"))
printf("Terminating... bye!\n");
;// Quit - no operation (an empty statement with a semi-colon)*/
//else
// printf("Unknown menu: %s \n\n", input);
}
// Function: show_menu()
// Input: none
// Output: none
// - prints out the main menu
void show_menu(){
// TODO: Modify this function as you need
printf("******************************\n");
printf(" In G-IMPACT of Handong, the List of participants Management System(LMS) \n");
printf("******************************\n");
printf(" 1. create a new participants\n");
printf(" 2. Print participants in the way you want\n");
printf(" 3. Export the entire data in a report\n");
printf(" 4. Read the entire data from the file you want\n");
printf(" 5. Write the entire data to the file you want\n");
printf(" 6. Update the data of the participant you want\n");
printf(" 7. Delete the data of the participant you want\n");
printf(" 8. advanced search\n");
printf(" 99. Quit");
}
<file_sep>a.out: main.o base.o extra.o
gcc -o a.out main.o base.o extra.o
main.o: base.h extra.h record.h main.c
gcc -c -o main.o main.c
base.o : base.h base.c
gcc -c -o base.o base.c
extra.o: extra.h extra.c
gcc -c -o extra.o extra.c
clean:
rm a.out main.o base.o extras.o
<file_sep>#ifndef _BASE_H_
#define _BASE_H_
#include <stdlib.h>
#include "record.h"
// function prototypes
//void print_all_records(Participant[]);
//void register_pcp(Participant participants[]);
//void ld_data(Participant participants[],char * filename);
void create_pcp(linkedList *my_list,Participant* pcp, int* number_to_add);
void add_pcp_from_k(Participant* pcp);
void add_pcp_from_d(linkedList *my_list,Participant* pcp);
void create_new_node(linkedList *my_list,Participant* tpcp);
void print_all_nodes(linkedList *my_list);
void print_name_nodes(linkedList *my_list);
void print_phone_num_nodes(linkedList *my_list);
void print_age_nodes(linkedList *my_list);
void print_school_nodes(linkedList *my_list);
void print_group_num_nodes(linkedList *my_list);
void print_nodes(linkedList *my_list);
void export_entire_data_in_report(linkedList *my_list);
void read_entire_data_from_file(linkedList *my_list);
void write_entire_data_to_file(linkedList *my_list);
void find_node_to_update(linkedList *my_list);
void update_the_node(linkedList *my_list, Participant *pcp);
void print_update_data(Participant *pcp);
void find_node_to_delete(linkedList *my_list);
void delete_the_node(linkedList *my_list,Participant *pcp);
#endif
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "extra.h"
#include "record.h"
void advanced_search(linkedList *my_list) {
node *p;
int group_num;
int age_up;
int k = 0;
printf("Enter the group number you want : ");
scanf("%d", &group_num);
printf("Enter more than age you want : ");
scanf("%d", &age_up);
for(p=my_list->head; p!=NULL; p=p->link) {
if(p->pcp.gr_num == group_num && p->pcp.age >= age_up){
printf("=======================================\n");
printf("=================No.%d==================\n",++k);
printf("\tName : %s\n\tPhone_number : %s\n\tAge : %d\n\tHigh School : %s\n\tGroup Number : %d\n",p->pcp.name,p->pcp.phone_num,p->pcp.age,p->pcp.n_highsch,p->pcp.gr_num);
}
}
}<file_sep>#ifndef _RECORD_H_
#define _RECORD_H_
// type defition
typedef struct participant{
// TODO: define your own structure type here
char name[30]; // the name of the participant
char phone_num[20]; // the phone number of the participant
int age; // the age of the participant
char n_highsch[30]; // the name of the particiapant’s highschool
int gr_num;// the number of the group to which the participants belong
} Participant;
typedef struct node
{
Participant pcp;
struct node * link;
}node;
typedef struct linkedList
{
node *head, *tail;
}linkedList;
#endif
<file_sep>
#ifndef _EXTRAS_H_
#define _EXTRAS_H_
#include <stdlib.h>
#include "record.h"
void advanced_search(linkedList *my_list);
#endif
<file_sep># the-List-of-participants-Management-System
## Information
### The subject
#### - In G-IMPACT of Handong, the List of participants Management System(LMS)
### The purpose
#### - In G-IMPACT, the participants list is fixed finally the day before the event. Thus, the day before G-IMPACT, there are many fluctuations in the list. We need LMS to reflect the list fluctuation.
#### - The efficient sorting program of participants list is essential for safety management of all and G-IMPACT program operation.
### How the complete system could be used
#### - Not only G-IMPACT, we can also use LMS in other event such as HanST, Handong English Camp etc.
#### - Regardless the scale of the event, we always can manage the participants list efficiently.
## Implementation
### Create
#### - create a new data of the participants list from a file
#### - create a new data of the participants list from the standard input
### Read
#### - print a record, , multiple or all records to the standard output according to the specifed condition the user choose
#### - read or write the data of the participants list from/to the file system
#### - export the all data file of the participants in a report format as text file
### Update
#### - update the data of the participant the user want and choose
### Delete
#### - delete the data of the participant the user want
| 6de134ac5171f347ae271ca9d58739d2d6fb079a | [
"Markdown",
"C",
"Makefile"
] | 8 | C | KiEunKim-medofch/the-List-of-participants-Management-System | 186cd385ec90acfa3fd4b9282d90a6ae291758f1 | 7a00f78709938fbfaf5d588acb2a15f628491226 | |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import ErrorComponent from './ErrorComponent';
import MovieListDetails from './MovieListDetails';
export default class MovieList extends Component {
constructor(props) {
super(props);
this.state = {
error: ''
}
}
render() {
const { movieList } = this.props;
return (
<>
{movieList.Response ? <MovieListDetails movieDetails={movieList.Search}/> : <ErrorComponent error={movieList} />}
</>
);
}
}
<file_sep>import React, { Component } from 'react'
export default class VideoList extends Component {
constructor(props) {
super(props);
this.state = {
items: Array.from({ length: 10 })
};
}
render() {
// eslint-disable-next-line no-unused-vars
const {searchList,recordsPerPage,totalRecords} = this.props;
return (
<ul className="full-list">
{searchList.map(list =>
<li key={list.etag}>
<iframe title={list.snippet.title} src={`https://www.youtube.com/embed/`+list.id.videoId} frameBorder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowFullScreen />
<h6>{list.snippet.title}</h6>
<p>{list.snippet.description}</p>
<a href={`https://www.youtube.com/watch?v=`+list.id.videoId} target="_blank" rel="noopener noreferrer">Play More</a>
</li>
)}
</ul>
)
}
}
<file_sep>import React, { Component } from 'react'
export default class MovieListDetails extends Component {
render() {
const { movieDetails } = this.props;
return (
<>
<ul className="movie-list">
{movieDetails.map(movie =>
<li id={`movie`+movie.imdbID+movie.Title} key={`movie`+movie.Year+movie.imdbID+movie.Title}>
<div className="movie-card-image">
<img src={movie.Poster === 'N/A' ? `http://henrycavill.org/images/Films/2013-Man-of-Steel/posters/3-Walmart-Superman-a.jpg` : movie.Poster} alt={movie.Title} />
</div>
<div className="movie-card-body">
<h6 className="movie-card-title">{movie.Title}</h6>
<div className="movie-card-details">
<div className="movie-card-year">
<p>Year</p>
<p className="movie-card-movie">{movie.Type}</p>
</div>
<div className="movie-card-type">
<p>Type</p>
<p className="movie-card-year">{movie.Year}</p>
</div>
</div>
</div>
</li>
)}
</ul>
</>
)
}
}
| 1d870b9058a14aa4d1ed503163923b848f308182 | [
"JavaScript"
] | 3 | JavaScript | rajadileepkumar/youtube-api | 6147d7e9c73343438dac89c2aff70ba58d71a5bc | 5cd7a0b527a863ad1197bd6078ef3f0d6b5f0281 | |
refs/heads/master | <file_sep>/*
* (c) Copyright 2014 Swisscom AG
* All Rights Reserved.
*/
package com.swisscom.cloud.demo.spring.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.swisscom.cloud.demo.spring.model.Person;
/**
* @author <NAME>
* @since 24.02.2014
*/
@Transactional
@Component
public class PersonRepositoryImpl implements PersonRepository {
@PersistenceContext
private EntityManager em;
@Override
public List<Person> findAll() {
Query q = em.createQuery("SELECT p FROM Person p");
@SuppressWarnings("unchecked")
List<Person> result = q.getResultList();
return result;
}
@Override
public Person findOne(String id) {
Query q = em.createQuery("SELECT p FROM Person p WHERE p.id = :id");
q.setParameter("id", id);
return (Person) q.getSingleResult();
}
@Override
public <S extends Person> S save(Person person) {
em.merge(person);
@SuppressWarnings("unchecked")
S result = (S) person;
return result;
}
@Override
public void delete(Person person) {
Person loaded = findOne(person.getId());
if (loaded != null) {
em.remove(loaded);
}
}
}
<file_sep>/*
* (c) Copyright 2014 Swisscom AG
* All Rights Reserved.
*/
package com.swisscom.cloud.demo.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;
/**
* @author <NAME>
* @since 24.02.2014
*/
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public View home() {
return new RedirectView("/person", true);
}
}
<file_sep>cf-spring-demo
===========
Simple Annotation Based Spring Demo Web-Application for Cloud Foundry.
Dependencies
------------
- Running mysql database
- Maven
- Spring
- Hibernate
Usage
-----
Login to the Swisscom Application Cloud and switch to your Org and Space, then
mvn clean package
cf create-service mariadb small maria-d
cf push
Configuration
-------------
Local
If you want to connect to a mysql database which does not run on localhost or
your connection settings differ from the provided defaults, then you want to
modify the file `src/main/resources/application.properties`.
Cloud
In the class `SpringDemoWebApplication` it is assumed that exactly one
service instance is bound to this application (see JavaDoc comments). This
service instance is assumed to be mysql or mariadb. If these assumptions
are not valid, you want to modify the code.
Feedback
--------
Most welcome. Create pull-requests or contact me via email.
<file_sep>/*
* (c) Copyright 2014 Swisscom AG
* All Rights Reserved.
*/
package com.swisscom.cloud.demo.spring.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;
import com.swisscom.cloud.demo.spring.model.Person;
import com.swisscom.cloud.demo.spring.service.PersonService;
/**
* @author <NAME>
* @since 24.02.2014
*/
@Controller
public class PersonController {
@Autowired
private PersonService svc;
@RequestMapping(value = "/person", method = RequestMethod.GET)
public String getPersonList(ModelMap model) {
model.addAttribute("personList", svc.listPerson());
return "person-list";
}
@RequestMapping(value = "/person/save", method = RequestMethod.POST)
public View createPerson(@ModelAttribute Person person, ModelMap model) {
if (StringUtils.hasText(person.getId())) {
svc.updatePerson(person);
} else {
svc.addPerson(person);
}
return new RedirectView("/person", true);
}
@RequestMapping(value = "/person/delete", method = RequestMethod.GET)
public View deletePerson(@ModelAttribute Person person, ModelMap model) {
svc.deletePerson(person);
return new RedirectView("/person", true);
}
@RequestMapping(value = "/crash", method = RequestMethod.GET)
public void crashApp() {
// crash app
System.out.println("crashing...");
crashApplication();
}
public void crashApplication() {
Object[] o = null;
while (true) {
o = new Object[] {o};
}
}
}
<file_sep>$(document).foundation();
/*
* Init
*/
$(document).ready(function(){
loadSoundFile();
});
/*
* Not yet implemented
*/
function notYetImplemented() {
$("#soon").show();
}
/*
* Load images and activate Slick
*/
function readyToPlay() {
//$.getJSON("http://api.flickr.com/services/feeds/groups_pool.gne?id=998875@N22〈=en-us&format=json&jsoncallback=?", displayImages);
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "Swisscom",
format: "json"
},
displayImages);
playSound();
}
function displayImages(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).prependTo($("<div/>").attr("class", "hide").prependTo("#loadedImages"));
if ( i == 10 ) return false;
});
activateSlick();
}
function activateSlick() {
$('.slick-container').slick({
autoplay: true,
autoplaySpeed: 1000,
arrows: false,
fade: true//,
//centerMode: true
});
}
/*
* Sound
*/
var soundfile;
function loadSoundFile() {
soundfile = "http://cf-demo.beta.swisscloud.io/audio/wenn.mp3";
}
function playSound() {
//soundfile = "http://cf-demo.beta.swisscloud.io/audio/wenn.mp3";
el = $("#soundElement");
if (el.mp3) {
if(el.mp3.paused) el.mp3.play();
else el.mp3.pause();
} else {
el.mp3 = new Audio(soundfile);
el.mp3.play();
}
}
/*!
* jQuery Sticky Footer 1.1
* <NAME>
* http://tangerineindustries.com
*
* Released under the MIT license
*
* Copyright 2013 <NAME>.
*
* Date: Thu Jan 22 2013 13:34:00 GMT-0630 (Eastern Daylight Time)
* Modification for jquery 1.9+ Tue May 7 2013
* Modification for non-jquery, removed all, now classic JS Wed Jun 12 2013
*/
window.onload = function() {
stickyFooter();
//you can either uncomment and allow the setInterval to auto correct the footer
//or call stickyFooter() if you have major DOM changes
//setInterval(checkForDOMChange, 1000);
};
//check for changes to the DOM
function checkForDOMChange() {
stickyFooter();
}
//check for resize event if not IE 9 or greater
window.onresize = function() {
stickyFooter();
};
//lets get the marginTop for the <footer>
function getCSS(element, property) {
var elem = document.getElementsByTagName(element)[0];
var css = null;
if (elem.currentStyle) {
css = elem.currentStyle[property];
} else if (window.getComputedStyle) {
css = document.defaultView.getComputedStyle(elem, null).
getPropertyValue(property);
}
return css;
}
function stickyFooter() {
if (document.getElementsByTagName("footer")[0].getAttribute("style") !== null) {
document.getElementsByTagName("footer")[0].removeAttribute("style");
}
if (window.innerHeight != document.body.offsetHeight) {
var offset = window.innerHeight - document.body.offsetHeight;
var current = getCSS("footer", "margin-top");
if (isNaN(current) === true) {
document.getElementsByTagName("footer")[0].setAttribute("style","margin-top:0px;");
current = 0;
} else {
current = parseInt(current);
}
if (current+offset > parseInt(getCSS("footer", "margin-top"))) {
document.getElementsByTagName("footer")[0].setAttribute("style","margin-top:"+(current+offset)+"px;");
}
}
}
/*
! end sticky footer
*/ | 460ed0bb36ae407b96405cff540d9757ec5a9737 | [
"Markdown",
"Java",
"JavaScript"
] | 5 | Java | ringgi/cf-spring-demo | a1e8b8e144c41b3e6e562e091b2096f0c5ead0a3 | a0bb981d6b3deade3a25efb3d9429660589c208b | |
refs/heads/master | <file_sep>"""Module containing steps for sending POST requests to the /login endpoint."""
from uuid import uuid4
from aloe import step, world
from requests import get, delete
from features.helper import *
from features.helper.accounts_api import create_random_account
@step(r"I try to delete a user's account")
def delete_user_account(self):
create_random_account()
world.response = delete(url(f"/accounts/{world.username}"))
@step(r"I try to delete an account that doesn't exist")
def delete_non_existant_account(self):
world.username = uuid4()
world.response = delete(url(f"/accounts/{world.username}"))
@step(r"I try to delete all users' accounts")
def delete_all_accounts(self):
create_random_account()
world.initial_accounts = get(url("/accounts")).json()
world.response = delete(url("/accounts"))
@step(r"the user's account should be deleted")
def check_user_account_deleted(self):
expect(get(url(f"/accounts/{world.response}")).status_code).to(equal(404))
@step(r"no accounts should be deleted")
def check_response_login_status(self):
accounts = get(url("/accounts")).json()
expect(accounts).to(contain(*world.initial_accounts))
<file_sep>"""Module containing steps for sending POSt requests to the /login endpoint."""
from aloe import step, world
from requests import post
from features.helper import *
from features.helper.accounts_api import create_random_account
@step(r"I attempt to login with an? (in)?valid (\w+) and password combination")
def attempt_login(self, invalid, login):
json = create_random_account()
json = {key: json[key] for key in (login, "password")}
if invalid:
json["password"] = "<PASSWORD>"
world.response = post(url("/login"), json=json)
@step(r"I attempt to login without providing a password")
def attempt_no_password_login(self):
create_random_account()
world.response = post(url("/login"), json={"username": world.username})
@step(r"I provide an extra argument whilst attempting to login")
def attempt_login_with_extra_arg(self):
json = create_random_account()
del json["email"]
world.unexpected_argument = {"you": "can't login with this"}
json.update(world.unexpected_argument)
world.response = post(url("/login"), json=json)
@step(r"the response should contain a key suggesting that login was (un)?successful")
def check_response_login_status(self, unsuccessful):
success = str(not bool(unsuccessful)).lower()
expect(world.response.json()).to(equal({"success": success}))
<file_sep>"""Module containing code for the /login endpoint."""
from flask_restful import Resource, abort
from flask import request
from werkzeug.security import check_password_hash
from lib.accounts import find_account
class Login(Resource):
"""Class representing the /login endpoint in the API."""
def post(self):
"""Find out whether the given json credentials are valid."""
json = request.get_json()
login = json.pop("username", None) or json.pop("email", None)
if login is None:
abort(400, message="One of the following arguments are required: 'username', 'email'")
try:
password = json.pop("password")
except KeyError:
abort(400, message="The 'password' argument is required.")
if json:
abort(400, message=f"Unexpected arguments: {json}")
account = find_account(login)
if account is None:
abort(404, message=f"No account exists with username '{username}'.")
success = check_password_hash(account["password"], password)
json = {"success": str(success).lower()}
return json, 200 if success else 401
<file_sep>"""Module containing generic API response checking steps."""
from aloe import step, world
from expects import *
@step(r"I should get a (\d+) response")
def check_response(self, expected_response_code):
expect(world.response.status_code).to(equal(int(expected_response_code)))
<file_sep>from aloe import step, world
from features.helper import *
EXPECTED_MESSAGES = {
"account creation was successful":
"An account with username '{username}' was successfully created.",
"the username is already in use":
"An account already exists with username '{username}'.",
"usernames cannot contain @ symbols":
"The value of the 'username' field must not contain an '@' symbol.",
"a required argument was missing":
"The 'username', '<PASSWORD>' and 'email' arguments are required.",
"an unexpected argument was given":
"Unexpected arguments: {unexpected_argument}",
"the user does not exist":
"No account exists with username '{username}'.",
"the password argument was missing":
"The 'password' argument is required.",
}
@step("the response message should indicate that ((?:[\w@] ?)+)")
def check_message(self, message_purpose):
expected_message = EXPECTED_MESSAGES[message_purpose]
expected_message = expected_message.format(**world.__dict__)
expect(world.response.json()["message"]).to(equal(expected_message))
<file_sep>"""Module containing functions for accessing the database for the REST API."""
import sqlite3 as _sqlite
DATABASE_FILE = "api.db"
def sql(query):
"""Execute the given SQL query on the database."""
with _sqlite.connect(DATABASE_FILE) as connection:
return connection.cursor().execute(query)
def find_account(login):
"""Return the account with the given login or None if it doesn't exist."""
login = login.casefold()
login_type = "email" if "@" in login else "username"
sql("SELECT email, username, password"
"FROM accounts"
f"WHERE {login_type} = {login}")
def add_account(username, password, email):
"""Add the given account information to the database."""
sql("INSERT INTO accounts VALUES({username}, {password}, {email})")
<file_sep>Flask>=0.12.2
Flask-RESTful>=0.3.6
Werkzeug>=0.12.2
<file_sep>"""Module containing test execution steps for calling the accounts API."""
from requests import get, post
from aloe import step, world
from features.helper import * # pylint: disable=wildcard-import,unused-wildcard-import
from features.helper.accounts_api import post_account, generate_random_account_json
@step(r"I try to create an account ((?:[\w@] ?)+)")
def create_account_valid_request(self, condition):
json = generate_random_account_json()
if condition.startswith("without providing a"):
argument_name = condition.split()[-1]
del json[argument_name]
elif condition == "using a username with an @ symbol in it":
json["username"] += "@"
elif condition == "whilst providing an extra argument":
world.unexpected_argument = {"well,": "this is unexpected"}
json.update(world.unexpected_argument)
elif condition == "using a used username":
post_account(json) # Post account an extra time
post_account(json)
@step("an account with that username should be created")
def confirm_account_created(self):
expect(get(url(f"/accounts/{world.username}")).status_code).to(equal(200))
<file_sep>"""Module containing helper methods for accessing the /accounts endpoint of the API."""
from uuid import uuid4
from aloe import world
from requests import post
from features.helper import url
def generate_random_account_json():
"""Generate random credentials for creating an account with."""
world.username = str(uuid4())
world.password = str(<PASSWORD>())
world.email = f"{<EMAIL>"
return {"username": world.username, "password": <PASSWORD>, "email": world.email}
def post_account(json):
"""Send a POST request to the /accounts endpoint with the given json payload."""
world.response = post(url("/accounts"), json=json)
def create_random_account():
"""Create a random account and return the credentials."""
json = generate_random_account_json()
post_account(json)
return json
<file_sep># Proposals
* Make code comply with `pylint`.
* Use a database instead of the `ACCOUNTS` list.
* Try using `return {"message": message}, code` instead of `abort(code, message=message)`
* Use `before` hooks to create accounts for tests that need them,
or add a `Given` step to create them.
<file_sep>"""Module containing steps for sending GET requests to the /accounts endpoint."""
from uuid import uuid4
from aloe import step, world
from requests import get
from features.helper import *
from features.helper.accounts_api import create_random_account
@step(r"I try to get the details of an existing account")
def get_exisiting_account_details(self):
create_random_account()
world.response = get(url(f"/accounts/{world.username}"))
@step(r"the response should contain the user's public details")
def check_response_contains_user_details(self):
expect(world.response.json()).to(equal({"username": world.username}))
@step(r"I try to get the details of an account that doesn't exist")
def get_non_existant_account(self):
world.username = uuid4()
world.response = get(url(f"/accounts/{world.username}"))
@step(r"I try to get all the usernames that are currently in use")
def get_all_usernames(self):
world.usernames = [create_random_account()["username"] for _ in range(3)]
world.response = get(url("/accounts"))
@step(r"the response should contain a list of all used usernames")
def check_response_contains_existing_usernames(self):
expect(world.response.json()).to(contain(*world.usernames))
<file_sep>aloe>=0.1.15
expects>=0.8.0
requests>=2.18.4
<file_sep>from expects import *
from features.config import BASE_URL
# Helper functions
def url(path="/"):
"""Return the full url to the given path."""
return BASE_URL + path
<file_sep># Account Service RESTful API
Written using the Flask framework for Python.
<file_sep>"""Main file for running the accounts service API."""
from flask import Flask
from flask_restful import Api
from lib.accounts import Accounts, AccountsList
from lib.login import Login
app = Flask(__name__)
api = Api(app)
api.add_resource(AccountsList, "/accounts")
api.add_resource(Accounts, "/accounts/<username>")
api.add_resource(Login, "/login")
if __name__ == "__main__":
app.run(debug=True)
<file_sep>"""Module containing code for the /accounts endpoint."""
from flask_restful import Resource, abort
from flask_restful.reqparse import RequestParser
from flask import request
from werkzeug.security import generate_password_hash
ACCOUNTS = [] # TODO: replace with a database (SQL Alchemy?)
def find_account(login):
"""Return the account with the given login or None if it doesn't exist."""
login = login.casefold()
login_type = "email" if "@" in login else "username"
for account in ACCOUNTS:
if account[login_type].casefold() == login:
return account.copy()
return None
class Accounts(Resource):
"""Class representing the /accounts/{username} endpoint in the REST API."""
def get(self, username):
"""Get the details of the account with the given `username` parameter."""
account = find_account(username)
if account is None:
abort(404, message=f"No account exists with username '{username}'.")
# Remove email and password from response
account.pop("email")
account.pop("password")
return account
def delete(self, username):
"""Delete the account with the given username."""
account = find_account(username)
if account is None:
abort(404, message=f"No account exists with username '{username}'.")
ACCOUNTS.remove(account)
class AccountsList(Resource):
"""Class representing the base /accounts endpoint in the REST API."""
def get(self):
"""Get all existing account usernames."""
return [account["username"] for account in ACCOUNTS]
def post(self):
"""Add a new account."""
json = request.get_json()
try:
username = json.pop("username")
password = json.pop("<PASSWORD>")
email = json.pop("email")
except KeyError:
abort(400, message="The 'username', 'password' and 'email' arguments are required.")
if json:
abort(400, message=f"Unexpected arguments: {json}")
if "@" in username:
abort(422, message="The value of the 'username' field must not contain an '@' symbol.")
if find_account(username) is not None:
abort(409, message=f"An account already exists with username '{username}'.")
ACCOUNTS.append({
"username": username,
"password": <PASSWORD>_<PASSWORD>_<PASSWORD>(password),
"email": email,
})
json = {"message": f"An account with username '{username}' was successfully created."}
return json, 201
| 4bc7623d492091464c0219dd0fa004b96d6eab54 | [
"Markdown",
"Python",
"Text"
] | 16 | Python | AndyDeany/flask-rest-account-service | c4a66e329eb44e7e8a890da7785d93241c2b8c33 | 519e5d8e93e231806c135fb0bd59c7560ca311ef | |
refs/heads/master | <repo_name>york18/2031-C-and-shell-scripting<file_sep>/A2/Q2 (1)/allfiles
#!/bin/sh
# EECS2031 - asg2
# Filename: allfiles
# Author: <NAME>
# Email: <EMAIL>
# Login ID: york18
for f in *
do
if test -f $f
then
echo $f
fi
done
<file_sep>/A2/Q2 (1)/myutil
#!/bin/sh
# EECS2031 - asg2
# Filename: myutil
# Author: <NAME>
# Email: <EMAIL>
# Login ID: york18
menu
echo
echo -n "Enter command: "
while read command
do
case $command in
s | S) isearch;;
c | C) icount;;
f | F) allfiles;;
v | V) fdisplay;;
d | D) doublesp;;
a | A) addlines;;
l | L) prtlines;;
h | H) menu;;
r | R) clear;;
q | Q) exit 1;;
*) echo "Invalid command";;
esac
echo
echo -n "Enter command: "
done<file_sep>/A2/Q1 (1)/try1.c
#include <stdio.h>
#include <stdlib.h>
/***************** DO NOT USE ARRAY INDEXING *****************/
/************** USE ONLY POINTERS IN THIS FILE ***************/
int toString(char []);
int main()
{
char a[100];
int n;
printf("Input a valid string to convert to integer\n");
scanf("%s", a);
n = toString(a);
printf("String = %s\nInteger = %d\n", a, n);
return 0;
}
int toString(char a[]) {
int c, sign, offset, n;
if (a[0] == '-') { // Handle negative integers
sign = -1;
}
if (sign == -1) { // Set starting position to convert
offset = 1;
}
else {
offset = 0;
}
n = 0;
for (c = offset; a[c] != '\0'; c++) {
n = n * 10 + a[c] - '0';
}
if (sign == -1) {
n = -n;
}
return n;
}
/*
Save the three command-line arguments into nr1, nc1 and nc2.
*/
void get_args( char **argv, int *nr1, int *nc1, int *nc2 )
{
/*************** ADD YOUR CODE HERE ***************/
}
/*
Initialize a 2-dimensional array.
Element (i, j) is assigned value i+j.
*/
void initMatrix ( int **a, int nrows, int ncols )
{
/*************** ADD YOUR CODE HERE ***************/
}
/*
Multiply arrays a and b.
Array a has nr1 rows and nc1 columns.
Array b has nc1 rows and nc2 columns.
Allocate an array c having nr1 rows and nc2 columns.
Compute a x b and store the result in array c.
Return array c.
If an error occurs (e.g., insufficient memory), return NULL pointer.
*/
int **matrix_mult( int **a, int **b, int nr1, int nc1, int nc2 )
{
/*************** ADD YOUR CODE HERE ***************/
return( NULL ); /* replace this line with your code */
}
/************************* END OF FILE *************************/
<file_sep>/A2/Q2 (1)/icount
#!/bin/sh
# EECS2031 - asg2
# Filename: icount
# Author: <NAME>
# Email: <EMAIL>
# Login ID: york18
echo -n "Enter the file name: "
read filename
if test ! -f $filename
then
echo "File '$filename' does not exist."
elif test ! -r $filename
then echo "File '$filename' is not readable."
else
echo -n "Count lines, words, characters or all three (l, m, c, a)? "
read varname
until test $varname = l || test $varname = L || test $varname = m || test $varname = M || test $varname = c || test $varname = C || test $varname = a || test $varname = A
do
echo "Invalid option"
echo -n "Count lines, words, characters or all three (l, w, c, a)? "
read varname
done
if test $varname = l || test $varname = L
then
lines=`wc -l < $filename`
echo "File '$filename' contains $lines lines."
elif test $varname = m || test $varname = M
then
words=`wc -w < $filename`
echo "File '$filename' contains $words words."
elif test $varname = c || test $varname = C
then
characters=`wc -m < $filename`
echo "File '$filename' contains $characters characters."
elif test $varname = a || test $varname = A
then
lines=`wc -l < $filename`
words=`wc -w < $filename`
characters=`wc -m < $filename`
echo "File '$filename' contains $lines lines, $words words, $characters characters."
else
echo "Invalid option"
fi
fi<file_sep>/Labs/Lab4/lab4a.c
/***********************************
* EECS2031 - Lab 4
* Filename: lab4a.c
* Author: Last name, first name
* Email: Your preferred email address
* Login ID: Your login ID
************************************/
#include <stdio.h>
#define MAX_SIZE 500
void myStrInput ( char *s );
int myStrCmp( char *s1, char *s2 );
int main()
{
char strg1[ MAX_SIZE ], strg2[ MAX_SIZE ];
myStrInput( strg1 );
myStrInput( strg2 );
printf( "%d\n", myStrCmp( strg1, strg2 ));
return 0;
}
void myStrInput ( char *s )
{
int c = getchar();
int i = 0;
while(c != '\n')
{
*(s + i) = c;
i++;
c = getchar();
}
*(s + i) = '\0';
}
int myStrCmp( char *s1, char *s2 )
{
int i = 0;
for(; *(s1 + i) != '\0'; i++)
{
if(*(s1 + i) != *(s2 + i))
{
return i;
}
else
{
if(*(s1 + i + 1) == '\0' && *(s2 + i + 1) == '\0')
{
return -1;
}
}
}
return i;
}
<file_sep>/Labs/lab8/q2/mkpub
#!/bin/sh
if test -d $1
then
chmod a+rx $1
echo "Directory '$1' is now made public."
elif test -f $1
then
echo "File '$1' is now made public."
chmod a+r $1
else
echo "File '$1' does not exits."
fi
<file_sep>/A2/Q1 (1)/mm.c
/***********************************
* EECS 2031 - Assignment 2
* Filename: mm.c
* Author: <NAME>
* Email: <EMAIL>
* Login ID: york18
************************************/
#include <stdio.h>
#include <stdlib.h>
/***************** DO NOT USE ARRAY INDEXING *****************/
/************** USE ONLY POINTERS IN THIS FILE ***************/
static int** allocate2D( int nrows, int ncols )
{
int **array, i;
/* Allocate an array of pointers, each pointing to a row. */
array = ( int** ) malloc( nrows * sizeof( int* ) );
if ( array == NULL )
{
printf( "Insufficient memory!\n" );
exit ( 1 );
}
/* Allocate each row. */
for(i = 0; i < nrows; i++)
{
*(array + i) = ( int* ) malloc( ncols * sizeof( int ) );
if ( *(array + i) == NULL )
{
printf( "Insufficient memory!\n" );
exit ( 1 );
}
}
return( array );
}
/*
* Converts a char array into an int
*/
int toInt(char *a)
{
int c, sign, offset, n;
offset = 0;
if (*(a + 0) == '-') // Handle negative integers
{
sign = -1;
}
if (sign == -1) // Set starting position to convert
{
offset = 1;
}
else
{
offset = 0;
}
n = 0;
for (c = offset; *(a+c) != '\0'; c++)
{
n = n * 10 + *(a+c) - '0';
}
if (sign == -1)
{
n = -n;
}
return n;
}
/*
Save the three command-line arguments into nr1, nc1 and nc2.
*/
void get_args( char **argv, int *nr1, int *nc1, int *nc2 )
{
*nr1 = toInt(*(argv + 1));
*nc1 = toInt(*(argv + 2));
*nc2 = toInt(*(argv + 3));
}
/*
Initialize a 2-dimensional array.
Element (i, j) is assigned value i+j.
*/
void initMatrix ( int **a, int nrows, int ncols )
{
int i = 0;
for(; i < nrows; i++)
{
int j = 0;
for(; j < ncols; j++)
{
*(*(a + i) + j) = i + j;
}
}
}
/*
Multiply arrays a and b.
Array a has nr1 rows and nc1 columns.
Array b has nc1 rows and nc2 columns.
Allocate an array c having nr1 rows and nc2 columns.
Compute a x b and store the result in array c.
Return array c.
If an error occurs (e.g., insufficient memory), return NULL pointer.
*/
int **matrix_mult( int **a, int **b, int nr1, int nc1, int nc2 )
{
int **mm;
mm = allocate2D(nr1, nc2);
int sum = 0;
int i = 0;
int j = 0;
int k = 0;
for (i = 0; i < nr1; i++)
{
for (j = 0; j < nc2; j++)
{
for (k = 0; k < nc1; k++)
{
sum = sum + (*(*(a + i)+ k) * (*(*(b + k) + j)));
}
*(*(mm + i) + j) = sum;
sum = 0;
}
}
return( mm );
}
/************************* END OF FILE *************************/
<file_sep>/A1/Q1- Polynomial/poly.c
/***********************************
* EECS2031 - Assignment 1
* Filename: poly.c
* Author: <NAME>
* Email: <EMAIL>
* Login ID: york18
************************************/
#include "poly.h"
void toCharArray(int n1, char *s);
void sort( int coeff[ ], int exp[ ] );
int len = 0;
/*
Initialize all coefficients and exponents of the polynomial to zero.
*/
void init_polynom( int coeff[ ], int exp[ ] )
{
int i = 0;
for (; i < ASIZE; i++)
{
coeff[i] = exp[i]= 0;
}
} /* end init_polynom */
/*
Get inputs from user using scanf() and store them in the polynomial.
*/
void get_polynom( int coeff[ ], int exp[ ] )
{
int l = 0;
int total;
scanf("%d", &total);
while(total > 0)
{
scanf("%d", &coeff[l]);
scanf("%d", &exp[l]);
total--;
l++;
}
coeff[l] = '\0';
exp[l] = '\0';
} /* end get_polynom */
void sort( int coeff[ ], int exp[ ] )
{
int i = 0;
int j = 0;
int a;
int b;
for(; coeff[i] != '\0' || exp[i] != '\0'; i++)
{
j = 0;
for (j = i + 1; coeff[j] != '\0' || exp[j] != '\0'; j++)
{
if (exp[i] < exp[j])
{
a = exp[i];
b = coeff[i];
exp[i] = exp[j];
coeff[i] = coeff[j];
exp[j] = a;
coeff[j] = b;
}
}
}
}
/*
Convert the polynomial to a string s.
*/
void polynom_to_string( int coeff[ ], int exp[ ], char s[ ] )
{
int j = 0;
int k = 0;
int l = 0;
int boolean = 0;
for(; coeff[k] != '\0' || exp[k] != '\0';)
{
if(coeff[k] == 1 && exp[k] == '\0')
{
s[j] = '1';
j++;
}
else if(coeff[k] == -1 && exp[k] == '\0')
{
s[j - 1] = '-';
s[j] = '1';
j++;
}
else if(coeff[k] == 0)
{
/* do nothing */
}
else
{
l = 0;
char temp[ASIZE];
char temp2[ASIZE];
if(coeff[k] == 1)
{
/* don't do anything. Since coefficient 1 should not be printed */
}
else
{
if(coeff[k] == -1 && j != 0)
{
s[j - 1] = '-';
}
else
{
toCharArray(coeff[k], temp); /* If coeff[k] is not just a digit but a number > 9*/
for(; temp[l] != '\0'; l++)
{
/* s[j - 1] is initially '+' but since the next coefficient is negative '+' should not be printed but instaead '-' should be there*/
if((temp[l] == '-' && j != 0)) /*j!= 0 because if first coefficient is negative then s[j - 1] is out of bound*/
{
s[j - 1] = temp[l];
}
else
{
s[j] = temp[l];
j++;
}
}
}
}
if(exp[k] == 0)
{
/* don't do anything */
}
else
{
s[j] = 'x';
j++;
if(exp[k] == 1)
{
/* don't do anything */
}
else
{
s[j] = '^';
j++;
l = 0;
toCharArray(exp[k], temp2);
for(; temp2[l] != '\0'; l++)
{
s[j] = temp2[l];
j++;
}
}
}
/* print '+' only if there is a next element and if next element is 0 then no need to print it*/
if(coeff[k + 1] != '\0' || exp[k + 1] != '\0')
{
s[j] = '+';
j++;
}
}
k++;
}
if(j == 0)
{
s[j] = '0';
s[j + 1] = '\0';
}
else
{
s[j] = '\0';
}
} /* end polynom_to_string */
/* This method converts an integer into char Array */
void toCharArray(int n1, char *s)
{
char buffer[ASIZE];
int i = 0;
int len;
int booleanIsNeg = 0;
/* If integer is 0*/
if(n1 == 0)
{
s[0] = '0';
s[1] = '\0';
}
else
{
if(n1 < 0) /* negative number */
{
booleanIsNeg = 1;
n1 = -1 * n1;
}
for(; n1 != 0; i++)
{
buffer[i] = n1 % 10 + '0';
n1 = n1 / 10;
}
if(booleanIsNeg == 1)
{
buffer[i] = '-';
i++;
}
buffer[i] = '\0';
len = i;
int j = 0;
/* reverse the buffer array*/
for(; j != len; j++)
{
s[j] = buffer[i - 1];
i--;
}
s[j] = '\0';
}
}
/*
Evaluate the polynomial for the value of x and store the result p(x) in variable result.
*/
void eval_polynom(int coeff[ ], int exp[ ], double x, double *result )
{
int j = 0;
double dupx = x;
*result = 0;
for(; coeff[j] != '\0' || exp[j] != '\0'; j++)
{
int expo = exp[j];
if(expo == 0)
{
x = 1;
}
else
{
if(expo > 0)
{
if(expo == 1)
{
x = x;
}
else
{
while(expo != 1)
{
x = x * dupx;
expo--;
}
}
}
else
{
if(expo == -1)
{
x = 1 / x;
}
else
{
while(expo != -1)
{
x = x * dupx;
expo++;
}
x = 1 / x;
}
}
}
double intermediate = coeff[j] * x;
*result = *result + intermediate;
x = dupx;
}
} /* end eval_polynom */
/*
Add two polynomials and the result is stored in the first polynomial (arrays co1[] and ex1[]).
*/
void add_polynom( int co1[ ], int ex1[ ], int co2[ ], int ex2[ ] )
{
sort(co1, ex1);
sort(co2, ex2);
int co2b[ASIZE];
int ex2b[ASIZE];
len = 0;
int length1 = 0; /* to store length of polynomial 1 */
int length2 = 0; /* (to store length of co2 which is same as ex2) || (to store length of plynomial 2) */
while(co1[length1] != '\0'|| ex1[length1] != '\0')
{
length1++;
}
while(co2[length2] != '\0'|| ex2[length2] != '\0')
{
length2++;
}
int index = 0;
while(index < length2)
{
co2b[index] = co2[index];
index++;
}
index = 0;
while(index < length2)
{
ex2b[index] = ex2[index];
index++;
}
int i = 0;
int k = 0;
if(length1 == 0)
{
co1[length1] = co2[length2];
length1++;
}
/* doing addition of the exponents with 0 first*/
if(ex1[length1 - 1] == ex2[length2 - 1] && ex1[length1 - 1] == 0)
{
int d = co1[length1 - 1] + co2[length2 - 1]; /* add the two coffecients of the same exponents */
co1[length1 - 1] = d;
co2[length2 - 1] = 0; /*turning the coefficient into 0 since its addition is done*/
}
for(; co1[i] != '\0' || ex1[i] != '\0'; i++)
{
int j = 0;
for(; j < length2; j++)
{
if(ex1[i] == ex2[j] && ex1[i] != 0)
{
int d = co1[i] + co2[j]; /* add the two coffecients of the same exponents */
co1[i] = d;
co2[j] = 0; /*turning the coefficient into 0 since its addition is done*/
ex2[j] = 0; /*turning the exponent into 0 since its addition is done*/
}
}
}
/* adding remaining elements of second polynomial to first one*/
for(; k < length2; k++)
{
if(co2[k] != 0 || ex2[k] != 0)
{
co1[i] = co2[k];
ex1[i] = ex2[k];
i++;
}
}
ex1[i] = '\0';
co1[i] = '\0';
len = i;
index = 0;
while(index < length2)
{
co2[index] = co2b[index];
index++;
}
index = 0;
while(index < length2)
{
ex2[index] = ex2b[index];
index++;
}
sort(co1, ex1);
} /* end add_ polynom */
/************************** END OF FILE ***************************/
<file_sep>/A2/Q2 (1)/menu
#!/bin/sh
# EECS2031 - asg2
# Filename: menu
# Author: <NAME>
# Email: <EMAIL>
# Login ID: york18
echo "=================== MENU ==================="
echo "s: Search for a word"
echo "c: Count lines, words, characters"
echo "f: List all ordinary files in current directory"
echo "v: View content of a file"
echo "d: Double spacing"
echo "a: Add line numbers"
echo "l: Display specified lines in file"
echo "h: Help / Display this menu"
echo "r: Clear the screen"
echo "q: Quit the program"
echo "============================================"<file_sep>/Labs/Lab 6/calc.c
/***********************************
* EECS 2031 - Lab 6
* Filename: calc.c
* Author: Last name, first name
* Email: Your preferred email address
* Login ID: Your EECS login ID
************************************/
#include <stdio.h>
#include <stdlib.h>
/***** YOU MAY ADD YOUR OWN FUNCTION(S) HERE. *****/
int stringToInt(char a[])
{
int c, sign, offset, n;
if (a[0] == '-') { // Handle negative integers
sign = -1;
}
if (sign == -1) { // Set starting position to convert
offset = 1;
}
else {
offset = 0;
}
n = 0;
for (c = offset; a[c] != '\0'; c++) {
n = n * 10 + a[c] - '0';
}
if (sign == -1) {
n = -n;
}
return n;
}
/* Implement a simple calculator.
Input: two operands and one operator as command-line arguments.
Output: the result displayed on the standard output.
*/
void main( int argc, char *argv[] )
{
int result = 0; /* stores the result of the arithmetic operation */
/*****************************************/
/***** ADD YOUR CODE BELOW THIS LINE *****/
if(argc <= 1)
{
printf("Usage: calc [operand_1] [operator] [operand_2]\n");
}
else
{
int operand1 = stringToInt(argv[1]);
int operand2 = stringToInt(argv[3]);
char operator = argv[2][0];
if(operator == '+')
{
result = operand1 + operand2;
}
else if(operator == '-')
{
result = operand1 - operand2;
}
else if(operator == 'x')
{
result = operand1 * operand2;
}
else if(operator == '/')
{
result = operand1 / operand2;
}
else
{
result = operand1 % operand2;
}
/***** ADD YOUR CODE ABOVE THIS LINE *****/
/*****************************************/
/**** DO NOT ADD OR CHANGE ANYTHING BELOW THIS LINE ****/
printf( "%d\n", result );
}
}
<file_sep>/Labs/lab8/q2/phone
#!/bin/sh
echo -n "Enter the name to search: "
read name
grep -i $name phone_book.txt
<file_sep>/A2/Q2 (1)/fdisplay
#!/bin/sh
# EECS2031 - asg2
# Filename: fdisplay
# Author: <NAME>
# Email: <EMAIL>
# Login ID: york18
echo -n "Enter the file name: "
read filename
if test ! -f $filename
then
echo "File '$filename' does not exist."
elif test ! -r $filename
then
echo "File '$filename' is not readable."
else
echo -n "Enter option (e, p, f, l): "
read varname
until test $varname = e || test $varname = E || test $varname = p || test $varname = P || test $varname = f || test $varname = F || test $varname = l || test $varname = L
do
echo "Invalid option"
echo -n "Enter option (e, p, f, l): "
read varname
done
if test $varname = e || test $varname = E
then
cat $filename
elif test $varname = p || test $varname = P
then
cat $filename | more
elif test $varname = f || test $varname = F
then
head $filename
elif test $varname = l || test $varname = L
then
tail $filename
else
echo "Invalid option"
fi
fi<file_sep>/A2/Q2 (1)/isearch
#!/bin/sh
# EECS2031 - asg2
# Filename: isearch
# Author: <NAME>
# Email: <EMAIL>
# Login ID: york18
echo -n "Enter the file name: "
read filename
if test ! -f $filename
then
echo "File '$filename' does not exist."
elif test ! -r $filename
then echo "File '$filename' is not readable."
else
echo -n "Enter the word to search for: "
read searchword
echo -n "Case sensitive (y/n)? "
read varname
until test $varname = "y" || test $varname = "Y" || test $varname = "n" || test $varname = "N"
do
echo "Invalid option"
echo -n "Case sensitive (y/n)? "
read varname
done
if test $varname = "y" || test $varname = "Y"
then
grep $searchword $filename
elif test $varname = "n" || test $varname = "N"
then
grep -i $searchword $filename
fi
if test $? -ne 0
then
echo "Word '$searchword' not found."
fi
fi
<file_sep>/Labs/lab8/q2/mkpub2
#!/bin/sh
for name in $*
do
mkpub $1
shift
done
<file_sep>/Labs/Lab7/marks.c
/***********************************
* EECS 2031 - Lab 7
* Filename: marks.c
* Author: Last name, first name
* Email: Your preferred email address
* Login ID: Your EECS login ID
************************************/
#include <stdio.h>
#include <stdlib.h>
void main( int argc, char *argv[] )
{
/*****************************************/
/***** ADD YOUR CODE BELOW THIS LINE *****/
if(argc < 3)
{
printf("Usage: marks [input_file] [output_file]\n");
}
else
{
FILE *ifile, *ofile;
ifile = fopen( argv[1], "r" );
if ( ifile == NULL )
{
printf("File empty!\n");
exit(1);
}
ofile = fopen( argv[2], "w" );
if ( ofile == NULL )
{
printf("No write permission!\n");
exit(1);
}
char fname[30], lname[30];
int asg1;
int asg2;
float avg;
while ( fscanf( ifile, "%s %s %d %d", &fname, &lname, &asg1, &asg2 ) != EOF )
{
avg = (float) (asg1 + asg2) / 2;
fprintf( ofile, "%s %s %d %d %.1f\n", fname, lname, asg1, asg2, avg);
}
}
/***** ADD YOUR CODE ABOVE THIS LINE *****/
/*****************************************/
} /* end main */
<file_sep>/Labs/lab8/q2/calc~
#!/bin/sh
if test $2 = "+"
then
echo `expr $1 + $3`
elif test $2 = "-"
then
echo `expr $1 - $3`
elif test $2 = "x"
then
echo `expr $1 * $3`
elif test $2 = "/"
then
echo `expr $1 / $3`
else
echo `expr $1 % $3`
fi
<file_sep>/README.md
# 2031-C-and-shell-scripting<file_sep>/A1/Q1- Polynomial/poly.h
/***********************************
* EECS2031 - Assignment 1
* Filename: poly.h
* Author: <NAME>
************************************/
#include <stdio.h>
#define ASIZE 50
<file_sep>/Labs/lab8/q2/phone2
#!/bin/sh
grep -i $1 phone_book.txt<file_sep>/A2/Q2 (1)/prtlines
#!/bin/sh
# EECS2031 - Lab 8
# Filename: prtlines
# Author: <NAME>
# Email: <EMAIL>
# Login ID: york18
echo -n "Enter file name: "
read filename
if test ! -f $filename
then
echo "File '$filename' does not exist."
elif test ! -r $filename
then echo "File '$filename' is not readable."
else
size=`wc -l < $filename`
echo "File '$filename' has $size lines."
echo -n "From line: "
read x
while test `expr $x` -le `expr 0` || test `expr $x` -gt `expr $size`
do
echo "Invalid line number"
echo -n "From line: "
read x
done
echo -n "To line: "
read y
while test `expr $y` -le `expr 0` || test `expr $y` -gt `expr $size` || test `expr $y` -lt `expr $x`
do
echo "Invalid line number"
echo -n "To line: "
read y
done
last=`expr $y - $x + 1`
count=1
while test `expr $count` -le $last
do
echo -n "$x: "
echo -n "`head -$x phone_book.txt | tail -1`"
echo
count=`expr $count + 1`
x=`expr $x + 1`
done
fi
<file_sep>/Labs/Lab4/lab4b.c
/***********************************
* EECS2031 - Lab 4
* Filename: lab4b.c
* Author: Last name, first name
* Email: Your email address
* Login ID: Your EECS login ID
************************************/
#include <stdio.h>
#define MAX_SIZE 100
main() {
char my_strg[ MAX_SIZE ];
double my_number = 0.0;
/********** Fill in your code here. **********/
int c, i = 0;
int n = 0; /* number of fractional digits */
double frac = 0.0;
/* Input a string */
while ( ( c = getchar() ) != '\n' )
my_strg[ i++ ] = c;
my_strg[ i ] = '\0';
/* Convert the string to a double */
for( i = 0; my_strg[ i ] != '.'; i++ )
my_number = my_number * 10 + ( my_strg[ i ] - '0' );
/* At this point, my_strg[i] == '.' and my_number contains the integer part. */
/* Process the fractional part */
for( i++, n = 0; my_strg[ i ] != '\0'; i++, n++ )
frac = frac * 10 + ( my_strg[ i ] - '0' );
/* At this point, my_strg[i] == '\0' */
/* Adjust the fractional part */
for( i = 1; i <= n; i++ )
frac /= 10;
my_number += frac;
/*********************************************/
printf( "%.6f\n", my_number );
}
<file_sep>/Labs/lab8/q2/mkpub2~
#!/bin/sh
for name in $*
do
shift
mkpub $0
done
<file_sep>/A2/Q2 (1)/myutil2 not used
#!/bin/sh
# EECS2031 - asg2
# Filename: myutil
# Author: <NAME>
# Email: <EMAIL>
# Login ID: nehamo
menu
echo
echo -n "Enter command: "
read command
until test $command = q || test $command = Q
do
if test $command = s || test $command = S
then
isearch
elif test $command = c || test $command = C
then
icount
elif test $command = f || test $command = F
then
allfiles
elif test $command = v || test $command = V
then
fdisplay
elif test $command = d || test $command = D
then
doublesp
elif test $command = a || test $command = A
then
addlines
elif test $command = l || test $command = L
then
prtlines
elif test $command = h || test $command = H
then
menu
elif test $command = r || test $command = R
then
clear
else
echo "Invalid command"
fi
echo
echo -n "Enter command: "
read command
done
if test $command = q || test $command = Q
then
exit 1
fi
<file_sep>/A2/Q2 (1)/doublesp
#!/bin/sh
# EECS2031 - asg2
# Filename: doublesp
# Author: <NAME>
# Email: <EMAIL>
# Login ID: york18
echo -n "Enter input file name: "
read fileinput
if test ! -f $fileinput
then
echo "File '$fileinput' does not exist."
elif test ! -r $fileinput
then echo "File '$fileinput' is not readable."
else
echo -n "Enter output file name: "
read fileoutput
if test -f $fileoutput && test ! -w $fileoutput
then
echo "File '$fileoutput' not writable."
exit 1
fi
if test ! -f $fileoutput
then
touch $fileoutput
size=`wc -l < $fileinput`
count=1
while test `expr $count` -le `expr $size`
do
(head -$count $fileinput | tail -1) >> $fileoutput
(echo;echo) >> $fileoutput
count=`expr $count + 1`
done
elif test -f $fileoutput
then
echo "File '$fileoutput' exists."
echo -n "Append to it (y/n)? "
read append
until test $append = "y" || test $append = "Y" || test $append = "n" || test $append = "N"
do
echo "Invalid option"
echo -n "Append to it (y/n)? "
read append
done
if test $append = y || test $append = Y
then
size=`wc -l < $fileinput`
count=1
while test `expr $count` -le `expr $size`
do
(head -$count $fileinput | tail -1) >> $fileoutput
(echo;echo) >> $fileoutput
count=`expr $count + 1`
done
elif test $append = "n" || test $append = "N"
then
exit 1
else
echo "Invalid option"
fi
fi
fi
| b0fdade4a6eb0da119cf8d2c99e9bf5305e37275 | [
"Markdown",
"C",
"Shell"
] | 24 | Shell | york18/2031-C-and-shell-scripting | db35d4a823441e9767c12bd19b8959a7d9d2e39b | c7a46a235a6613fd134590097416fb86a58e82c5 | |
refs/heads/master | <file_sep>// variables
var swRegistration;
var isSubscribed;
const publicServerKey = '<KEY>';
const subscribeButton = document.querySelector('#btnSubscribe');
// register service worker
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Push notification supported!');
navigator.serviceWorker.register('sw.js')
.then(function(swReg){
console.log('Service worker registered successfully!');
swRegistration = swReg;
initUI();
}).catch(function(err) {
console.error('Service Worker not registered ' + err);
});
} else {
console.error('Push notification NOT supported!')
}
// initialize UI and get subscription details
function initUI() {
subscribeButton.addEventListener('click', function() {
subscribeButton.disabled = true;
if (isSubscribed) {
unsubscribeUser();
} else {
subscribeUser();
}
});
// tries to get details of active subscription
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
isSubscribed = !(subscription === null);
if (isSubscribed) {
console.log('User\'s subscription is active!');
// write to output subscription details
console.log(JSON.stringify(subscription));
} else {
console.log('User is not subscribed!');
}
updateSubscriptionButton();
});
}
// refreshes the state of the "Subscribe / unsubscribe" button
function updateSubscriptionButton() {
if (isSubscribed) {
subscribeButton.textContent = 'Unsubscribe';
} else {
subscribeButton.textContent = 'Subscribe';
}
subscribeButton.disabled = false;
}
// subscribe user
function subscribeUser() {
var publicKey = urlB64ToUint8Array(publicServerKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: publicKey
}).then(function(subscription){
isSubscribed = true;
console.log('User successfully subscribed');
console.log(JSON.stringify(subscription));
updateSubscriptionButton();
registerSubscriptionOnServer(subscription);
}).catch(function(err) {
console.log('Unable to subscribe user ', err);
});
}
// unsubscribe user
function unsubscribeUser() {
var subscriptionObject;
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
subscriptionObject = subscription;
return subscription.unsubscribe();
}
}).catch(function(err) {
console.error('Cannot unsubscribe user ', err);
}).then(function() {
// unsegister user on server
console.log("User successfully unsubscribed");
isSubscribed = false;
unregisterSubscriptionOnServer(subscriptionObject);
updateSubscriptionButton();
});
}
function registerSubscriptionOnServer(subscription) {
fetch('/registerSubscription', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
subscription: subscription,
})
});
}
function unregisterSubscriptionOnServer(subscription) {
fetch('/unregisterSubscription', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
subscription: subscription,
})
});
}
// converts VAPID public key to UInt 8 bit array required to subscribe user
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}<file_sep>// Register event listener for the 'push' event.
self.addEventListener('push', function(event) {
console.log('Received a push message', event);
var data = event.data.json();
console.log(JSON.stringify(data));
// Keep the service worker alive until the notification is created.
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon,
vibrate: data.vibrate,
actions: data.actions,
requireInteraction: data.requireInteraction
})
);
});
self.addEventListener('notificationclick', function(event) {
event.notification.close();
if (event.action === 'yes') {
console.log('Clicked yes');
} else if (event.action === 'no') {
console.log('Clicked no');
} else {
console.log('Clicked nothing');
}
});
self.addEventListener('notificationclose', function(event) {
console.log('Closed');
});<file_sep>var reqInt = false; // require interaction
function sendBasicPushMessage() {
// TO DO simple push done
// push with icon - done
// push with vibration
// push with actions
// pust to specified users
fetch('/api/send-push', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
data: JSON.stringify({title: 'Simple push notification',
body: 'This is what a basic push notification looks like.',
requireInteraction: reqInt
})
})
}).then((response) => {
console.log(response);
});
}
function sendPushMessageWithIcon() {
fetch('/api/send-push', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
data: JSON.stringify({title: 'Push notification with icon',
body: 'This is what a push notification with icon looks like.',
icon: './web_app/images/notification.png',
requireInteraction: reqInt
})
})
}).then((response) => {
console.log(response);
});
}
function sendPushMessageWithVibrating() {
fetch('/api/send-push', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
data: JSON.stringify({title: 'Push notification with vibrating',
body: 'This is what a push notification with vibrating.',
icon: './web_app/images/vibrating.png',
vibrate: [200, 100, 200, 100, 200, 100, 200],
requireInteraction: reqInt
})
})
}).then((response) => {
console.log(response);
});
}
function sendPushMessageWithAction() {
fetch('/api/send-push', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
data: JSON.stringify({title: 'Push notification with Action',
body: 'This is what a push notification with Action',
icon: './web_app/images/like_demo.png',
vibrate: [200, 100, 300, 100, 200, 100, 400],
actions: [{ "action": "yes", "title": "Yes!!!", "icon": "./web_app/images/yes.png" },
{ "action": "no", "title": "No!!!", "icon": "./web_app/images/no.png" }],
requireInteraction: reqInt
})
})
}).then((response) => {
console.log(response);
});
}
function sendPushMessageWithCustomBadge() {
fetch('/api/send-push', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
data: JSON.stringify({title: 'Push notification with Custom Badge',
body: 'This is what a push notification with custom badge',
icon: './web_app/images/coffee.png',
badge: './web_app/images/coffee-beans.png',
vibrate: [200, 100, 300, 100, 200, 100, 400],
requireInteraction: reqInt
})
})
}).then((response) => {
console.log(response);
});
}
function initUI() {
const basicPushNotificationBtn = document.querySelector('#btnSimplePush');
basicPushNotificationBtn.addEventListener('click', () => {
sendBasicPushMessage();
});
const pushNotificationWithIconBtn = document.querySelector('#btnPushWithIcon');
pushNotificationWithIconBtn.addEventListener('click', () => {
sendPushMessageWithIcon();
});
const pushNotificationWithVibratingBtn = document.querySelector('#btnPushWithVibrating');
pushNotificationWithVibratingBtn.addEventListener('click', () => {
sendPushMessageWithVibrating();
});
const pushNotificationWithCustomBadge = document.querySelector('#btnPushWithCustomBadge');
pushNotificationWithCustomBadge.addEventListener('click', () => {
sendPushMessageWithCustomBadge();
});
const pushNotificationWithActionBtn = document.querySelector('#btnPushNotificationWithAction');
pushNotificationWithActionBtn.addEventListener('click', () => {
sendPushMessageWithAction();
});
const requireInteractionsCheckbox = document.querySelector('#chbRequireInteraction');
requireInteractionsCheckbox.addEventListener('click', () => {
reqInt = requireInteractionsCheckbox.checked;
});
}
window.addEventListener('load', () => {
initUI();
}); | 121b3ee0dba2560cf214985078a08cce119ba777 | [
"JavaScript"
] | 3 | JavaScript | msuskadev/pwa-push-demo | e8ebdd969d911d505973e3cc5ac08d03a7045344 | 8cd259210a8c3605eaa1636c78020c1d8dc090fa | |
refs/heads/master | <repo_name>gaku123/Muda<file_sep>/app/src/main/java/com/ifive/muda/MudaFragment.java
package com.ifive.muda;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MudaFragment extends Fragment {
private MudaChishiki muda;
private TextView title,content;
public MudaFragment() {
// Required empty public constructor
}
public static MudaFragment newInstance() {
return new MudaFragment();
}
public void setMudaChishiki(MudaChishiki muda) {
this.muda = muda;
muda.update(this);
}
public MudaChishiki getMudaChishiki() {
return muda;
}
public void update() {
title.setText(muda.title);
content.setText(muda.content);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
muda = new MudaChishiki(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_muda, container, false);
title = (TextView)rootView.findViewById(R.id.title);
content = (TextView)rootView.findViewById(R.id.content);
return rootView;
}
}
| 7b06b92638ab7d26b912f163384568128d63939c | [
"Java"
] | 1 | Java | gaku123/Muda | 8ef1c961f966e35dee989e3c881989b8361f8bea | c6769729c8d22a135d6b2f3cf836173169c64b24 | |
refs/heads/master | <file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 4 21:11:07 2018
@author: Gavin
"""
import calendar
import sys
import requests
from tkinter import *
from tkinter.filedialog import askdirectory
from tkinter import simpledialog
from tkinter import ttk
import datetime
import os
class NEISS_Data_Requester(object):
def __init__(self, master):
self.firstyear = 1997
self.curyear = datetime.datetime.today().year
self.years=[]
self.data=[]
self.case=[]
self.num_cases=0
self.num_n_cases=0
self.master=master
self.progress=ttk.Progressbar(self.master, orient=HORIZONTAL, length=100, mode='determinate')
# self.progress2=ttk.Progressbar(self.master, orient=HORIZONTAL, length=100, mode='determinate')
self.data_years=StringVar()
self.data_years.set("Years of Data Loaded=\nNone")
self.data_events=StringVar()
self.data_events.set("Number of Injury Events Loaded=\nNone")
self.data_loaded=False
self.file_to_dl=False
### Data loaded string
self.load_str=StringVar()
self.load_str.set("Datasets Loaded=\n"+str(self.data_loaded))
### Download availablity string
self.dl_str=StringVar()
self.dl_str.set("File Ready To Download=\n"+str(self.file_to_dl))
### Progress Bar String
self.progress_str=StringVar()
self.progress_str.set("Ready")
### Dates
self.date1=[]
self.date1_label=StringVar()
self.date1_label.set("Choose Date(s)")
# self.entry1=StringVar()
# self.entry1.set("(MM/DD/YYYY)or(MM/DD/YYYY-MM/DD/YYYY)")
### Age
self.entry2=StringVar()
self.entry2.set("singlular(#) or range(#-#)")
### Narrative
self.entry14=StringVar()
self.entry14.set("Enter as: Word1,Word2,ect...")
### PSU
self.entry16=StringVar()
self.entry16.set("Enter as: 1,2,3,...,100")
### Count Cases vs Non-Cases
self.case_num=StringVar()
self.case_num.set("Number of Cases:"+str(self.num_cases)+" Number of Non-Cases:"+str(self.num_n_cases))
### Sex
self.m1i1=IntVar()
self.m1i2=IntVar()
self.m1i3=IntVar()
### Race
self.m2i1=IntVar()
self.m2i2=IntVar()
self.m2i3=IntVar()
self.m2i4=IntVar()
self.m2i5=IntVar()
self.m2i6=IntVar()
self.m2i7=IntVar()
### Location
self.m3i1=IntVar()
self.m3i2=IntVar()
self.m3i3=IntVar()
self.m3i4=IntVar()
self.m3i5=IntVar()
self.m3i6=IntVar()
self.m3i7=IntVar()
self.m3i8=IntVar()
self.m3i9=IntVar()
### Fire Involvement
self.m4i1=IntVar()
self.m4i2=IntVar()
self.m4i3=IntVar()
self.m4i4=IntVar()
#Hospital Stratum
self.m5i1=IntVar()
self.m5i2=IntVar()
self.m5i3=IntVar()
self.m5i4=IntVar()
self.m5i5=IntVar()
### Disposition
self.m6i1=IntVar()
self.m6i2=IntVar()
self.m6i3=IntVar()
self.m6i4=IntVar()
self.m6i5=IntVar()
self.m6i6=IntVar()
self.m6i7=IntVar()
path="diagnosis.tsv"
with open(path,'r') as f:
self.diag=[]
self.diag_nums=[]
for row in f:
temp=row.split("\t")
self.diag.append("=".join(temp))
self.diag_nums.append(str(int(temp[0])))
self.diag_data={}
path="body_parts.tsv"
with open(path,'r') as f:
self.body=[]
self.body_nums=[]
for row in f:
temp=row.split("\t")
self.body.append("=".join(temp))
self.body_nums.append(str(int(temp[0])))
self.body_data={}
path="product_codes.tsv"
with open(path,'r') as f:
self.prdcts=[]
self.prdct_nums=[]
for row in f:
temp=row.split("\t")
self.prdcts.append("=".join(temp))
self.prdct_nums.append(str(int(temp[0])))
self.prd_data={}
self.nyears=[str(year) for year in range(self.firstyear,self.curyear)]
self.nyears_data={}
def updateProgress(self, number, total):
if(total==0):
number=0
total=1
value=int((number/total)*100)
self.progress['value']=value
self.master.update()
# Needed to remove this method because it take way too long... maybe multithread it?
def updateProgress2(self, number, total):
value=int((number/total)*100)
self.progress2['value']=value
self.master.update_idletasks()
# Get a file based on a URL and cache it locally
# if already exists, we don't have to go to the web for it
def getFile(self,url):
filesize_r = requests.head(url)
size_b = int(filesize_r.headers['content-length'])
chunks = int(size_b / 1024)
local_filename = ".cache/"+url.split('/')[-1]
# Should check filesize here as well
if ( not os.path.isfile(local_filename)
or os.path.getsize(local_filename) != size_b
):
self.progress_str.set("Downloading {0}".format(url.split('/')[-1]))
r = requests.get(url, stream=True)
if not os.path.exists(os.path.dirname(local_filename)):
os.makedirs(os.path.dirname(local_filename))
with open(local_filename,'wb') as f:
chunk_count = 0
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
chunk_count += 1
if chunk_count % 1000 == 0:
self.updateProgress(chunk_count,chunks)
return local_filename
def loadFiles(self):
self.master.update_idletasks()
self.data=[]
years_down=[]
# Dictionary comprehension that reduces years to only the ones checked
years = {key:value for (key,value) in self.nyears_data.items() if value.get() == 1}
for year in years.keys():
self.progress_str.set("Loading {0}".format(year))
if self.nyears_data[year].get() == 1:
url = 'https://www.cpsc.gov/cgibin/NEISSQuery/Data/Archived%20Data/{0}/neiss{0}.tsv'.format(year)
filename = self.getFile(url)
r_data=open(filename,'r',encoding="ISO-8859-1").readlines()
if(len(self.data)==0):
for row in r_data:
self.data.append(row.split("\t"))
else:
for row in range(1,len(r_data)):
self.data.append(r_data[row].split("\t"))
years_down.append(year)
self.data_loaded=True
self.file_to_dl=True
# self.status_str.set("Status: Datasets Loaded="+str(self.data_loaded)+
# "File Ready To Download="+str(self.file_to_dl)+
# "Years of Data Loaded="+str(years_down)+
# "Number of Injury Events Loaded="+str(len(self.data)-1)+
# "Number of Cases:"+str(self.num_cases)+" Number of Non-Cases:"+str(self.num_n_cases))
self.progress_str.set("Data loaded")
self.data_years.set("Years of Data Loaded=\n"+str(years_down))
self.data_events.set("Number of Injury Events Loaded=\n"+str(len(self.data)-1))
self.load_str.set("Datasets Loaded=\n"+str(self.data_loaded))
self.dl_str.set("File Ready To Download=\n"+str(self.file_to_dl))
self.master.update_idletasks()
### This version of loading NEISS data is my cheating method - before Nick and Andy gave me the link used above
def oldloadFiles(self):
self.data=[]
years_down=[]
if(len(self.years)>0):
tot_years=0
for year in self.years:
if(year[1]==1):
tot_years+=1
load_count=0
for i in range(len(self.years)):
if(self.years[i][1]==1):
years_down.append(self.years[i][0])
# temp=[]
# Example of the http: https://raw.githubusercontent.com/gblyth/NEISS_GUI/master/Bin%20Files/NEISS_1998Q1.bin
r=requests.get('https://raw.githubusercontent.com/gblyth/NEISS_GUI/master/Bin%20Files/NEISS_'+
self.years[i][0]+'Q1.bin')
r_data=r.text.split("\n")
if(len(self.data)==0):
for row in r_data:
self.data.append(row.split("\t"))
else:
for row in range(1,len(r_data)):
self.data.append(r_data[row].split("\t"))
load_count+=1
self.updateProgress(load_count,(tot_years*4))
r=requests.get('https://raw.githubusercontent.com/gblyth/NEISS_GUI/master/Bin%20Files/NEISS_'+
self.years[i][0]+'Q2.bin')
r_data=r.text.split("\n")
for row in range(1,len(r_data)):
self.data.append(r_data[row].split("\t"))
load_count+=1
self.updateProgress(load_count,(tot_years*4))
r=requests.get('https://raw.githubusercontent.com/gblyth/NEISS_GUI/master/Bin%20Files/NEISS_'+
self.years[i][0]+'Q3.bin')
r_data=r.text.split("\n")
for row in range(1,len(r_data)):
self.data.append(r_data[row].split("\t"))
load_count+=1
self.updateProgress(load_count,(tot_years*4))
r=requests.get('https://raw.githubusercontent.com/gblyth/NEISS_GUI/master/Bin%20Files/NEISS_'+
self.years[i][0]+'Q4.bin')
r_data=r.text.split("\n")
for row in range(1,len(r_data)):
self.data.append(r_data[row].split("\t"))
load_count+=1
self.updateProgress(load_count,(tot_years*4))
# self.data.append(temp)
print("Years downloaded are:\n",years_down)
self.data_loaded=True
self.file_to_dl=True
# self.status_str.set("Status: Datasets Loaded="+str(self.data_loaded)+
# "File Ready To Download="+str(self.file_to_dl)+
# "Years of Data Loaded="+str(years_down)+
# "Number of Injury Events Loaded="+str(len(self.data)-1)+
# "Number of Cases:"+str(self.num_cases)+" Number of Non-Cases:"+str(self.num_n_cases))
self.data_years.set("Years of Data Loaded=\n"+str(years_down))
self.data_events.set("Number of Injury Events Loaded=\n"+str(len(self.data)-1))
self.load_str.set("Datasets Loaded=\n"+str(self.data_loaded))
self.dl_str.set("File Ready To Download=\n"+str(self.file_to_dl))
self.master.update_idletasks()
def setFileName(self):
root=Tk()
cmd = """osascript -e 'tell app "Finder" to set frontmost of process "Python" to true'"""
os.system(cmd)
root.withdraw()
new_window=simpledialog.askstring("File Name","Please Name Your File:")
root.destroy()
return new_window
def downloadFiles(self):
place=askdirectory()
# print("Place=",place)
if(place!=""):
name=self.setFileName()
if(type(name)==str):
name=name.split(" ")
name="_".join(name)
# print("Name=",name)
path=place+"/"+name
print("File path=\n",path)
output_file=open(str(str(place)+"/"+str(name)+".tsv"), 'w')
if(len(self.case)>0):
for row in range(len(self.data)):
output_file.write("\t".join(self.data[row])+"\t"+str(self.case[row])+"\n")
else:
for row in self.data:
output_file.write("\t".join(row)+"\n")
output_file.close()
def clearCase(self):
self.case=[]
self.num_cases=0
self.num_n_cases=0
# self.entry1.set("(MM/DD/YYYY)or(MM/DD/YYYY-MM/DD/YYYY)")
self.date1=[]
self.date1_label.set("Choose Date(s)")
self.entry2.set("singlular(#) or range(#-#)")
self.entry14.set("Enter as: Word1,Word2,ect...")
self.entry16.set("Enter as: 1,2,3,...,100")
### Sex
self.m1i1.set(0)
self.m1i2.set(0)
self.m1i3.set(0)
### Race
self.m2i1.set(0)
self.m2i2.set(0)
self.m2i3.set(0)
self.m2i4.set(0)
self.m2i5.set(0)
self.m2i6.set(0)
self.m2i7.set(0)
### Location
self.m3i1.set(0)
self.m3i2.set(0)
self.m3i3.set(0)
self.m3i4.set(0)
self.m3i5.set(0)
self.m3i6.set(0)
self.m3i7.set(0)
self.m3i8.set(0)
self.m3i9.set(0)
### Fire Involvement
self.m4i1.set(0)
self.m4i2.set(0)
self.m4i3.set(0)
self.m4i4.set(0)
#Hospital Stratum
self.m5i1.set(0)
self.m5i2.set(0)
self.m5i3.set(0)
self.m5i4.set(0)
self.m5i5.set(0)
### Disposition
self.m6i1.set(0)
self.m6i2.set(0)
self.m6i3.set(0)
self.m6i4.set(0)
self.m6i5.set(0)
self.m6i6.set(0)
self.m6i7.set(0)
# Clear diagnosis data
temp=self.diag_data.keys()
for spot in temp:
self.diag_data[spot].set(0)
# Clear body part data
temp=self.body_data.keys()
for spot in temp:
self.body_data[spot].set(0)
# Clear diagnosis data
temp=self.prd_data.keys()
for spot in temp:
self.prd_data[spot].set(0)
self.case_num.set("Number of Cases:"+str(self.num_cases)+" Number of Non-Cases:"+str(self.num_n_cases))
self.updateProgress(0,len(self.data))
self.master.update_idletasks()
def checkCase(self):
check=[]
for i in range(16):
check.append([])
# e1=str(self.entry1.get())
e2=str(self.entry2.get())
e14=str(self.entry14.get())
e16=str(self.entry16.get())
if(len(self.date1)==2):
check[0]=self.date1
if(len(self.date1)==1):
check[0]=self.date1[0]
if(e2!="singlular(#) or range(#-#)" and e2!=""):
temp=e2.split("-")
if(len(temp)==1):
try:
checkit=int(temp[0])
check[1]=e2
except ValueError:
print("Please re-enter as a number")
elif(len(temp)==2):
try:
checkit=int(temp[0])
try:
checkit=int(temp[1])
check[1]=e2.split("-")
except ValueError:
print("Please re-enter range in numbers")
except ValueError:
print("Please re-enter range in numbers")
check[1]=e2.split("-")
### Sex
if(self.m1i1.get()==True):
check[2].append('1')
if(self.m1i2.get()==True):
check[2].append('2')
if(self.m1i3.get()==True):
check[2].append('0')
### Race
if(self.m2i1.get()==True):
check[3].append('1')
if(self.m2i2.get()==True):
check[3].append('2')
if(self.m2i3.get()==True):
check[3].append('3')
if(self.m2i4.get()==True):
check[3].append('4')
if(self.m2i5.get()==True):
check[3].append('5')
if(self.m2i6.get()==True):
check[3].append('6')
if(self.m2i7.get()==True):
check[3].append('0')
### Body Part
values = [(code, var.get()) for code, var in self.body_data.items()]
for i in range(len(self.body_nums)):
if(values[i][1]==True):
check[5].append(self.body_nums[i])
### Diagnosis
values = [(code, var.get()) for code, var in self.diag_data.items()]
for i in range(len(self.diag_nums)):
if(values[i][1]==True):
check[6].append(self.diag_nums[i])
### Disposition
if(self.m6i1.get()==True):
check[8].append('1')
if(self.m6i2.get()==True):
check[8].append('2')
if(self.m6i3.get()==True):
check[8].append('4')
if(self.m6i4.get()==True):
check[8].append('5')
if(self.m6i5.get()==True):
check[8].append('6')
if(self.m6i6.get()==True):
check[8].append('8')
if(self.m6i7.get()==True):
check[8].append('9')
### Location
if(self.m3i1.get()==True):
check[9].append('1')
if(self.m3i2.get()==True):
check[9].append('2')
if(self.m3i3.get()==True):
check[9].append('4')
if(self.m3i4.get()==True):
check[9].append('5')
if(self.m3i5.get()==True):
check[9].append('6')
if(self.m3i6.get()==True):
check[9].append('7')
if(self.m3i7.get()==True):
check[9].append('8')
if(self.m3i8.get()==True):
check[9].append('9')
if(self.m3i9.get()==True):
check[9].append('0')
### Fire Involvement
if(self.m4i1.get()==True):
check[9].append('1')
if(self.m4i2.get()==True):
check[9].append('2')
if(self.m4i3.get()==True):
check[9].append('3')
if(self.m4i4.get()==True):
check[9].append('0')
### Product Number
values = [(code, var.get()) for code, var in self.prd_data.items()]
for i in range(len(self.prdct_nums)):
if(values[i][1]==True):
check[11].append(self.prdct_nums[i])
### Narrative
if(e14!="Enter as: Word1,Word2,ect..." and e14!=""):
check[13]=e14.split(",")
### Stratum
if(self.m5i1.get()==True):
check[15].append('C')
if(self.m5i2.get()==True):
check[15].append('V')
if(self.m5i3.get()==True):
check[15].append('L')
if(self.m5i4.get()==True):
check[15].append('M')
if(self.m5i5.get()==True):
check[15].append('S')
### PSU
if(e16!="Enter as: 1,2,3,...,100" and e16!=""):
check[15]=e16.split(",")
print(check)
self.setCases(check)
def setCases(self, check):
self.progress_str.set("Setting Case Definition")
self.master.update_idletasks()
self.case=["Case"]
trues=0
falses=0
print("Length of self.data:",len(self.data)-1)
for i in range(1, len(self.data)):
if(len(self.data[i])==19):
row_case=True
j=0
while(row_case and j<len(check)):
if(len(check[j])!=0):
#### Check Dates
if(j==0):
if(len(check[0])==2):
start=datetime.datetime.strptime(check[0][0], '%m/%d/%Y')
end=datetime.datetime.strptime(check[0][1], '%m/%d/%Y')
try:
date=datetime.datetime.strptime(self.data[i][1], '%m/%d/%Y')
if(not start<=date<=end):
row_case=False
except ValueError:
row_case=False
else:
if(self.data[i][1]!=check[0]):
row_case=False
### Check Ages
if(j==1):
age=-1
try:
age=int(self.data[i][2])
except ValueError:
row_case=False
if(age>200):
age=int(int(age)%100/12)
if(len(check[1])==2):
start=int(check[1][0])
end=int(check[1][1])
if(age>=0):
if(not start<=age<=end):
row_case=False
else:
if(self.data[i][2]!=check[1]):
row_case=False
### Check Sex
if(j==2):
if(self.data[i][3] not in check[2]):
row_case=False
### Check Race
if(j==3):
if(self.data[i][4] not in check[3] and self.data[i][5] not in check[3]):
row_case=False
### Check Body Part
if(j==5):
if(self.data[i][6] not in check[5]):
row_case=False
### Check Diagnosis
if(j==6):
if(self.data[i][7] not in check[6] and self.data[i][8] not in check[6]):
row_case=False
### Check Disposition
if(j==8):
if(self.data[i][9] not in check[8]):
row_case=False
### Check Location
if(j==9):
if(self.data[i][10] not in check[9]):
row_case=False
### Check Fire Involvement
if(j==10):
if(self.data[i][11] not in check[10]):
row_case=False
### Check Product#
if(j==11):
if(self.data[i][12] not in check[11] and self.data[i][13] not in check[11]):
row_case=False
### Check Narrative
if(j==13):
combined=str(self.data[i][14]+self.data[i][15])
found=False
spot=0
while(not found and spot<len(check[13])):
if(check[13][spot].upper() in combined.upper()):
found=True
spot+=1
if(not found):
row_case=False
### Check Stratum
if(j==14):
if(self.data[i][16] not in check[14]):
row_case=False
### Check PSU
if(j==15):
if(self.data[i][17] not in check[15]):
row_case=False
### Iterate up
j+=1
if(row_case):
trues+=1
else:
falses+=1
self.case.append(row_case)
if(i%10000==0):
self.updateProgress(i, len(self.data))
# self.updateProgress2(i, len(self.data))
print("Cases=",trues,"Non-Cases=",falses)
self.num_cases=trues
self.num_n_cases=falses
self.case_num.set("Number of Cases:"+str(self.num_cases)+" Number of Non-Cases:"+str(self.num_n_cases))
self.master.update_idletasks()
def popup(self):
child = Toplevel(self.master)
self.newWindow(child)
def printDate(self):
print("self.date1:",self.date1)
def newWindow(self, parent):
self.values = {}
self.parent = parent
self.cal = calendar.TextCalendar(calendar.SUNDAY)
self.year = datetime.date.today().year
self.month = datetime.date.today().month
self.wid = []
day=datetime.date.today().day
self.day_selected = day
self.month_selected = self.month
self.year_selected = self.year
self.day_name = ''
self.date_label="Date:"
self.startMenu()
def startMenu(self):
single_btn = Button(self.parent, text='Single Date',command=self.popupSingle)
self.wid.append(single_btn)
range_btn = Button(self.parent, text='Date Range',command=self.popupRange)
self.wid.append(range_btn)
cancel_btn = Button(self.parent, text='Cancel',command=self.kill)
self.wid.append(cancel_btn)
single_btn.grid()
range_btn.grid()
cancel_btn.grid()
self.values = {}
def popupSingle(self):
self.values={}
self.step="single"
self.clear()
self.setup(self.year, self.month)
def popupRange(self):
self.values={}
self.step="start"
self.clear()
self.setup(self.year, self.month)
def kill(self):
self.values={}
self.parent.destroy()
def clear(self):
for w in self.wid[:]:
w.grid_forget()
self.wid.remove(w)
def go_prev(self):
if self.month > 1:
self.month -= 1
else:
self.month = 12
self.year -= 1
self.clear()
self.setup(self.year, self.month)
def go_prev_year(self):
if self.year > 0:
self.year -= 1
self.clear()
self.setup(self.year, self.month)
def go_next(self):
if self.month < 12:
self.month += 1
else:
self.month = 1
self.year += 1
self.clear()
self.setup(self.year, self.month)
def go_next_year(self):
if self.year > 0:
self.year += 1
self.clear()
self.setup(self.year, self.month)
def selection(self, day, name):
if(self.step=="single"):
self.day_selected = day
self.month_selected = self.month
self.year_selected = self.year
self.day_name = name
#data
self.values['day_selected'] = day
self.values['month_selected'] = self.month
self.values['year_selected'] = self.year
self.values['day_name'] = name
self.values['month_name'] = calendar.month_name[self.month_selected]
self.clear()
self.setup(self.year, self.month)
elif(self.step=="start"):
self.day_selected = day
self.month_selected = self.month
self.year_selected = self.year
self.day_name = name
#data
self.values['start']={}
self.values['start']['day_selected'] = day
self.values['start']['month_selected'] = self.month
self.values['start']['year_selected'] = self.year
self.values['start']['day_name'] = name
self.values['start']['month_name'] = calendar.month_name[self.month_selected]
self.clear()
self.setup(self.year, self.month)
elif(self.step=="end"):
self.day_selected = day
self.month_selected = self.month
self.year_selected = self.year
self.day_name = name
#data
self.values['end']={}
self.values['end']['day_selected'] = day
self.values['end']['month_selected'] = self.month
self.values['end']['year_selected'] = self.year
self.values['end']['day_name'] = name
self.values['end']['month_name'] = calendar.month_name[self.month_selected]
self.step="end"
self.clear()
self.setup(self.year, self.month)
def setup(self, y, m):
year_left = Button(self.parent, text='<<<', command=self.go_prev_year)
self.wid.append(year_left)
left = Button(self.parent, text='<', command=self.go_prev)
self.wid.append(left)
year_left.grid(row=0, column=1)
left.grid(row=0, column=2)
header = Label(self.parent, height=2, text='{} {}'.format(calendar.month_abbr[m], str(y)))
self.wid.append(header)
header.grid(row=0, column=3, columnspan=3)
right = Button(self.parent, text='>', command=self.go_next)
year_right = Button(self.parent, text='>>>', command=self.go_next_year)
self.wid.append(year_right)
self.wid.append(right)
right.grid(row=0, column=6)
year_right.grid(row=0, column=7)
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
for num, name in enumerate(days):
t = Label(self.parent, text=name[:3])
self.wid.append(t)
t.grid(row=1, column=num+1)
for w, week in enumerate(self.cal.monthdayscalendar(y, m), 2):
for d, day in enumerate(week):
if day:
b = Button(self.parent, width=1, text=day, command=lambda day=day:self.selection(day, calendar.day_name[(day-1) % 7]))
self.wid.append(b)
b.grid(row=w, column=d+1)
### Set date label for a single day
if(self.step=="single"):
sel = Label(self.parent, height=2, text='Date: {} {} {}'.format(
calendar.month_name[self.month_selected], self.day_selected, self.year_selected))
### Set date label for the starting day in a range
elif(self.step=="start"):
sel = Label(self.parent, height=2, text='Start Date: {} {} {}'.format(
calendar.month_name[self.month_selected], self.day_selected, self.year_selected)+
'\nEnd Date:')
### Set date label for the ending day in a range
elif(self.step=="end"):
sel = Label(self.parent, height=2, text='Start Date: {} {} {}'.format(
self.values['start']['month_name'],
self.values['start']['day_selected'],
self.values['start']['year_selected'])+
'\nEnd Date: {} {} {}'.format(calendar.month_name[self.month_selected],
self.day_selected,
self.year_selected))
self.wid.append(sel)
sel.grid(row=8, column=1, columnspan=7)
ok = Button(self.parent, width=5, text='OK', command=self.checkOK)
self.wid.append(ok)
ok.grid(row=9, column=2, columnspan=3, pady=10)
cancel = Button(self.parent, width=5, text='Cancel', command=self.checkCancel)
self.wid.append(cancel)
cancel.grid(row=9, column=5, columnspan=3, pady=10)
def checkOK(self):
if(self.step=="single" or self.step=="end"):
self.kill_and_save()
self.submitDate(self.values)
elif(self.step=="start"):
self.step="end"
self.clear()
self.setup(self.year, self.month)
def checkCancel(self):
if(self.step=="single" or self.step=="start"):
self.values={}
self.clear()
self.startMenu()
# self.kill_and_save()
elif(self.step=="end"):
self.step="start"
self.clear()
self.setup(self.year, self.month)
def kill_and_save(self):
self.parent.destroy()
def submitDate(self, value):
self.date1=[]
temp=value
label=[]
if(len(temp)==2):
temp1=[str(temp['start']['month_selected']),
str(temp['start']['day_selected']),
str(temp['start']['year_selected'])]
if(len(temp1[0])==1):
temp1[0]='0'+temp1[0]
if(len(temp1[1])==1):
temp1[1]='0'+temp1[1]
temp1="/".join(temp1)
label.append(temp1)
temp2=[str(temp['end']['month_selected']),
str(temp['end']['day_selected']),
str(temp['end']['year_selected'])]
if(len(temp2[0])==1):
temp2[0]='0'+temp2[0]
if(len(temp2[1])==1):
temp2[1]='0'+temp2[1]
temp2="/".join(temp2)
label.append(temp2)
temp1=datetime.datetime.strptime(temp1, '%m/%d/%Y')
temp2=datetime.datetime.strptime(temp2, '%m/%d/%Y')
if(temp1>temp2):
self.date1=[label[1], label[0]]
else:
self.date1=label
elif(len(temp)>0):
temp1=[str(temp['month_selected']),
str(temp['day_selected']),
str(temp['year_selected'])]
if(len(temp1[0])==1):
temp1[0]='0'+temp1[0]
if(len(temp1[1])==1):
temp1[1]='0'+temp1[1]
temp1="/".join(temp1)
label.append(temp1)
temp1=datetime.datetime.strptime(temp1, '%m/%d/%Y')
self.date1=label
if(len(self.date1)==2):
self.date1_label.set("Start Date:"+self.date1[0]+"\nEnd Date:"+self.date1[1])
elif(len(self.date1)==1):
self.date1_label.set("Date:"+self.date1[0])
self.master.update_idletasks()
def makeGUI(self):
Button(self.master, text="Load Selected Data", command=self.loadFiles).grid(column=4, row=1)
Button(self.master, text="Download File", command=self.downloadFiles).grid(column=4, row=2)
Button(self.master, text="Quit", command=self.master.destroy).grid(column=4, row=3)
Label(self.master, textvariable=self.progress_str).grid(column=4, row=6)
self.progress.grid(column=4, row=7)
Label(self.master, textvariable=self.load_str).grid(column=4, row=17)
Label(self.master, textvariable=self.dl_str).grid(column=4, row=18)
Label(self.master, textvariable=self.data_years).grid(column=4, row=19)
Label(self.master, textvariable=self.data_events).grid(column=4, row=20)
Label(self.master, text="Date").grid(column=2, row=1)
Label(self.master, text="Age").grid(column=2, row=2)
Label(self.master, text="Sex").grid(column=2, row=3)
Label(self.master, text="Race").grid(column=2, row=4)
Label(self.master, text="Body_Part").grid(column=2, row=5)
Label(self.master, text="Diagnosis").grid(column=2, row=6)
Label(self.master, text="Disposition").grid(column=2, row=7)
Label(self.master, text="Location").grid(column=2, row=8)
Label(self.master, text="Fire_Involvement").grid(column=2, row=9)
Label(self.master, text="Product#").grid(column=2, row=10)
Label(self.master, text="Narrative Field").grid(column=2, row=11)
Label(self.master, text="Stratum").grid(column=2, row=12)
Label(self.master, text="PSU").grid(column=2, row=13)
self.choose_btn = Button(self.master, textvariable=self.date1_label,command=self.popup).grid(column=3, row=1)
Entry(self.master, textvariable=self.entry2, width=34).grid(column=3, row=2)
Entry(self.master, textvariable=self.entry14, width=34).grid(column=3, row=11)
Entry(self.master, textvariable=self.entry16, width=34).grid(column=3, row=13)
Button(self.master, text="Count Cases", command=self.checkCase).grid(column=4, row=4)
# self.progress2.grid(column=5, row=15)
Label(self.master, textvariable=self.case_num).grid(column=3, row=20)
Button(self.master, text="Clear Case", command=self.clearCase).grid(column=4, row=5)
### Checkbox Menu #1 - Sex
m1= Menubutton(self.master, text="Sex", relief=RAISED)
m1.menu=Menu(m1, tearoff=0)
m1["menu"]=m1.menu
m1.menu.add_checkbutton(label="1=Male", variable=self.m1i1)
m1.menu.add_checkbutton(label="2=Female", variable=self.m1i2)
m1.menu.add_checkbutton(label="0=Not recorded", variable=self.m1i3)
m2=Menubutton(self.master, text="Race", relief=RAISED)
m2.menu=Menu(m2, tearoff=0)
m2["menu"]=m2.menu
m2.menu.add_checkbutton(label="1=White", variable=self.m2i1)
m2.menu.add_checkbutton(label="2=Black/African American", variable=self.m2i2)
m2.menu.add_checkbutton(label="3=Asian", variable=self.m2i3)
m2.menu.add_checkbutton(label="4=American Indian/Alaska Native", variable=self.m2i4)
m2.menu.add_checkbutton(label="5=Native Hawaiian/Pacific Islander", variable=self.m2i5)
m2.menu.add_checkbutton(label="6=Other", variable=self.m2i6)
m2.menu.add_checkbutton(label="0=Not Stated in ED record", variable=self.m2i7)
m3=Menubutton(self.master, text="Location", relief=RAISED)
m3.menu=Menu(m3, tearoff=0)
m3["menu"]=m3.menu
m3.menu.add_checkbutton(label="1=Home", variable=self.m3i1)
m3.menu.add_checkbutton(label="2=Farm/ranch", variable=self.m3i2)
m3.menu.add_checkbutton(label="4=Street or highway", variable=self.m3i3)
m3.menu.add_checkbutton(label="5=Other public property", variable=self.m3i4)
m3.menu.add_checkbutton(label="6=Mobile/Manufactured home", variable=self.m3i5)
m3.menu.add_checkbutton(label="7=Industrial", variable=self.m3i6)
m3.menu.add_checkbutton(label="8=School/Daycare", variable=self.m3i7)
m3.menu.add_checkbutton(label="9=Place of recreation or sports", variable=self.m3i8)
m3.menu.add_checkbutton(label="0=Not recorded", variable=self.m3i9)
m4=Menubutton(self.master, text="Fire Involvement", relief=RAISED)
m4.menu=Menu(m4, tearoff=0)
m4["menu"]=m4.menu
m4.menu.add_checkbutton(label="1=Fire involvement and/or smoke inhalation\n - Fire Dept. attended", variable=self.m4i1)
m4.menu.add_checkbutton(label="2=Fire involvement and/or smoke inhalation\n - Fire Dept. did not attend", variable=self.m4i2)
m4.menu.add_checkbutton(label="3=Fire involvement and/or smoke inhalation\n - Fire Dept. attendance is not recorded", variable=self.m4i3)
m4.menu.add_checkbutton(label="0=No fire involvement or fire involvement not recorded", variable=self.m4i4)
m5=Menubutton(self.master, text="Hospital Stratum", relief=RAISED)
m5.menu=Menu(m5, tearoff=0)
m5["menu"]=m5.menu
m5.menu.add_checkbutton(label="C=Children\'s Hospitals", variable=self.m5i1)
m5.menu.add_checkbutton(label="V=Very Large Hospitals", variable=self.m5i2)
m5.menu.add_checkbutton(label="L=Large Hospitals", variable=self.m5i3)
m5.menu.add_checkbutton(label="M=Medium Hospitals", variable=self.m5i4)
m5.menu.add_checkbutton(label="S=Small Hospitals", variable=self.m5i5)
m6=Menubutton(self.master, text="Disposition", relief=RAISED)
m6.menu=Menu(m6, tearoff=0)
m6["menu"]=m6.menu
m6.menu.add_checkbutton(label="1=Treated and released or examined and released without treatment", variable=self.m6i1)
m6.menu.add_checkbutton(label="2=Treated and transferred to another hospital", variable=self.m6i2)
m6.menu.add_checkbutton(label="4=Treated and admitted for hospitalization (within same facility)", variable=self.m6i3)
m6.menu.add_checkbutton(label="5=Held for observation", variable=self.m6i4)
m6.menu.add_checkbutton(label="6=Left without being seen/Left against medical advice (AMA)", variable=self.m6i5)
m6.menu.add_checkbutton(label="8=Fatality, including DOA, died in the ED, brain dead", variable=self.m6i6)
m6.menu.add_checkbutton(label="9=Not recorded", variable=self.m6i7)
m7=Menubutton(self.master, text="Diagnosis", relief=RAISED)
m7.menu=Menu(m7, tearoff=0)
m7["menu"]=m7.menu
for part in self.diag:
var=IntVar()
m7.menu.add_checkbutton(label=part, variable=var)
self.diag_data[part]=var
m9=Menubutton(self.master, text="Body Parts", relief=RAISED)
m9.menu=Menu(m9, tearoff=0)
m9["menu"]=m9.menu
for part in self.body:
var=IntVar()
m9.menu.add_checkbutton(label=part, variable=var)
self.body_data[part]=var
m10=Menubutton(self.master, text="Products", relief=RAISED)
m10.menu=Menu(m10, tearoff=0)
m10["menu"]=m10.menu
for code in self.prdcts:
var=IntVar()
m10.menu.add_checkbutton(label=code, variable=var)
self.prd_data[code]=var
myear=Menubutton(self.master, text="Years of NEISS Data", relief=RAISED)
myear.menu=Menu(myear, tearoff=0)
myear["menu"]=myear.menu
for year in self.nyears:
var=IntVar()
myear.menu.add_checkbutton(label=year, variable=var)
self.nyears_data[year]=var
m1.grid(column=3, row=3)
m2.grid(column=3, row=4)
m3.grid(column=3, row=8)
m4.grid(column=3, row=9)
m5.grid(column=3, row=12)
m6.grid(column=3, row=7)
m7.grid(column=3, row=6)
# m8.grid(column=5, row=)
m9.grid(column=3, row=5)
m10.grid(column=3, row=10)
myear.grid(column=1, row=1)
mainloop()
if __name__ == "__main__":
master=Tk()
neiss_GUI=NEISS_Data_Requester(master)
neiss_GUI.makeGUI()
<file_sep># NEISS Database GUI
### This is a GUI I built for downloading NEISS datasets and applying simple
### case definitions.
### First select the years of NEISS data you would like to use
### Then press the "Load Selected Data" button on the right and wait
### The progress bar will fill and the "Datasets Loaded" will = "True"
### Set a case definition by filling in the entry fields with the indicated
### value types and press the "Count Cases" button on the right
### You can clear your case definition by pressing the "Clear Case"
### button on the right
### You can also download your datasets, with set case definition by pressing
### the "Download File" button on the right.
| 6d1903e403cc482bf8886d801b25f25a10562b41 | [
"Markdown",
"Python"
] | 2 | Python | gblyth/NEISS_GUI | 5795be0ff58ad954f54834aefe35c7182f3a6006 | a0bf0b6404086647f7fe1634e48613bdc7e96f3e | |
refs/heads/master | <repo_name>nlharri/iOS-Stanford-2017-Concentration<file_sep>/README.md
# iOS-Stanford-2017-Concentration
<file_sep>/Concentration/ViewController.swift
//
// ViewController.swift
// Concentration
//
// Created by <NAME> on 2018. 12. 14..
// Copyright © 2018. <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// this is the reference to the model
// () is the initializer
// Classes get an init with no arguments by default
// if all the arguments are initialized
// The only property in Concentration is cards
// lazy means it is not initialized until someone uses it.
// but lazy cannot have property observers, like didSet
// the number of pairs of cards in the game is tied to the UI, that's why it is private
private lazy var game: Concentration = Concentration(numberOfPairsOfCards: numberOfPairsOfCards)
var numberOfPairsOfCards: Int {
return (cardButtons.count + 1 ) / 2
}
// property observer
private(set) var flipCount: Int = 0 {
didSet {
flipCountLabel.text = "Flips: \(flipCount)"
}
}
// here ! means this property does not need initializer
@IBOutlet private var cardButtons: [UIButton]!
@IBOutlet private weak var flipCountLabel: UILabel!
@IBAction private func touchCard(_ sender: UIButton) {
flipCount += 1
// ! means "assume this optional is set, and grap the associated value
// if it is not set, it will crash!
//let cardNumber = cardButtons.firstIndex(of: sender)!
if let cardNumber = cardButtons.firstIndex(of: sender) {
game.chooseCard(at: cardNumber)
//flipCard(withEmoji: emojiChoices[cardNumber], on: sender)
// here we need to update our view from our model
updateViewFromModel()
} else {
print ("ERROR")
}
}
private func updateViewFromModel() {
for index in cardButtons.indices {
let button = cardButtons[index]
let card = game.cards[index]
if card.isFaceUp {
button.setTitle(emoji(for: card), for: UIControl.State.normal)
button.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
} else {
button.setTitle("", for: UIControl.State.normal)
button.backgroundColor = card.isMatched ? #colorLiteral(red: 1, green: 0.5781051517, blue: 0, alpha: 0) : #colorLiteral(red: 1, green: 0.5781051517, blue: 0, alpha: 1)
}
}
}
// private var emojiChoices: Array<String> = ["🐰", "🦇", "🐂", "🐈", "👻", "🙊", "🦊", "🐶", "🐮", "🐫", "🐳", "🦈", "🐠", "🦐", "🦂", "🦍", "🦏", "🐎", "🐬"]
private var emojiChoices = "🐰🦇🐂🐈👻🙊🦊🐶🐮🐫🐳🦈🐠🦐🦂🦍🦏🐎🐬"
private var emoji = Dictionary<Card, String>()
private func emoji(for card: Card) -> String {
if emoji[card] == nil && emojiChoices.count > 0 {
let randomStringIndex = emojiChoices.index(emojiChoices.startIndex, offsetBy: emojiChoices.count.arc4random)
emoji[card] = String(emojiChoices.remove(at: randomStringIndex))
}
// the above one can simply be written like this!
return emoji[card] ?? "?"
}
}
extension Int {
var arc4random: Int {
if self > 0 {
return Int(arc4random_uniform(UInt32(self)))
} else if self < 0 {
return -Int(arc4random_uniform(UInt32(-self)))
} else {
return 0
}
}
}
<file_sep>/Concentration/Concentration.swift
//
// Concentration.swift
// Concentration
//
// Created by <NAME> on 2018. 12. 17..
// Copyright © 2018. <NAME>. All rights reserved.
//
import Foundation
// this is the model
// struct is a value type, it is constantly copied everywhere
struct Concentration {
// here () is the initializer
// array is a value type and Card is a value type
// this means it cannot be modified
private(set) var cards = [Card]()
private var indexOfOneAndOnlyFaceUpCard: Int? {
get {
var foundIndex: Int?
for index in cards.indices {
if cards[index].isFaceUp {
if foundIndex == nil {
foundIndex = index
} else {
return nil
}
}
}
return foundIndex
}
set {
for index in cards.indices {
cards[index].isFaceUp = (index == newValue)
}
}
}
mutating func chooseCard(at index: Int) {
assert(cards.indices.contains(index), "Concentration.chooseCard(at: \(index)): chosen index not in the cards")
if !cards[index].isMatched {
if indexOfOneAndOnlyFaceUpCard != nil {
if indexOfOneAndOnlyFaceUpCard != index {
let matchIndex = indexOfOneAndOnlyFaceUpCard!
// check if cards match
if cards[matchIndex] == cards[index] {
cards[matchIndex].isMatched = true
cards[index].isMatched = true
}
cards[index].isFaceUp = true
}
} else {
indexOfOneAndOnlyFaceUpCard = index
}
}
}
// initializers can be private as well, but in this case it should not be private
init(numberOfPairsOfCards: Int) {
assert(numberOfPairsOfCards > 0, "Concentration.init(\(numberOfPairsOfCards)): you must have at least one pair of cards")
// CountableRange is a Sequence
// special syntax
// 1...numberOfPairsOfCards -- [1 -- numberOfPairsOfCards]
// 0..<numberOfPairsOfCards -- [0 -- numberOfPairsOfCards-1]
// _ means I DONT CARE! DONT GIVE IT A NAME!
for _ in 0..<numberOfPairsOfCards {
// structs get a free initializer as well
let card = Card()
cards.append(card)
cards.append(card) // this creates a copy of card!! also assignment creates a copy!!
// or
// cards += [card, card]
// this is the same
}
}
}
<file_sep>/Concentration/Card.swift
//
// Card.swift
// Concentration
//
// Created by <NAME> on 2018. 12. 17..
// Copyright © 2018. <NAME>. All rights reserved.
//
import Foundation
// Card is a struct
// Difference from class:
// - struct -- no inheritance
// - value types ... class is a reference type
// - this means it gets copied!!!
// Arrays, Ints, Strings, Dictionaries -- these are all structs! But swift implement these in a copy-on-write semantics. That's why it is fast.
// This card does not contain the emoji. This is the model, not the UI!
struct Card: Hashable {
var isFaceUp = false
var isMatched = false
private var identifier: Int
var hashValue: Int { return identifier }
static func ==(lhs: Card, rhs: Card) -> Bool {
return lhs.identifier == rhs.identifier
}
private static var identifierFactory = 0
private static func getUniqueIdentifier() -> Int {
identifierFactory += 1
return identifierFactory
}
// inits have usually the same internal name and external name
init() {
self.identifier = Card.getUniqueIdentifier()
}
}
| ef021117781f8da2e6ce3eb1cc54c7c67b1d3e47 | [
"Markdown",
"Swift"
] | 4 | Markdown | nlharri/iOS-Stanford-2017-Concentration | a0c484e1c63e83fb4252b6f2e2f29fb9b887c7ad | 3b245873613fe14fde3ce2428ed6089ecf50a9c8 | |
refs/heads/master | <file_sep>"""
Basic order matching.
"""
from dataclasses import dataclass, field
from sortedcontainers import SortedList
import math
# from time import time
class Side:
BUY = -1
SELL = 1
@dataclass
class Order:
goid: int
side: Side
instrument: int
price: int
quantity: int
quant_remaining: int = field(init=False)
def __post_init__(self):
self.quant_remaining = self.quantity
def __lt__(self, other):
if self.price == other.price:
return self.goid < other.goid
return self.price * self.side < other.price * self.side
def __le__(self, other):
return (self == other) or (self < other)
def __gt__(self, other):
if self.price == other.price:
return self.goid > other.goid
return self.price * self.side > other.price * self.side
def __ge__(self, other):
return (self == other) or (self > other)
def __eq__(self, other):
return (self.goid == other.goid)\
and (self.price == other.price)\
and (self.side == other.side)\
and (self.quantity == other.quantity)\
and (self.instrument == other.instrument)
@dataclass(frozen=True)
class Trade:
__slots__ = ['aggressor_goid', 'resting_goid', 'price', 'quantity']#, 'timestamp']
aggressor_goid: int
resting_goid: int
price: int
quantity: int
# timestamp: float
class OrderBook:
def __init__(self, algo) -> None:
super().__init__()
self.book: dict = {Side.BUY: SortedList(), Side.SELL: SortedList()}
self.order_num = 0
self.trades = []
self.algo = algo
self.dummy_order_cursor_min = Order(-math.inf, Side.BUY, 0, 0, 0)
self.dummy_order_cursor_max = Order(math.inf, Side.BUY, 0, 0, 0)
def execute_order(self, inc_order):
is_buy = inc_order.side == Side.BUY
side = inc_order.side
cur_price = inc_order.price
inc_remaining = inc_order.quant_remaining
book = self.book[side]
def _order_cond():
if len(book) > 0:
best_price = book[0].price
return cur_price >= best_price if is_buy else cur_price <= best_price
while (inc_remaining > 0) and _order_cond():
self.trades += self.algo.execute(book, inc_order, self)
inc_remaining = inc_order.quant_remaining
(inc_remaining > 0) and self.book[-1 * side].add(inc_order)
def add_order(self, side, instrument, price, quantity):
self.order_num += 1
self.execute_order(Order(self.order_num, side, instrument, price, quantity))<file_sep>from .order_matching_engine import Order, Side
from random import randint, random
def create_dummy_order(goid,
min_price=1,
max_price=4,
min_quantity=1,
max_quantity=200,
distribution=.5) -> Order:
price = randint(min_price, max_price)
quant = randint(min_quantity, max_quantity)
if random() < distribution:
return Order(goid, Side.BUY, 1, price, quant)
else:
return Order(goid, Side.SELL, 1, price, quant)
<file_sep>**goex** is an alternative exchange engine.
Works on Python 3.6+, but for best performance, run with [Python 3.6 compatible PyPy v7.3.1](https://www.pypy.org/download.html#python-3-6-compatible-pypy3-6-v7-3-1).
<file_sep>certifi==2020.4.5.1
dataclasses==0.7
sortedcontainers==2.1.0
tqdm==4.45.0
<file_sep>"""
Implementations of matching algorithms.
Any time an aggressing order is received, matching takes the following steps:
1. Check if aggressing quantity
Each algorithm is composed of steps.
"""
from .order_matching_engine import Order, OrderBook, Trade
from sortedcontainers import SortedList
from typing import List
import numpy as np
class OrderMatchingAlgorithm:
# def __init__(self, order_book):
# self.order_book = order_book
#
#
@staticmethod
def execute(book: SortedList, order: Order, ob: OrderBook) -> List[Trade]:
raise NotImplementedError()
class FIFO(OrderMatchingAlgorithm):
@staticmethod
def order_key(order):
return order.price, order.goid
@staticmethod
def execute(book: SortedList, order: Order, ob: OrderBook) -> List[Trade]:
resting_order = book.pop(0)
filled_quantity = min(order.quant_remaining, resting_order.quant_remaining)
order.quant_remaining -= filled_quantity
resting_order.quant_remaining -= filled_quantity
(resting_order.quant_remaining > 0) and book.add(resting_order)
# TODO: Global TradeLog object?
return [Trade(order.goid, resting_order.goid, resting_order.price, filled_quantity)]
#
# def execute_order(self, inc_order):
# is_buy = inc_order.side == Side.BUY
# side = inc_order.side
# cur_price = inc_order.price
# inc_remaining = inc_order.quant_remaining
# book = self.book[side]
#
# def _order_cond():
# if len(book) > 0:
# best_price = book[0].price
# return cur_price >= best_price if is_buy else cur_price <= best_price
#
# while (inc_remaining > 0) and _order_cond():
# self.trades += self.algo.execute(book, inc_order, self)
# inc_remaining = inc_order.quant_remaining
#
# (inc_remaining > 0) and self.book[-1 * side].add(inc_order)
# class ProRata(OrderMatchingAlgorithm):
# def __init__(self, thresh=2):
# self.thresh = thresh
# @staticmethod
# def execute(book: SortedList, order: Order, ob: OrderBook) -> List[Trade]:
# trades = []
# # Fill the TOP order
# trades += FIFO.execute(book, order, ob)
# if order.quant_remaining < 1:
# # Order filled entirely by TOP
# return trades
# ob.dummy_order_cursor_max.price = order.price
# grp_max = book.bisect_right(ob.dummy_order_cursor_max)
# if not grp_max:
# # No more orders
# return trades
# grp = [book.pop(0) for _ in range(grp_max)]
# arr = np.array([o.quant_remaining for o in grp])
# den = arr.sum()
# arr = np.floor(order.quant_remaining * arr / den)
# qfills = [q if q > 2 else 0 for q in arr]
# trades = []
# for ix, q in enumerate(qfills):
# resting_order = grp[ix]
# order.quant_remaining -= q
# resting_order.quant_remaining -= q
# (resting_order.quant_remaining > 0) and book.add(resting_order)
# trades.append(Trade(order.goid, resting_order.goid, resting_order.price, q))
#
# def _fifo_rest():
# t = FIFO.execute(book, order, ob)
# t and trades.extend(t)
#
# while order.quant_remaining > 0:
# _fifo_rest()
#
# return trades
<file_sep>## Structure of order matching algorithms
**goex** will aim to support most of the order matching algorithms supported on
the [CME Globex platform.](https://www.cmegroup.com/confluence/display/EPICSANDBOX/Supported+Matching+Algorithms#space-menu-link-content)
The CME group currently lists 8 supported matching algorithms:
* Allocation
* FIFO
* FIFO w/ LMM
* FIFO w/ Top Order and LMM
* Pro Rata
* Configurable
* Threshold Pro-Rata
* Threshold Pro-Rata w/ LMM
In practice, each of these algorithms are composed of steps. Each step can be
one of the following algorithms:
* FIFO
* Pro Rata
* LMM
* Split
* Leveling
* TOP
In order to differentiate between the steps of an algorithm and the total
algorithm, we will refer to the steps as **allocation steps** and the
algorithm composed of allocation steps as the **matching algorithm**.
####[Algorithm Matrix](https://www.cmegroup.com/confluence/display/EPICSANDBOX/CME+Globex+Matching+Algorithm+Steps#CMEGlobexMatchingAlgorithmSteps-TOP)
| Algorithm | Operational Name | Step | | | | | | |
|-----------|---------------------------------------------|----------|----------|----------|-------|-----------|-----------|------|
| | | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| A | Allocation Algorithm<br>(Pro Rata w/ Top) | TOP | Pro Rata | FIFO | | | | |
| C | Currency Roll<br>(Pro Rata w/o Top) | Pro Rata | FIFO | | | | | |
| F | FIFO | FIFO | | | | | | |
| K | Configurable (Split FIFO/Pro Rata with LMM) | TOP | LMM | Split | FIFO\* | Pro Rata\* | Leveling\* | FIFO |
| O | Pro Rata w/ Top and parameters | TOP | Pro Rata | FIFO | | | | |
| Q | Pro Rata w/ Top, Parameters, and LMM | TOP | LMM | Pro Rata | FIFO | | | |
| S | LMM w/ Top | TOP | LMM | FIFO | | | | |
| T | LMM w/o Top | LMM | FIFO | | | | | |
\*FIFO and Pro Rata percentages are determined by CMEG and calculated during
Split. Leveling can be optionally on or off for K.
<file_sep>const airbnb = require('@neutrinojs/airbnb');
const react = require('@neutrinojs/react');
const jest = require('@neutrinojs/jest');
const svgr = require('@svgr/webpack')
module.exports = {
options: {
root: __dirname,
},
use: [
airbnb(),
react({
html: {
title: 'app'
}
}),
// (neutrino) => {
// neutrino.config.module
// .rule('svgr')
// .test(/\.svg$/)
// // .use(svgr)
// },
jest(),
],
};
<file_sep>## goex
**goex** is an open-source exchange that supports trading of nearly any
commodity or financial instrument.
<file_sep>from goex.engine import Order, OrderBook, Side, create_dummy_order, FIFO
from random import randint, random
from tqdm import tqdm
import argparse
def printl(s1, s2, p=20):
print(f"{f'{s1:<{p}} {s2:<{int(p / 2)}}':^80}")
class Benchmarker:
@staticmethod
def run(num_orders=10 ** 7,
min_price=1, max_price=4,
min_quantity=1, max_quantity=200,
distribution=.5,
verbose=1,
algo='FIFO'):
# Benchmark
twidth = 80
OB = OrderBook(FIFO())
orders = []
if verbose >= 1:
print(f"{'-' * twidth}\n")
print(f"{'Running benchmark for goex v0.1':^{twidth}}\n")
if verbose >= 2:
print(f"{'-' * twidth}\n")
print(f"{'Settings':^{twidth}}\n")
# printl('Algorithm', f'{algo}')
printl('Algorithm', f'{algo}')
printl('Orders', f'{num_orders}')
printl(f"Price", f"[{min_price}, {max_price}]")
printl(f"Quantity", f"[{min_quantity}, {max_quantity}]")
printl(f"Distribution", f"[{distribution}, {1 - distribution}]")
printl(f"Verbosity", f"{verbose}")
print()
if verbose >= 2:
print(f"{'-' * twidth}\n")
print(f"{'Benchmark':^{twidth}}\n")
print(f"{'Stage':<22}{'Rate':<10}{'Elapsed':<10}{'Progress':<10}")
# for n in tqdm(range(num_orders),
# disable=verbose < 1,
# unit='',
# smoothing=0,
# ncols=twidth,
# ascii=True,
# unit_scale=True,
# desc=f"{'Building orders...':<22}",
# bar_format="{desc}{rate_fmt:<10}{elapsed:<10}{bar} {percentage:3.0f}%"):
orders = [create_dummy_order(n, min_price, max_price, min_quantity, max_quantity,
distribution) for n in tqdm(range(num_orders),
disable=verbose < 1,
unit='',
smoothing=0,
ncols=twidth,
ascii=True,
unit_scale=True,
desc=f"{'Building orders...':<22}",
bar_format="{desc}{rate_fmt:<10}{elapsed:<10}{bar} {percentage:3.0f}%")]
from time import time
start = time()
for order in tqdm(orders,
disable=verbose < 1,
smoothing=0,
desc=f"{'Simulating orders...':<22}",
unit='',
ascii=True,
ncols=twidth,
unit_scale=True,
bar_format="{desc}{rate_fmt:<10}{elapsed:<10}{bar} {percentage:3.0f}%"):
OB.execute_order(order)
# time()
end = time()
(verbose >= 2) and print()
print(f"{'-' * twidth}\n")
print(f"{'Results':^80}\n")
total_time = (end - start)
print(f"{f'Processed {num_orders} orders and filled {len(OB.trades)} trades.':^80}\n")
printl(f"Total time elapsed (s):", f"{total_time:{6}.{5}f}", p=30)
printl(f"Average time per order (us):", f"{(1000000 * total_time / num_orders):{6}.{5}f}",
p=30)
printl(f"Average orders per second:", f"{(num_orders / total_time):{6}.{2}f}", p=30)
print()
print(f"{'-' * twidth}")
class NumRange:
"""
Adapted from https://stackoverflow.com/a/61411431/9893711
"""
def __init__(self, ntype, imin=None, imax=None):
self.ntype = ntype
self.imin = imin
self.imax = imax
def __call__(self, arg):
try:
value = self.ntype(arg)
except ValueError:
raise self.exception()
if (self.imin is not None and value < self.imin) or (
self.imax is not None and value > self.imax):
raise self.exception()
return value
def type_str(self):
raise NotImplementedError("You should extend NumRange and implement type_str().")
def exception(self):
if self.imin is not None and self.imax is not None:
return argparse.ArgumentTypeError(
f"Must be an {self.type_str()} in the range [{self.imin}, {self.imax}]")
elif self.imin is not None:
return argparse.ArgumentTypeError(f"Must be an {self.type_str()} >= {self.imin}")
elif self.imax is not None:
return argparse.ArgumentTypeError(f"Must be an {self.type_str()} <= {self.imax}")
else:
return argparse.ArgumentTypeError(f"Must be an {self.type_str()}")
class IntRange(NumRange):
def __init__(self, imin=None, imax=None):
super().__init__(int, imin, imax)
def type_str(self):
return 'integer'
class FloatRange(NumRange):
def __init__(self, imin=None, imax=None):
super().__init__(float, imin, imax)
def type_str(self):
return 'float'
parser = argparse.ArgumentParser(description='Benchmark order_matching_engine.py.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-n', '--num-orders',
type=IntRange(1),
default=10000000,
help='number of orders to simulate')
parser.add_argument('-p', '--min-price',
type=IntRange(0),
default=1,
help='minimum price per order')
parser.add_argument('-P', '--max-price',
type=IntRange(0),
default=4,
help='maximum price per order')
parser.add_argument('-q', '--min-quantity',
type=IntRange(0),
default=1,
help='minimum quantity per order')
parser.add_argument('-Q', '--max-quantity',
type=IntRange(0),
default=200,
help='maximum quantity per order')
parser.add_argument('-d', '--distribution',
type=FloatRange(0, 1),
default=.5,
help='probability of generating a buy order')
parser.add_argument('-v', '--verbose',
type=int,
choices=range(4),
default=1,
help='verbose output')
parser.add_argument('--version',
action='version',
version='goex v0.1')
if __name__ == '__main__':
args = parser.parse_args()
Benchmarker.run(args.num_orders,
args.min_price,
args.max_price,
args.min_quantity,
args.max_quantity,
args.distribution,
args.verbose)
<file_sep>from .order_matching_engine import Order, OrderBook, Side, Trade
from .algos import OrderMatchingAlgorithm, FIFO, ProRata
from .utils import create_dummy_order | a91457ab9200f956a4362642a9599233eba42d74 | [
"Markdown",
"Python",
"Text",
"JavaScript"
] | 10 | Python | zraffo/goex | 202a610cc3de576bb033a0dda043ff27e0518f3f | 6fdab6fde9cb4d6ec2c3fe0330173953f9eee7e8 | |
refs/heads/master | <file_sep>日経ソフトウェアの連載「イチからわかる Ruby on Rails」で使っているサンプルコードです。
途中から連載を読み始めた方は、こちらのコードを使ってください。
## Cloud9のセットアップ方法
Cloud9のセットアップがまだの方は、
Railsチュートリアルの1.2節「[さっそく動かす](http://railstutorial.jp/chapters/beginning?version=4.2#sec-up_and_running)」に従ってCloud9をセットアップください。
Railsチュートリアル 1.2 さっそく動かす
http://railstutorial.jp/chapters/beginning?version=4.2#sec-up_and_running
## ダウンロード方法
Cloud9上のターミナルで、次のコマンド群を実行してください。
```bash
$ cd ~/workspace
$ git clone https://github.com/yasslab/nikkeibp2015.git
Cloning into 'nikkeibp2015'...
... (以下、省略) ...
$ cd nikkeibp2015
$ bundle install
Using rake 10.4.2
Using i18n 0.7.0
Using json 1.8.3
... (以下、省略) ...
```
これで準備完了です :)
あとは連載記事に従って読み進めてください。
## 関連リンク
- [日経ソフトウェア (2016年1月号)](http://ec.nikkeibp.co.jp/item/backno/SW1212.html)
- [Railsチュートリアル](http://railstutorial.jp)
- [Railsガイド](http://railsguides.jp)
## ライセンス
(The MIT License)
Copyright © 2015-2016 [YassLab](http://yasslab.jp)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<file_sep>require 'test_helper'
class UserTest < ActiveSupport::TestCase
test "サンプルデータは正しい" do
u = users(:sample)
assert u.valid?
end
test "nameが空文字だとダメ" do
u = users(:sample)
u.name = ""
assert_not u.valid?
end
test "emailが空文字だとダメ" do
u = users(:sample)
u.email = ""
assert_not u.valid?
end
end
<file_sep>class UsersController < ApplicationController
def new
@user = User.first
end
end
| 9159bde0ac8d74225fdee97115f4aa7222be3f10 | [
"Markdown",
"Ruby"
] | 3 | Markdown | yasslab/nikkeibp2015 | 97ba88056ff99eb753c496d6fc77f8955dc794e7 | f0c1c2e9d234b0538d0ea8047148aaec58f9eeed | |
refs/heads/master | <file_sep># Azure Camp 2019
This is the code for azure camp 2019 in Calgary, Alberta. The theme of this camp is around containers and Kubernetes. For good measure we're adding a little bit of AI into the mix because that's cool these days.
Our application is an application form for a job posting site. We're going to allow people to post jobs on the site and then we'll display them for other to apply. This system is built on top of a cluster of microservices, again because that's cool.
If you're actually considering building a system on microservices it is best to do a bunch of research up front and have a clear understanding of what the advantages and disadvantages of microservices are. https://dwmkerr.com/the-death-of-microservice-madness-in-2018/ is a pretty good article to get you started.
## Services
1. Salary prediction service - this AI based service will rate your offered salary against the industry average for your province.
2. UI This is the visual front end for your application. Really simple, just a couple of forms.
3. Model builder - builds the AI model for the salary prediction service.
4. Social poster - posts messages about new job posting on social media
## Infrastructure
We are designing the system to run atop of a series of containers hosted in Kubernetes which we'll be calling K8s to save typing.
## Prerequisites
Most of the tools we're using can be installed quickly on the day of the camp but it never hurts to be prepared. These are some of the things you can install ahead of time.
1. The Azure CLI ([Any platform](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest)) - for accessing azure
2. Docker ([Windows](https://runnable.com/docker/install-docker-on-windows-10) | [OSX](https://runnable.com/docker/install-docker-on-macos) | [Linux](https://runnable.com/docker/install-docker-on-linux)) - for running containers locally
3. Kubectrl ([Any platform](https://kubernetes.io/docs/tasks/tools/install-kubectl/#install-kubectl)) - for interacting with kubernetes
## Why containers?
That's a great question. Maybe we should take one step back from that and talk about what containers are.
Years ago computers didn't have operating systems - they were dumb boxes into which you'd feed some input in the form of a program and then you'd wait for it to finish. They were also crazy mad expensive. In order to not waste money by having these monsters sit idle people started to build programs which would remain resident on the computers and which would feed new programs into the computers.
These were the first time sharing systems. As time progressed and computers got faster sometimes it was desirable to run multiple applications at once. Of course running multiple applications at once could introduce all sorts of instabilities. What if two apps needed the same resource at the same time? How could you best share the compute resources? What if two applications used the same shared libraries but different versions?
Bit of a nightmare really. Doubly so when you consider shipping you application into an unknown environment with goodness knows what libraries installed.
Containers introduce a layer of isolation which is greater than that of a simple process. This might sound a lot like a virtual machine but containers actually sit in a sweet spot where they can be way more efficient than a full VM and way more isolated than a process. They give you the confidence that you application will perform the same way in production as it does in test and even on your local machine.
Let's start with building an application. Then we'll containerize it for deployment.
## Building the Application
## Original plan
1. Create an app which listens to an Azure storage queue
2. Add docker support and run on your local machine
3. Check it into GitHub
4. Hook up an azure DevOps account to it and do a build
5. Check the security of your application during builds and deployment: DevOps security or DevSecOps.
6. Hook DevOps up to your Azure account and push the container to the docker registry in Azure
7. Using an ARM template build a reproducible Azure environment
8. Deploy the container to AKS and use DevOps release pipelines to deploy a new version
<file_sep>using System;
using System.IO;
using Microsoft.Data.DataView;
using Microsoft.ML;
using Microsoft.ML.Data;
using static Microsoft.ML.Transforms.NormalizingEstimator;
namespace ModelBuilder
{
class Program
{
static readonly string _trainDataPath = Path.Combine(Environment.CurrentDirectory, "Data", "WeeklyEarningsTrain.csv");
static readonly string _testDataPath = Path.Combine(Environment.CurrentDirectory, "Data", "WeeklyEarningsTest.csv");
static readonly string _modelPath = Path.Combine(Environment.CurrentDirectory, "Data", "Model.zip");
static void Main(string[] args)
{
MLContext mlContext = new MLContext();
// If working in Visual Studio, make sure the 'Copy to Output Directory'
// property of iris-data.txt is set to 'Copy always'
IDataView trainingDataView = mlContext.Data.LoadFromTextFile<WeeklyEarnings>(path: _trainDataPath, hasHeader: false, separatorChar: ',');
IDataView testDataView = mlContext.Data.LoadFromTextFile<WeeklyEarnings>(_testDataPath, hasHeader: false, separatorChar: ',');
var dataProcessPipeline = mlContext.Transforms.CopyColumns(outputColumnName: DefaultColumnNames.Label, inputColumnName: nameof(WeeklyEarnings.AverageWeeklyEarnings))
.Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "GeographyEncoded", inputColumnName: nameof(WeeklyEarnings.Geography)))
.Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "IndustryEncoded", inputColumnName: nameof(WeeklyEarnings.Industry)))
.Append(mlContext.Transforms.Concatenate(DefaultColumnNames.Features, "GeographyEncoded", "IndustryEncoded"));
var trainer = mlContext.Regression.Trainers.StochasticDualCoordinateAscent(labelColumnName: DefaultColumnNames.Label, featureColumnName: DefaultColumnNames.Features);
var trainingPipeline = dataProcessPipeline.Append(trainer);
Console.WriteLine("=============== Training the model ===============");
var trainedModel = trainingPipeline.Fit(trainingDataView);
Console.WriteLine("===== Evaluating Model's accuracy with Test data =====");
IDataView predictions = trainedModel.Transform(testDataView);
var metrics = mlContext.Regression.Evaluate(predictions, label: DefaultColumnNames.Label, score: DefaultColumnNames.Score);
ConsoleHelper.PrintRegressionMetrics(trainer.ToString(), metrics);
using (var fs = File.Create(_modelPath))
trainedModel.SaveTo(mlContext, fs);
Console.WriteLine("The model is saved to {0}", _modelPath);
Console.WriteLine("Testing single");
TestSinglePrediction(mlContext);
Console.ReadLine();
}
private static void TestSinglePrediction(MLContext mlContext)
{
//Sample:
//48,British Columbia,Average weekly earnings including overtime for all employees,Other services (except public administration),580.13,-7.5,0.7
var weeklyEarning = new WeeklyEarnings()
{
Date = 48,
Geography = "British Columbia",
Industry = "Other services (except public administration)"
};
ITransformer trainedModel;
using (var stream = new FileStream(_modelPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
trainedModel = mlContext.Model.Load(stream);
}
// Create prediction engine related to the loaded trained model
var predEngine = trainedModel.CreatePredictionEngine<WeeklyEarnings, WeeklyEarningsPrediction>(mlContext);
//Score
var resultprediction = predEngine.Predict(weeklyEarning);
///
Console.WriteLine($"**********************************************************************");
Console.WriteLine($"Predicted weekly earning: {resultprediction.AverageWeeklyEarnings:0.####}, actual weekly earning: 580.13");
Console.WriteLine($"**********************************************************************");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.ML.Data;
namespace ModelBuilder
{
public class WeeklyEarnings
{
[LoadColumn(0)]
public int Date { get; set; }
[LoadColumn(1)]
public string Geography { get; set; }
[LoadColumn(3)]
public string Industry { get; set; }
[LoadColumn(4)]
public float AverageWeeklyEarnings { get; set; }
}
public class WeeklyEarningsPrediction
{
[ColumnName("Score")]
public float AverageWeeklyEarnings { get; set; }
}
}
| 245860fd1fd08ff99f39f436a062ccce6824b97f | [
"Markdown",
"C#"
] | 3 | Markdown | baoqinye/AzureCamp2019 | 03ffa4f5366ee3d3cf3c9188bfdbcb23412bd3d3 | 955e9e6e3b97e4952580cf440ea7241c79279da1 | |
refs/heads/master | <repo_name>chris12540/react-1-lecture<file_sep>/src/App.js
import React, { Component } from "react";
import "./App.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: "bOb",
pic: "http://http.cat/404",
friends: [{ name: "Kian", pic: "http://http.cat/200" }]
};
// this.updateName = this.updateName.bind(this);
}
addFriend = () => {
const newFriend = { name: this.state.name, pic: this.state.pic };
const friendsCopy = this.state.friends.slice();
// do not mutate state directly!
friendsCopy.push(newFriend);
this.setState({ name: "", pic: "", friends: friendsCopy });
};
// updateName = event => {
// this.setState({
// name: event.target.value
// });
// };
// updatePic = event => {
// this.setState({
// pic: event.target.value
// });
// };
render() {
const { name, pic, friends } = this.state;
return (
<div>
<div>
Name:{" "}
<input
type="text"
value={name}
onChange={e => this.setState({ name: e.target.value })}
/>
{name}
</div>
<div>
Picture URL:{" "}
<input
type="text"
value={pic}
onChange={e => this.setState({ pic: e.target.value })}
/>
{pic}
</div>
<button onClick={this.addFriend}>Add Friend</button>
<div>
Friends: <br />
{friends.map(friend => {
return (
<div>
Name: {friend.name} Picture:{" "}
<img src={friend.pic} alt="Cats :P" height="200px" />
</div>
);
})}
</div>
</div>
);
}
}
export default App;
| 2837b0470148fe18a475eaabd05ac36e21093347 | [
"JavaScript"
] | 1 | JavaScript | chris12540/react-1-lecture | 125353c2b6483e4ba8820eb3e120001f274a0866 | 25b389c1137098bf2cf8c7d6dfb8cc74d93188d2 | |
refs/heads/master | <repo_name>sunilvanam/NodeJS<file_sep>/app.js
const express = require('express');
const mongo = require('mongoose');
const bodyparser = require('body-parser');
const app = express();
const user = require('./models/user')
const order = require('./models/order')
const fs = require('fs')
const mongoUrl = 'mongodb://localhost:27017/nodeDBex'
app.listen(9000, function(req, res){
});
app.use(bodyparser.json());
mongo.connect(mongoUrl,{useNewUrlParser:true,useUnifiedTopology: true})
const con = mongo.connection
con.on('open', function(){
console.log('MongoDB connected succesfully')
})
app.post('/create_user', async (req, res)=>{
const alien = new user({
first_name : req.body.first_name,
last_name : req.body.last_name,
email : req.body.email,
mobile : req.body.mobile,
user_id : req.body.user_id
})
try {
const aliens = await alien.save()
res.send("User created success")
} catch (error) {
res.send('Error ' + error )
}
})
app.post('/create_order', async (req, res)=>{
const order_data = new order({
product_name : req.body.product_name,
price : req.body.price,
address : req.body.address,
quantity : req.body.quantity,
user_id : req.body.user_id
})
try {
const orders = await order_data.save()
res.send('Order created successfully')
} catch (error) {
res.send('Error ' + error )
}
})
app.get('/get_order/:id', async (req, res)=>{
let id = req.params.id;
console.log(id);
try{
let result = await order.find({"user_id":id})
res.send(result)
}catch(error){
res.send('Error '+ error)
}
})
app.get('/get_user', async (req, res)=>{
let id = req.params.id;
try{
let result = await user.find()
res.json(result)
}catch(error){
res.send('Error '+ error)
}
})
<file_sep>/models/user.js
const mongoose = require('mongoose')
const alienSchema = new mongoose.Schema({
first_name: {
type : String,
required : true
},
last_name: {
type : String,
required : true
},
email: {
type : String,
required : true
},
mobile: {
type : String,
required : true
},
user_id: {
type : String,
required : true
}
})
module.exports = mongoose.model('users', alienSchema) | 5582f7433c85a52f68d1d6e9e6d16bbc2ef60fae | [
"JavaScript"
] | 2 | JavaScript | sunilvanam/NodeJS | 570fc5387bf6a93e8cc7b98e8c0cfd77405a9f77 | bba160ba84d146fb4a05bd6a069312740d9695b3 | |
refs/heads/master | <file_sep><div id='profileArea'>
<?php
// boldShow($type, $content) returns escaped html with $type in bold followed by
// $content in normal style.
// If the profile is a form, boldShow will turn it into
// an input field.
function boldShow($type, $content, $profileType = "", $textblock = false)
{
$type = htmlentities($type, ENT_QUOTES, "UTF-8");
$content = htmlentities($content, ENT_QUOTES, "UTF-8");
return "<p class='profiledata'><b>$type:</b> $content</p>\n";
}
// Calculates the current age based on the birthdate
function getAge($birthdate)
{
list($year, $month, $day) = explode("-", $birthdate);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
// If the month-difference is smaller then 0, or is 0 with a smaller day-difference,
// the user hasn't had his/her birthday this year yet.
if($month_diff < 0) {
$year_diff--;
}
else if($month_diff == 0 && $day_diff < 0) {
$year_diff--;
}
return $year_diff;
}
function getLikePicture(array $likestatus)
{
$status = array();
foreach($likestatus as $liked) {
if($liked) {
$status[] = "liked";
}
else {
$status[] = "pending";
}
}
return '<img class="likepicture" src="' . base_url() . "img/$status[0]-$status[1].jpg"
. '" width="90" height="60" />';
}
foreach($profiles as $profile) {
// A profilebox is opened and the username and gender for the public profile are echoed.
// If the profile is big, the profilebox is a section.
if($profileType == "big") {
$boxType = "<div id='bigprofile' ";
}
// If the profile is small, it is a link
else {
$boxType = "<a href=\"". base_url().
"/index.php/viewprofile/showprofile/". $profile['userId']. "\" ";
}
// The gender is converted to readable matter
if($profile['gender'] == '0') {
$gender = "M";
}
else {
$gender = "F";
}
// The username and gender are displayed extra big
echo $boxType. "class='profilebox'>\n". heading(htmlentities($profile['username']. " (".
$gender. ")", ENT_QUOTES, "UTF-8"), 3);
$loggedIn = $this->authentication->userLoggedIn();
$imgfile;
if($loggedIn && $profile['picture'])
{
// The file name does not depend on user input and therefore does not need to be
// escaped.
$imgfile = 'pictures/' . $profile['picture'];
}
else
{
$imgfile = 'silhouette-' . ($profile['gender'] == 0 ? 'man' : 'woman') . '.jpg';
}
// Show thumbnail.
$imgurl = base_url() . 'img/' . $imgfile;
echo '<img class="profilepicture" src="' . $imgurl . '" alt="Profile photo" width="125" height="150" />';
// The thumbnail is shown. If the user is logged in, the real picture, else, a silhouette.
if($loggedIn)
{
// If there is a mutual like, show the users name
if(isset($profile['likestatus']) && $profile['likestatus'][0] && $profile['likestatus'][1]) {
echo boldShow("Name", $profile['firstName']. " ". $profile['lastName']);
echo boldShow("Email", $profile['email']);
}
}
// The age is displayed
echo boldShow("Age", getAge($profile['birthdate']), $profileType);
// If the profileType is small, the discription should show only the first line.
if($profileType == "small") {
$point = strpos($profile['description'], '.'); // Lines usually end with a point.
// However, if the line is longer then 100 characters, it is cut off.
if($point === false or $point > 100) {
$disc = substr($profile['description'], 0, 100). "...";
}
else {
$disc = substr($profile['description'], 0, $point+1);
}
}
else {
$disc = $profile['description'];
}
// And the discription, in correct length, is displayed.
// The true turns it into a textarea if the profile is a form.
echo boldShow("About me", $disc, $profileType, true);
// The usertype and preference are displayed
echo boldShow("Personality", $profile['personality']);
echo boldShow("Preference", $profile['preference']);
// If the profile is small, only a maximum of 4 random brands are shown
if($profileType == 'small') {
$maxBrands = min(array(3, count($profile['brands']) - 1));
shuffle($profile['brands']);
}
// else, if the profile is big, all brands are shown
else $maxBrands = count($profile['brands']) - 1;
$brands = "";
for($b = 0; $b < $maxBrands; $b++) {
$brands .= $profile['brands'][$b]. ", ";
}
// To avoid a comma at the end, the last brand is added after the loop.
$brands .= $profile['brands'][$b];
echo boldShow("Favorite brands", $brands);
// The like-status should be displayed.
if($this->authentication->userLoggedIn()) {
if($profile['likestatus'][0])
{
if($profile['likestatus'][1])
{
echo "You both like each other". br();
}
else
{
echo "You liked this user, but have yet to receiev a like back...". br();
}
}
else if($profile['likestatus'][1])
{
echo "The other user liked you, like back?". br();
}
else
{
echo "this user has not liked you yet, but you can be the first...". br();
}
if($profileType == 'big' && !$profile['likestatus'][0]) {
echo "<h3 id='likebutton'>". htmlspecialchars("<< Click here to like user >>"). "</h3>";
}
else {
echo getLikePicture($profile['likestatus']);
}
}
// If the profilebox is big, the div is closed
if($profileType == "big") {
echo "</div>";
}
else { // and if it is small, it's link is closed.
echo "</a>";
}
}
?>
</div>
<script type="text/javascript">
// Add mouse listener to the likebutton.
$('#likebutton').click(function()
{
var ok = confirm("<?php echo 'Do you want to like '. $profile['username']. '?'; ?>");
if(ok)
{
// Send like request.
$.post('<?php echo base_url(). '/index.php/viewprofile/like'; ?>',
{otherId: <?php echo $profile['userId'] ?>},
function()
{
// Refresh page when done.
window.location.reload();
});
}
});
</script><file_sep><?php
if($error !== null)
{
echo '<p class="error">' . form_prep($error) . '</p>';
}
$n = '<br/>';
echo form_open('adminpanel', array('id' => 'adminform'))
.$n. form_label('Similarity measure:', 'similarityMeasure')
.$n. form_dropdown('similarityMeasure', array(
"Dice's",
"Jaccard's",
"Cosine",
"Overlap"
), $similarityMeasure)
.$n. form_label('X-factor (0-1):', 'xFactor')
.$n. form_input('xFactor', $xFactor, array('type' => 'range', 'min'=> '0', 'max' => '1'))
.$n. form_label('Alpha factor (0-1):', 'alpha')
.$n. form_input('alpha', $alpha, array('type' => 'range', 'min'=> '0', 'max' => '1'))
.$n. form_submit('submit', 'Apply')
.$n. form_close()
;
<file_sep><?php
$base = base_url() . 'index.php';
$ci =& get_instance();
$admin = $ci->authentication->userIsAdmin();
?>
<nav>
<ul>
<li><a href="<?php echo "$base/home"?>">Home</a></li>
<li><a href="<?php echo "$base/search"?>">Search</a></li>
<?php
if($this->authentication->userLoggedIn()) {
echo "<li><a href=\"$base/search/matching\">Match!</a></li>";
echo "<li><a href=\"$base/profileUpdate\">Edit Profile</a></li>";
echo "<li><a href=\"$base/search/likes\">Likes</a></li>";
}
if($admin) {
echo "<li><a href=\"$base/adminpanel\">Configuration</a></li>";
}
?>
</ul>
</nav>
<section id='main'><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends CI_Controller
{
public function index()
{
$this->load->helper('url');
$this->load->helper('security');
$this->load->model('User', 'user');
$this->load->library('Personality', 'personality');
$this->load->model('Matching', 'matching');
$this->load->model('Brand', 'brand');
// User generator.
$allBrands = $this->brand->getBrands();
for($i = 1; $i < 50; ++$i)
{
$brands = array_rand(array_flip($allBrands), rand(2, 50));
$data = array(
'username' => "ExtraTestuser$i",
'email' => "<EMAIL>",
'firstName' => '<NAME>',
'lastName' => 'The ' . $i . ' th',
'gender' => $i % 2 == 0,
'birthdate' => '198' . $i % 10 . '-01-01',
'description' => 'Ik ben een testgebruiker om dit geheel een beetje op te vullen. Alleen dan wat beter gebalanceerd.',
'minAgePref' => 18,
'maxAgePref' => 100,
'genderPref' => $i % 3 == 0 ? null : $i % 3 == 1,
'personalityI' => rand(0, 100) / 100,
'personalityN' => rand(0, 100) / 100,
'personalityT' => rand(0, 100) / 100,
'personalityJ' => rand(0, 100) / 100,
'preferenceI' => rand(0, 100) / 100,
'preferenceN' => rand(0, 100) / 100,
'preferenceT' => rand(0, 100) / 100,
'preferenceJ' => rand(0, 100) / 100
);
$this->user->createUser($data, 'test12345', $brands);
/*print_r($brands);
echo "<br/>";
echo "<br/>";
echo "<br/>";*/
}
//$id = $this->user->createUser($data, 'hoi', $brands);
/*$this->user->deleteSelf();
$id = $this->user->createUser($data, 'hoi', $brands);
$user = $this->user->load(1);
print_r($user['genderPref'] === '0');*/
//print_r($this->user->load(1));
//print_r($this->matching->matchingList(1));
//$this->user->like(2);
//print_r($this->user->getLikeStatus(2));
//$this->parser->parse('searchbrowser', array('bla' => array('Blah!', 'Blablah!')));
/*if(count($_FILES) > 0)
{
$this->load->library('picture');
print_r($this->picture->uploadAndProcess());
}
else
{
echo form_open_multipart() . form_upload('picture') . form_submit('submit', 'go') . form_close();
}*/
}
}
<file_sep>
<div id="searchbrowsebuttons">
<p id="previous"> << Previous page </p>
<p id="next"> Next page >> </p>
</div>
<script type="text/javascript">
$(document).ready(function()
{
// Put the received user id's in a global using the template parser.
userIds = [0 {ids} , {id} {/ids} ];
// Remove initial zero.
userIds.splice(0,1);
// The current page of results.
currentPage = 0;
// The total number of pages, equal to the number of id's divided by 6 (and rounded upwards).
nofPages = Math.ceil(userIds.length / 6);
// Hide the previous button.
$('#previous').hide();
// Hide the nest button if there is only one page.
if(nofPages <= 1)
{
$('#next').hide();
}
// Function for getting a certain page through AJAX.
function getPage(page)
{
// Determine id's on this page.
var ids = '';
for(var i = page * 6; i < page * 6 + 6 && i < userIds.length; ++i)
{
ids += '/' + userIds[i];
}
// Do an AJAX request to update the displayed search results.
$('#profileArea').load('<?php echo base_url() . '/index.php/search/displayProfiles' ?>' + ids);
}
// Add mouse listeners to browser buttons.
$('#previous').click(function()
{
if(currentPage > 0)
{
// Load previous page.
getPage(--currentPage);
// Show next button again, if neccessary.
if($('#next').is(':hidden'))
{
$('#next').show();
}
// Hide previous button if back at first page.
if(currentPage == 0)
{
$('#previous').hide();
}
}
});
$('#next').click(function()
{
if(currentPage < nofPages - 1)
{
// Load next page.
getPage(++currentPage);
// Show prev button, if it was hidden before.
if($('#previous').is(':hidden'))
{
$('#previous').show();
}
// Hide next button if at last page.
if(currentPage == nofPages - 1)
{
$('#next').hide();
}
}
});
});
</script>
<file_sep><?php
$base = base_url() . 'index.php';
?>
</section>
<footer>
<ul>
<li><a href="<?php echo "$base/about"?>">About</a></li>
<li><a href="<?php echo "$base/howto"?>">Help</a></li>
<li><a href="<?php echo "$base/termsofuse"?>">Terms of use</a></li>
<li><a href="<?php echo "$base/privacypolicy"?>">Privicy (nihil.)</a></li>
</ul>
</footer>
</div>
</body>
</html> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class ProfileUpdate extends CI_Controller {
// After succesfully validating a filled in form, use the POST data to add a new user to the
// database.
private function _updateUser()
{
// Load libraries and models.
$this->load->library('picture');
$this->load->model('user');
// Fetch input.
$input = $this->input->post();
// This will be contain the parsed data as added to the user model.
$data = array();
// Values that can be directly put to the data array (after a rename of their keys).
$rename = array(
'username' => 'username',
'firstName' => 'firstName',
'lastName' => 'lastName',
'email' => 'email',
'gender' => 'gender',
'description' => 'description',
'ageprefmin' => 'minAgePref',
'ageprefmax' => 'maxAgePref',
'birthdate' => 'birthdate'
);
foreach($rename as $key => $newkey)
{
if(isset($input[$key]))
$data[$newkey] = $input[$key];
}
// Parse gender preference.
$data['genderPref'] = $input['genderPref'] == 2 ? null : (int) $input['genderPref'];
// Parse brand preferences.
if(isset($input['brandpref']))
$brands = array_keys(array_filter($input['brandpref']));
$profile = $this->user->load($this->authentication->currentUserId());
foreach($profile as $key => $val) {
if(isset($data[$key]))
$profile[$key] = $data[$key];
}
// Process uploaded image. 'picture' will be set to null if none are specified.
$data['picture'] = $this->picture->uploadAndProcess();
if(!$data['picture'] == null)
{
$profile['picture'] = $data['picture'];
}
// Actually create the user.
$this->user->updateSelf($profile);
}
public function index()
{
$this->load->model('user','',true);
$this->load->library(array('personality', 'form_validation', 'upload'));
$this->load->helper(array('html', 'form'));
$this->load->view('header',array("pagename" => "Edit Profile"));
$this->load->view('loginbox');
$this->load->view('nav');
$config = array(
array(
'field' => 'firstName',
'label' => 'Firstname',
'rules' => 'required'
),
array(
'field' => 'lastName',
'label' => 'Lastname',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|valid_email'
),
array(
'field' => 'gender',
'label' => 'Gender',
'rules' => 'required'
),
array(
'field' => 'birthdate',
'label' => 'Birthdate',
'rules' => 'required|alpha-dash|callback_validateDate'
),
array(
'field' => 'description',
'label' => 'About you',
'rules' => ''
),
array(
'field' => 'genderPref',
'label' => 'Gender preference',
'rules' => 'required'
),
array(
'field' => 'ageprefmin',
'label' => 'Minimum age',
'rules' => 'required|numeric|greater_than[17]|callback_validAgePref[ageprefmax]'
),
array(
'field' => 'ageprefmax',
'label' => 'Maximum age',
'rules' => 'required|numeric|less_than[123]'
),
array(
'field' => 'picture',
'label' => 'Upload picture',
'rules' => ''
)
);
// The list of brands is loaded from the database
$this->load->model('brand');
$brands = $this->brand->getBrands();
foreach($brands as $brand)
{
$config[] = array(
'field' => $brand,
'label' => $brand,
'rules' => '');
}
// And all the rules are added to the form_validation
$this->form_validation->set_rules($config);
// All errors are placed in a div with the error class
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
// The profile is loaded
$profile = $this->user->load($this->authentication->currentUserId());
// Check if there is a post result. If there is, the brandpref list is handed
// to the brandCheckBoxes function for re-populating.
if(array_key_exists('brandpref',$_POST)) {
$brandpref = $_POST['brandpref'];
}
else {
// If there is a profile, its brandspreferences are used as the re-populate list.
$brandpref = $profile['brands'];
}
$data = array('profile' => $profile,
'brands' => $brands,
'brandPreferences' => $brandpref);
// Display the form while it is invalid.
if ($this->form_validation->run() === false)
{
$this->load->view('content/registerView', $data);
}
else
{
// The form input is validated, the user is registeredand the succesmessage is displayed.
$this->_updateUser();
$data['succesmessage'] = "You have succesfully updated your profile";
$this->load->view('content/registerView', $data);
}
$this->load->view('footer');
}
/**
*
* Our own date-validation rule.
* @param string $date The date that will be checked
* @return boolean False if failed
*/
public function validateDate($date)
{
$dummy = array();
$validDate = !!preg_match_all('/[0-9]{4}-[0-9]{2}-[0-9]{2}/', $date, $dummy);
$year; $month; $day;
sscanf($date, '%D-%D-%D', $year, $month, $day);
$thisYear = date('o');
$validDate &= $year > $thisYear - 122 && $year <= $thisYear - 18
&& $month >= 1 && $month <= 12
&& $day >= 1 && $day <= 31;
if(!$validDate) {
if(is_numeric($year) && $year < $thisYear - 122)
$this->form_validation->set_message('validateDate',
'If you are older than 122, please contact the Guiness Book of World Records.');
else
$this->form_validation->set_message('validateDate',
'Invalid date');
return false;
}
else {
return true;
}
}
/**
*
* Checks if ageprefmin is smaller or equal to ageprefmax.
* @param int $ageprefmin The minimum age preference
* @param string $ageprefmax The name for the maximum age preference in the post
* @return boolean false if fails
*/
public function validAgePref($ageprefmin, $ageprefmax)
{
if($ageprefmin > $this->input->post($ageprefmax)) {
$this->form_validation->set_message('validAgePref',
'The %s field can not be greater than the Maximum age');
return false;
}
else {
return true;
}
}
public function check_password($password)
{
$this->load->model('user','',true);
$profile = $this->user->load($this->authentication->currentUserID(), array('email'));
if($this->user->lookup($profile['email'], $password) == null) {
$this->form_validation->set_message('check_password',
'Incorrect password');
return false;
}
else return true;
}
}
?><file_sep>
<?php
echo heading("Welcome $firstName $lastName!",3). br(2).
"You can log in with your email and password.<br />";
?><file_sep><section id='registerblock'>
<?php
if(isset($succesmessage))
echo heading($succesmessage, 2). br(2);
/*
* First some variables needed for creating and populating the fields are defined
*/
// If no profile is submitted, profileEdit is set to false and the profile to null.
$profileEdit = isset($profile);
if(!$profileEdit) $profile = null;
// Some inputs are selects from a list of possibilities.
// The list of gender options is prepared
$genders = array( '0' => 'Male',
'1' => 'Female');
// The list of possible gender preferences
$genderprefs = array( '0' => 'Male',
'1' => 'Female',
'2' => 'Either');
/*
* Then some functions for building the html for the form fields
*/
/**
* The brandprefs are returned in an array. CodeIgniter can not handle an array in its value
* set functions, so we made our own. :-)
*
* brandCheckBoxes turns an array of brands into html which displays a list of checkboxes.
* If the form was posted, the checkboxes are re-populated.
* @param array $brands List of brands
* @param array $brandprefs List of checked brands
* @return string html for a list of checkboxes
*/
function brandCheckBoxes(array $brands, array $brandprefs = null)
{
$html = form_fieldset("Brand-preferences", array('class' => 'brands')).
form_error('brandpref[]') .'<ul class="brandslist">';
foreach($brands as $brand) {
$html .= '<li>'. form_checkbox('brandpref[]',$brand,
$brandprefs != null && in_array($brand,$brandprefs)). $brand. "</li>";
}
return $html. "</ul></fieldset>";
}
function buildField($heading, $name, $size = 50, $profileEdit = false,
array $profile = null, $password = false)
{
$output = heading($heading, 4). form_error($name);
// If the field is a passwordfiel, it should not be re-populated
if($password) $value = '';
else if($profileEdit) $value = set_value($name, $profile[$name]);
else $value = set_value($name);
// The input parameters are set.
// If the field is a password, the type is set to password, else text.
$data = array('name' => $name,
'value' => $value,
'size' => $size,
'type' => $password ? 'password' : 'text'
);
$output .= form_input($data). br(2);
echo $output;
}
function buildDropdown($heading, $name, $filling, $profileEdit = false, array $profile = null)
{
$output = heading($heading, 4). form_error($name);
$output .= form_dropdown($name, $filling, set_value($name, $profile[$name])). br(2);
echo $output;
}
/*
* Start of the form
*/
if($profileEdit)
echo form_open_multipart('profileUpdate');
else echo form_open_multipart('register');
// If the profile is being edited, display a welcome message with the username
if($profileEdit) echo heading('Hi '. $profile['username']. '!', 2);
// Else, offer a field to register a username
else buildField('Username', 'username');
buildField('First name', 'firstName', 50, $profileEdit, $profile);
buildField('Last name', 'lastName', 50, $profileEdit, $profile);
// If the profile is being edited, one field for the old password and two for the new one are displayed
if($profileEdit) {
/*buildField('Old password', '<PASSWORD>', 50, false, null, true);
buildField('New password', '<PASSWORD>', 50, false, null, true);
buildField('Repeat new password', '<PASSWORD>conf', 50, false, null, true);*/
}
else { // Else, only two password fields are shown to register a password
buildField('Password', '<PASSWORD>', 50, false, null, '<PASSWORD>');
buildField('Repeat password', '<PASSWORD>', 50, false, null, 'password');
}
buildField('Email', 'email', 50, $profileEdit, $profile);
buildDropdown('Gender', 'gender', $genders, $profileEdit, $profile);
buildField('Birthdate (yyyy-mm-dd)', 'birthdate', 50, $profileEdit, $profile);
?>
<h4>About me</h4>
<?php echo form_error('description'); ?>
<textarea name="description" rows="5" cols="37"><?php echo set_value('description', $profile['description']); ?></textarea>
<br /><br />
<?php buildDropdown('Gender preference', 'genderPref', $genderprefs, $profileEdit, $profile); ?>
<h4>Age preference</h4>
<?php echo form_error('ageprefmin');
echo form_error('ageprefmax');
$min = $profileEdit ? $profile['minAgePref'] : 18;
$max = $profileEdit ? $profile['maxAgePref'] : 122; ?>
Minimum:
<input type="text" name="ageprefmin" value="<?php echo set_value('ageprefmin', $min); ?>"/>
Maximum:
<input type="text" name="ageprefmax" value="<?php echo set_value('ageprefmax', $max); ?>"/>
<br /><br />
<h4>Upload picture (JPEG format required, should be smaller than 1MB) </h4>
<?php echo form_error('picture');
echo form_upload('picture'); ?>
<br /><br />
<?php echo brandCheckBoxes($brands, $brandPreferences). br(); ?>
<?php
if(!$profileEdit) {
$questions = array(1 => array('A' => "Ik geef de voorkeur aan grote groepen mensen, met een grote diversiteit.",
'B' => "Ik geef de voorkeur aan intieme bijeenkomsten met uitsluitend goede vrienden."),
2 => array('A' => "Ik doe eerst, en dan denk ik.",
'B' => "Ik denk eerst, en dan doe ik."),
3 => array('A' => "Ik ben makkelijk afgeleid, met minder aandacht voor een enkele specifieke taak.",
'B' => "Ik kan me goed focussen, met minder aandacht voor het grote geheel."),
4 => array('A' => "Ik ben een makkelijke prater en ga graag uit.",
'B' => "Ik ben een goede luisteraar en meer een privé-persoon."),
5 => array('A' => "Als gastheer/-vrouw ben ik altijd het centrum van de belangstelling.",
'B' => "Als gastheer/-vrouw ben altijd achter de schermen bezig om te zorgen dat alles soepeltjes verloopt."),
6 => array('A' => "Ik geef de voorkeur aan concepten en het leren op basis van associaties.",
'B' => "Ik geef de voorkeur aan observaties en het leren op basis van feiten."),
7 => array('A' => "Ik heb een groot inbeeldingsvermogen en heb een globaal overzicht van een project.",
'B' => "Ik ben pragmatisch ingesteld en heb een gedetailleerd beeld van elke stap."),
8 => array('A' => "Ik kijk naar de toekomst.",
'B' => "Ik houd mijn blik op het heden gericht."),
9 => array('A' => "Ik houd van de veranderlijkheid in relaties en taken.",
'B' => "Ik houd van de voorspelbaarheid in relaties en taken."),
10 => array('A' => "Ik overdenk een beslissing helemaal.",
'B' => "Ik beslis met mijn gevoel."),
11 => array('A' => "Ik werk het beste met een lijst plussen en minnen.",
'B' => "Ik beslis op basis van de gevolgen voor mensen."),
12 => array('A' => "Ik ben van nature kritisch.",
'B' => "Ik maak het mensen graag naar de zin."),
13 => array('A' => "Ik ben eerder eerlijk dan tactisch.",
'B' => "Ik ben eerder tactisch dan eerlijk."),
14 => array('A' => "Ik houd van vertrouwde situaties.",
'B' => "Ik houd van flexibele situaties."),
15 => array('A' => "Ik plan alles, met een to-do lijstje in mijn hand.",
'B' => "Ik wacht tot er meerdere ideeën opborrelen en kies dan on-the-fly wat te doen.",),
16 => array('A' => "Ik houd van het afronden van projecten.",
'B' => "Ik houd van het opstarten van projecten.",),
17 => array('A' => "Ik ervaar stress door een gebrek aan planning en abrupte wijzigingen.",
'B' => "Ik ervaar gedetailleerde plannen als benauwend en kijk uit naar veranderingen."),
18 => array('A' => "Het is waarschijnlijker dat ik een doel bereik.",
'B' => "Het is waarschijnlijker dat ik een kans zie."),
19 => array('A' => "\"All play and no work maakt dat het project niet afkomt.\"",
'B' => "\"All work and no play maakt je maar een saaie pief.\""),
);
// The questions order is randomized
shuffle($questions);
// The C-answere, which is always the same, is added to the questions. Of course, after the shuffle.
$questions['C'] = "Ik zit er eigenlijk tussenin.";
// The questions array is turned into valid html with re-population
$questionsHtml = array();
for($q = 1; $q < count($questions); $q++) {
if(form_error("question$q") != '') $line = form_error("question$q");
else $line = br();
echo heading("Question $q:",4). $line.
form_radio("question$q",'A',set_value("question$q") == 'A'). utf8_encode($questions[$q-1]['A']). br().
form_radio("question$q",'B',set_value("question$q") == 'B'). utf8_encode($questions[$q-1]['B']). br().
form_radio("question$q",'C',set_value("question$q") == 'C'). utf8_encode($questions['C']). br(2);
}
}
?>
<br />
<div><input type="submit" value="Submit" /></div>
</form>
</section><file_sep><?php
class LoginSystem extends CI_Controller
{
function __construct() {
parent::__construct();
}
public function login()
{
$email = $this->input->post('email');
$password = $this->input->post('password');
if($email === false || $password === false)
{
// Show regular page if nothing in POST.
$this->index();
return;
}
$id = $this->authentication->login($email, $password);
$error = null;
if($id === null)
{
$error = 'Login error: this e-mail/password combination does not exist.';
}
$this->index($error);
}
public function logout()
{
// Log out the current user and show homepage.
$this->authentication->logout();
$this->index();
}
public function delete()
{
$sure = $this->input->post('sure');
if($sure == 'yes')
{
$this->model->load('User', 'user');
$this->user->deleteSelf();
$this->authentication->logout();
}
}
}
?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Configuration extends CI_Model
{
/**
* Constants representing similarity measure coefficients.
*/
const SMC_DICE = 0,
SMC_JACCARD = 1,
SMC_COSINE = 2,
SMC_OVERLAP = 3;
/**
* Load the current settings.
*
* @return array(string => int/float) The settings and their current values.
*/
public function load()
{
$settings = array(
'similarityMeasure',
'xFactor',
'alpha'
);
$result = $this->db->select($settings)
->from('Configuration')
->get()->row_array();
return $result;
}
/**
* Save changed settings.
*
* @param array(string => int/float) $data The changed settings. Should already be validated!
*/
public function save($data)
{
// Make sure an admin is doing this.
$this->authentication->assertAdministrator();
$this->db->update('Configuration', $data);
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
include_once('profilebrowser.php');
class Home extends ProfileBrowser
{
public function index($msg = null)
{
$this->load->model('user','',true);
$this->load->view('header',array('pagename' => 'Home'));
$this->load->view('loginbox');
$this->load->view('nav');
// Show message if specified.
if($msg !== null)
{
$this->parser->parse('msgbox', array('message' => $msg));
}
$this->load->view('content/showcase');
// Get a list of 600 userid's in random order and put them in the profile browser
$this->userBrowser($this->user->getRandomUsers(600));
$this->load->view('footer');
}
public function updateUser()
{
$this->load->library('form_validation');
if ($this->form_validation->run() == false) {
$this->load->view('myform');
}
else {
$this->load->view('formsuccess');
}
$this->load->helper('html');
$data = array('user' => array('text' => 'Smoked yah!'));
$this->load->view('content/testView', $data);
}
public function login()
{
$email = $this->input->post('email');
$password = $this->input->post('password');
if($email === false || $password === false)
{
// Show regular page if nothing in POST.
$this->index();
return;
}
$id = $this->authentication->login($email, $password);
$error = null;
if($id === null)
{
$error = 'Login error: this e-mail/password combination does not exist.';
}
$this->index($error);
}
public function logout()
{
// Log out the current user and show homepage.
$this->authentication->logout();
$this->index();
}
public function delete()
{
$sure = $this->input->post('sure');
if($sure == 'yes')
{
$this->load->model('User', 'user');
$this->user->deleteSelf();
$this->authentication->logout();
}
}
}
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Matching extends CI_Model
{
// Determine the length on the union of two arrays in O(n). $arrayA should've been flipped.
private function _unionLength($arrayA, $arrayB)
{
$result = count($arrayA);
foreach($arrayB as $val)
{
if(!isset($arrayA[$val['brandName']]))
{
++$result;
}
}
return $result;
}
// Determine the length on the intersection of two arrays in O(n). $arrayA should've been
// flipped.
private function _intersectLength($arrayA, $arrayB)
{
$result = 0;
foreach($arrayB as $val)
{
if(isset($arrayA[$val['brandName']]))
{
++$result;
}
}
return $result;
}
private function _distance($similarityMeasure, $xFactor, $userA, $userB)
{
// First determine distance between personality types and preferences.
$pd1 = ($userA->personalityI - $userB->preferenceI)
- ($userA->personalityN - $userB->preferenceN)
- ($userA->personalityT - $userB->preferenceT)
- ($userA->personalityJ - $userB->preferenceJ);
$pd2 = ($userB->personalityI - $userA->preferenceI)
- ($userB->personalityN - $userA->preferenceN)
- ($userB->personalityT - $userA->preferenceT)
- ($userB->personalityJ - $userA->preferenceJ);
// Take maximum of absolute distances and divide by four.
$personalityDistance = max(abs($pd1), abs($pd2)) / 4;
// Make the brand names of userA keys instead of values, effectively turning it into a hash
// table with O(1) lookup time.
$brandKeys = array_flip($userA->brands);
// Calculate distance between brand preferences by using the currently condifured
// similarity measure.
$alen = count($userA->brands);
$blen = count($userB->brands);
$i = $this->_intersectLength($brandKeys, $userB->brands);
$similarity;
switch($similarityMeasure)
{
case 0: // Dice
$similarity = 2 * $i / ($alen + $blen);
break;
case 1: // Jaccard
$similarity = $i / $this->_unionLength($brandKeys, $userB->brands);
break;
case 2: // cosine
$similarity = $i / (sqrt($alen) * sqrt($blen));
break;
case 3: // overlap
$similarity = $i / min($alen, $blen);
break;
}
// Brand distance is the opposite of the brand's similarity.
$brandDistance = 1 - $similarity;
// Now return the total distance based on the current x-factor.
return $xFactor * $personalityDistance
+ (1 - $xFactor) * $brandDistance;
}
/**
* Build a list of all users matching to a certain one, sorted on distance.
*
* @param $userId The id of the user to match on.
*
* @return array(int) The userId's of the matching users.
*/
public function matchingList($userId)
{
// Query expression to determine the age of a user.
$age = "(strftime('%Y', 'now') - strftime('%Y', birthdate)
- (strftime('%j', 'now') < strftime('%j', birthdate)))";
// Select neccessary data from user to match with.
$user = $this->db->select(array('gender', 'genderPref', 'birthdate', 'minAgePref',
"$age AS age", 'maxAgePref',
'personalityI', 'personalityN', 'personalityT',
'personalityJ', 'preferenceI', 'preferenceN',
'preferenceT', 'preferenceJ'))
->from('Users')
->where('userId', $userId)
->get()->row();
if(!$user)
{
throw new Exception('User not found.');
}
// Start building a query on the users table.
// TODO: Specify which columns are necessary.
$query = $this->db->select()->from('Users');
// First disallow matching the user with itself. Because recommending people to date
// themselves would be pretty weird.
$query->where('userId <>', $userId);
// Constrain on gender and mutual preference.
if($user->genderPref !== null)
{
$query->where('gender', $user->genderPref);
}
// Note: We only append a zero or one to the query, therefore this is not unsafe.
$query->where('(genderPref IS NULL OR genderPref = ' . ($user->gender ? '1' : '0') . ')');
// Now constrain on mutual age preference.
$query->where("$age >=", (int) $user->minAgePref);
$query->where("$age <=", (int) $user->maxAgePref);
$query->where('minAgePref <=', (int) $user->age);
$query->where('maxAgePref >=', (int) $user->age);
// Do query.
$matches = $query->get()->result();
// Determine brand preferences of current user.
$brands = $this->db->select('ub.brandName')
->from('UserBrands ub')
->join('Brands b', 'ub.brandName = b.brandName', 'left')
->where('userId', $userId)
->get()->result();
$user->brands = array();
foreach($brands as $brand)
{
$user->brands[] = $brand->brandName;
}
// Determine current similarity measure and x-factor.
$configs = $this->db->select(array('similarityMeasure', 'xFactor'))
->from('Configuration')
->get()->row();;
// Now compute personality distances between this users and possible matches.
$distances = array();
foreach($matches as &$match)
{
// First determine brand preferences for this user.
$match->brands = $this->db->select('ub.brandName')
->from('UserBrands ub')
->join('Brands b', 'ub.brandName = b.brandName', 'left')
->where('userId', $match->userId)
->get()->result_array();
// Now calculate the distance to this user.
$distances[] = $this->_distance($configs->similarityMeasure, $configs->xFactor, $user, $match);
}
// Only return the id's.
foreach($matches as &$match)
{
$match = $match->userId;
}
// Sort the matches on these distances.
array_multisort($distances, SORT_NUMERIC, $matches);
// Return the ordered matches.
return $matches;
}
}<file_sep>Webtechnologie practicum 3 - Datingsite
===============================================================================
= Door: =
= <NAME> - 3470644 =
= <NAME> - 3470784 =
= =
= URL website: =
= www.students.science.uu.nl/~3470784/webtech3 =
===============================================================================
_______________________________________________________________________________
Geteste browsers:
- Mozilla Firefox
- Google Chrome
_______________________________________________________________________________
Bestanden:
- Een databasemodel is te vinden in dbmodel.png.
- De databasedefinitie staat in database.sql.
- brands.txt bevat een lijst van gebruikte merknamen.
- De daadwerkelijke database (met de creatieve naam database.db) staat in www/database.
- In de www-map staat alles wat op de server dient te staan. www/system bevat de CodeIgniter
-libraries, terwijl in www/application de daadwerkelijke applicatiecode staat, op de manier die
CodeIgniter vereist.
- www/img bevat afbeeldingen, www/js bevat JQuery, www/css de stylesheets, www/uploads wordt als
tijdelijke opslagruimte voor geüploade foto's gebruikt, voordat deze worden verwerkt.
- Alle submappen van www, behalve css, img en js, worden afgeschermt door een .htaccess-bestand
die niemand toestaat. Hierdoor is het niet mogelijk bijvoorbeeld via de URL eens even de inhoud
van de database te bekijken. www/.htaccess herschrijft verder de 'http' in de URL om naar
'https', om HTTPS af te dwingen voor de gehele website.
_______________________________________________________________________________
Toelichting:
- Elke pagina begint met drie 'header' views, namelijk header (begintags, titel e.d.), nav (de
navigatiebalk), en loginbox (waarmee anonieme gebruikers kunnen inloggen of naar het
registratieformulier gaan en geregistreerde gebruikers kunnen uitloggen of hun account deleten).
Elke pagina wordt ook afgesloten met een 'footer'.
- De home-controller is de belangrijkste controller, die zowel het inloggen regelt als de
hoofdpagina weergeeft.
- Voor authenticatie is de authentication-library, die weer gebruik maakt van CodeIgniter's sessie-
mechanisme en de database. In de sessiedata van een ingelogde gebruiker wordt opgeslagen wat
de 'userId' van deze gebruiker is, aan de hand waarvan gegevens uit de database kunnen worden
gehaald. CodeIgniter zorgt ervoor dat sessie-id's in de cookie van de gebruiker gematcht worden
met de database.
- Het model 'user' bevat verschillende methoden die betrekking hebben op de gebruikerstabel in de
database, zoals het laden van gebruikers, het creeëren van net geregistreerde gebruikers en het
toevoegen van likes.
- Het model 'matching' voert matching uit met een bepaalde gebruiker. Het filteren van gebruikers
op basis van leeftijd(svoorkeur) en geslacht(svoorkeur) gebeurt via de query, terwijl het
sorteren op basis van matching distance gebeurt op PHP-niveau.
- De profile-view representeerd een gebruikersprofiel, dit kan zowel een kort overzicht voor
zoekresultaten zijn als de volledige pagina die ook nog eens bewerkbaar kan zijn voor de
eigenaar van het profiel.
- De zoekfuncties in de search-controller (zowel zoeken op eigenschappen als matchende gebruikers
in volgorde opvragen) leveren een lijst van user identifiers op (net als de generator van zes
willekeurige gebruikers uit het usermodel), deze kunnen vervolgens worden gebruikt door de
'profilebrowser'-controller. Deze weergeeft de eerste zes profielen en plakt alle (of tenminste
de eerste 600, verder zal de gebruiker niet doorklikken) opgeleverde userId's in een Javascript
(de searchbrowser-view). Dit script vraagt vervolgens, na het klikken op de next- of previous-
knop, via AJAX de profielen te tonen van de volgende zes id's. Deze identifiers worden
simpelweg via de URL doorgegeven.
_______________________________________________________________________________
Testadminstrator:
- Gebruikersnaam: admin
- Wachtwoord: puddingtaart
Testgebruikers:
- E-mail: <EMAIL>
- Wachtwoord: swordfish
- E-mail: <EMAIL>
- Wachtwoord: 0xE29883
<file_sep><?php
$base = base_url() . 'index.php/search/likes';
?>
<div id="likebox">
<h1>What do you want to display?</h1>
<a href="<?php echo "$base/mutual" ?>">People you like, that like you</a><br/>
<a href="<?php echo "$base/liking" ?>">People liking you</a><br/>
<a href="<?php echo "$base/liked" ?>">People you like</a><br/>
</div><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Personality
{
/**
* This function takes an associative array containing personality values (e.g. the result of
* User::load); these values have keys 'personalityI', 'personalityN', 'personalityT' or
* 'personalityJ' and a floating point number between 0 and 1 as value. Each of these present
* in the input array will either be returned directly or, if their value is lower than 0.5, the
* opposite letter of the same dicotomy will be given instead.
*
* @param array(string => mixed) $arr The input associative array. Will not be modified.
* @param bool $preference If true, this will work on preferences rather than
* own personalities.
*
* @return array(string => float) The resulting dominant personality values, e.g.
* array(I => 0.8, N => 0.7, T => 0.51, J => 0.65).
*/
public function dominantPersonalityComponents($arr, $preference = false)
{
// Determine whether to look at personality or preference.
$subject;
if($preference)
{
$subject = 'preference';
}
else
{
$subject = 'personality';
}
$slen = strlen($subject);
// Mapping of components to their opposites.
$opposites = array('I' => 'E', 'N' => 'S', 'T' => 'F', 'J' => 'P');
// Filter personality/preference values from array.
$result = array();
foreach($arr as $key => $val)
{
// Check whether key starts with 'personality'
if(substr_compare($subject, $key, 0, $slen) === 0)
{
// Component is I, N, T or J.
$component = $key[$slen];
if($val < 0.5)
{
// Component is not dominant, give opposite one instead.
$component = $opposites[$component];
// Invert value.
$val = 1 - $val;
}
// Add to result.
$result[$component] = $val;
}
}
return $result;
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class About extends CI_Controller
{
public function index($msg = null)
{
$this->load->view('header',array("pagename" => "About"));
$this->load->view('loginbox');
$this->load->view('nav');
$this->load->view('footer');
}
}
?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
include_once('profilebrowser.php');
class Search extends ProfileBrowser
{
// Returns null when input is valid, or an error message otherwise.
private function _validateInput($input)
{
// Generic error message.
$genericError = 'Something went wrong while processing your search query.';
// Check whether keys are correct.
$required = array('ownGender', 'genderPref', 'ownAge', 'minAge', 'maxAge', 'attitude',
'perceiving', 'judging', 'lifestyle');
if(sort(array_keys($input)) != sort($required))
{
return $genericError;
}
if(!in_array($input['ownGender'], array('male', 'female')))
{
return $genericError;
}
if(!in_array($input['genderPref'], array('male', 'female', 'either')))
{
return $genericError;
}
foreach (array($input['ownAge'], $input['minAge'], $input['maxAge']) as $age)
{
if($age < 18 || $age > 122)
{
return "Please enter a valid age: a number between 18 and 122.";
}
}
if($input['minAge'] > $input['maxAge'])
{
return "Maximal age should not be lower than minimal age.";
}
return null;
}
// Displays the matching users. Or nothing, if no user is logged in.
public function matching()
{
// Confirm whether the user is logged in.
if(!$this->authentication->userLoggedIn())
{
throw new Exception('User is not logged in.');
}
$this->load->model('Matching', 'matching');
// Header and navigation bar.
$this->load->view('header');
$this->load->view('nav');
$this->load->view('loginbox');
$current = $this->authentication->currentUserId();
if($current !== null)
{
$list = $this->matching->matchingList($current);
$this->userBrowser($list);
}
// Footer.
$this->load->view('footer');
}
/**
* Shows the users that have a certain like status, along with three buttons to select which
* to view.
*
* @param string $likeStatus Can be 'liking' (for others liking the user), 'liked'
* (for those being liked) and 'mutual' (when both users like each
* other). If empty, only the selection box is shown.
*/
public function likes($likeStatus = '')
{
// Assert the user is logged in.
if(!$this->authentication->userLoggedIn())
{
echo 'Access denied.';
return;
}
// Load user model.
$this->load->model('User', 'user');
// Reformat input to be usable with model-function.
$status = null;
if($likeStatus == 'liking')
{
$status = array(false, true);
}
else if($likeStatus == 'liked')
{
$status = array(true, false);
}
else if($likeStatus == 'mutual')
{
$status = array(true, true);
}
// Header and navigation bar.
$this->load->view('header');
$this->load->view('nav');
$this->load->view('loginbox');
// Likes selection box.
$this->load->view('likebox');
// View results if something has been selected.
if($status !== null)
{
// Get users to show.
$users = $this->user->usersWithLikeStatus($status);
// Use browser with id's.
$this->userBrowser($users);
}
// Footer.
$this->load->view('footer');
}
public function index()
{
// Header and navigation bar.
$this->load->view('header', array("pagename" => "Search"));
$this->load->view('nav');
$this->load->view('loginbox');
// Fetch search query data, if present.
$input = $this->input->post();
$error = null;
$doSearch = false;
$data;
// If something in POST, it means a search query has been done.
if($input && count($input) > 0)
{
// Validate input.
$error = $this->_validateInput($input);
if($error === null)
{
$doSearch = true;
}
// Specify error and data that should be left filled in form from last query.
$data = array(
'error' => $error,
'sFemale' => $input['ownGender'] == 'female' ? 'selected' : '',
'malePref' => $input['genderPref'] == 'male' ? 'selected' : '',
'femalePref' => $input['genderPref'] == 'female' ? 'selected' : '',
'ownAge' => $input['ownAge'],
'minAge' => $input['minAge'],
'maxAge' => $input['maxAge'],
'sI' => $input['attitude'] == 'I' ? 'selected' : '',
'sN' => $input['perceiving'] == 'N' ? 'selected' : '',
'sF' => $input['judging'] == 'F' ? 'selected' : '',
'sP' => $input['lifestyle'] == 'P' ? 'selected' : '',
'brands' => $input['brands']
);
}
else
{
/*$data = array_fill_keys(
array('error', 'sFemale', 'malePref', 'femalePref', 'ownAge', 'minAge', 'maxAge',
'sI', 'sN', 'sF', 'sP', 'brands'), null);*/
$keys = array('error', 'sFemale', 'malePref', 'femalePref', 'ownAge', 'minAge',
'maxAge', 'sI', 'sN', 'sF', 'sP', 'brands');
foreach($keys as $key)
{
$data[$key] = null;
}
}
// Display the search form with filled in values and possible error.
$this->parser->parse('searchform', $data);
// If a search is to be done. Do so and display first six profiles.
if($doSearch)
{
// Load search model.
$this->load->model('SearchModel', 'search');
// Perform the search operation.
$ids = $this->search->search($input);
$this->userBrowser($ids);
}
// Footer.
$this->load->view('footer');
}
}
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Datingsite extends CI_Controller
{
public function index($msg = null)
{
$this->load->model('user','',true);
$this->load->library('personality');
$this->load->helper('html');
$this->load->helper('form');
$this->load->view('header');
$this->load->view('loginbox');
$this->load->view('nav');
$this->load->view('content/showcase');
$data = array ( 'profileType' => 'small',
'profiles' => $this->_makeProfiles());
$this->load->view('content/profile', $data);
$this->load->view('footer');
}
public function updateUser()
{
$this->load->library('form_validation');
if ($this->form_validation->run() == false) {
$this->load->view('myform');
}
else {
$this->load->view('formsuccess');
}
$this->load->helper('html');
$data = array('user' => array('text' => 'Smoked yah!'));
$this->load->view('content/testView', $data);
}
private function _buildUser($userId) {
$user = $this->user->load($userId);
$user['personality'] = $this->personality->dominantPersonalityComponents($user);
$user['preference'] = $this->personality->dominantPersonalityComponents($user, true);
return $user;
}
/* Makes the small profiles for the homepage
*/
private function _makeProfiles()
{
//$this->load->library('parser');
//$data = array(
$profiles = array(1 => $this->user->getUserProfile(1),
2 => $this->user->getUserProfile(2),
3 => $this->user->getUserProfile(3),
4 => $this->user->getUserProfile(4),
5 => $this->user->getUserProfile(5),
6 => $this->user->getUserProfile(6));
//$this->parser->parse('content/profiles-small', $data);
return $profiles;
}
}
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Picture
{
// Dimensions of picture thumbnails.
const THUMBNAIL_WIDTH = 125,
THUMBNAIL_HEIGHT = 150;
/**
* Processes an uploaded picture by resizing it and moving it from the uploads to the the
* picture folder. The uploaded file will be deleted afterwards.
*
* @param string $picFile The path of the uploaded image, including file name.
*
* @return string The filename of the picture, excluding its path (which is 'img/pictures').
* On failure, null is returned.
*/
public function process($picFile)
{
// Copy 250x300 version of uploaded picture to img-folder, using GD.
$source = imagecreatefromjpeg($picFile);
list($sourceWidth, $sourceHeight) = getimagesize($picFile);
$dest = imagecreatetruecolor(self::THUMBNAIL_WIDTH, self::THUMBNAIL_HEIGHT);
$success = imagecopyresampled($dest, $source, 0, 0, 0, 0,
self::THUMBNAIL_WIDTH, self::THUMBNAIL_HEIGHT, $sourceWidth, $sourceHeight);
if($success)
{
// Generate picture filename (16 random lowercase characters + .jpg).
$picture = '';
for($i = 0; $i < 16; ++$i)
{
$picture .= chr(rand(ord('a'), ord('z')));
}
$picture .= '.jpg';
// Save image.
$success = imagejpeg($dest, 'img/pictures/' . $picture);
}
// Delete image upload.
unlink($picFile);
if($success)
{
// Add Image filename to data.
return $picture;
}
else
{
return null;
}
}
/**
* Uploads a file in the POST-body and processes it.
*
* @return string Same as the function process($picFile).
*/
public function uploadAndProcess($fieldname = 'picture')
{
// Configure and load the upload library.
$config = array(
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png',
'max_size' => '1000',
'allowed_types' => 'jpg' // Only jpegs are supported.
);
$ci =& get_instance();
$ci->load->library('upload');
$ci->upload->initialize($config);
// Do the actual upload.
$success = $ci->upload->do_upload($fieldname);
if($success)
{
$data = $ci->upload->data();
// Process the uploaded file.
return $this->process($data['full_path']);
}
else
{
//echo $ci->upload->display_errors();
return null;
}
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Model
{
/**
* Indicates whether anonymous users can view the content of a certain column. Columns not in
* this array shouldn't be visible at all. Besides these, viewing brand preferences also does
* not require being logged in.
*/
private $visibility = array(
'username' => true,
'email' => false,
'firstName' => false,
'lastName' => false,
'gender' => true,
'birthdate' => true,
'description' => true,
'minAgePref' => true,
'maxAgePref' => true,
'genderPref' => true,
'personalityI' => true,
'personalityN' => true,
'personalityT' => true,
'personalityJ' => true,
'preferenceI' => true,
'preferenceN' => true,
'preferenceT' => true,
'preferenceJ' => true,
'picture' => false
);
/**
* Returns the columns visibile to the currently active user.
*/
private function visibleColumns()
{
$login = $this->authentication->userLoggedIn();
if($login)
{
return array_keys($this->visibility);
}
else
{
$result = array();
foreach($this->visibility as $col => $visible)
{
if($visible)
{
$result[] = $col;
}
}
return $result;
}
}
/**
* Loads the preferred brands of a user.
*
* @param int $userId The ID of the user.
*
* @return array(string) The preferred brands of this user.
*/
private function loadUserBrands($userId)
{
$result = $this->db->select('ub.brandName')
->from('UserBrands ub')
->join('Brands b', 'ub.brandName = b.brandName', 'left')
->where(array('userId' => $userId))
->get()->result_array();
if(count($result) == 0)
{
throw new Exception('User not found or no brands associated.');
}
$brandNames = array();
foreach($result as $row)
{
$brandNames[] = $row['brandName'];
}
return $brandNames;
}
private function removeInvisibleColumns($data)
{
$login = $this->authentication->userLoggedIn();
$result = array();
foreach($data as $key => $val)
{
if(isset($this->visibility[$key]))
{
if($login || $this->visibility[$key])
{
$result[$key] = $val;
}
}
}
return $result;
}
/**
* Loads the properties of a user visible to the current user. These properties are the values
* of columns in the Users-table plus an entry 'brands' containing an array of strings
* representing brand names preferred by the user.
*
* @param int $userId The identifier of the user to load.
* @param array(string) $properties The properties of the user to load. If null,
* all accessible properties are loaded.
*
* @return array(string => mixed) An associative array of user properties and values.
*/
public function load($userId, $properties = null)
{
// Determine which columns to select.
if($properties !== null)
{
// Filter by wanted properties.
$columns = $this->removeInvisibleColumns($properties);
}
else
{
$columns = $this->visibleColumns();
}
$result = $this->db->select($columns)
->from('Users')
->where(array('userId' => $userId))
->get()->row_array();
if(!$result)
{
throw new Exception('User not found.');
}
$user = $result;
// Add brands if wanted.
if($properties === null || in_array('brands', $properties))
{
$user['brands'] = $this->loadUserBrands($userId);
}
return $user;
}
public function updateSelf($newprops)
{
// Determine which user is logged in.
$userId = $this->authentication->currentUserId();
if($userId === null)
{
throw new Exception('User is not logged in.');
}
//Start a transaction.
$this->db->trans_start();
// Values in Users table to change are all new properties that are also visible columns.
$data = $this->removeInvisibleColumns($newprops);
// Do update.
$this->db->where(array('userId' => $userId))
->update('Users', $data);
// If requested, update brands.
if(isset($newprops['brands']))
{
// First simply remove this user's brands.
$this->db->delete('UserBrands', array('userId' => $userId));
// Now insert new brands.
foreach($newprops['brands'] as $brand)
{
$this->db->insert('UserBrands',
array('userId' => $userId,
'brandName' => $brand));
}
//$this->db->insert_batch('UserBrands', $brandList);
}
// Complete transaction.
$this->db->trans_complete();
}
// Creates a salted SHA-1 hash of a password.
private function hashPassword($password)
{
// Load security helper.
$this->load->helper('security');
// The randomly generated key we specified for session encryption is also perfectly
// suitable to be a salt.
// Also add a smiley face wearing a hat, which is incredibly important.
$salt = $this->config->item('encryption_key') . '<:)';
return do_hash($password . $salt);
}
/**
* Create a new user.
*
* @param array(string => mixed) $data Values to be inserted into the Users table, except for
* the password hash. Data should be already validated!
* @param string $password The user's password. Will be hashed by this function.
* @param array(string) $brands List of preferred brands by this user. There should
* be at least one.
*
* @return int The ID of the newly created user.
*/
public function createUser($data, $password, $brands)
{
// Hash password.
$data['passwordHash'] = $this->hashPassword($password);
//Start a transaction.
$this->db->trans_start();
// Insert new user into table.
$this->db->insert('Users', $data);
// Add preferred brands.
$userId = $this->db->insert_id();
foreach($brands as $brand)
{
$this->db->insert('UserBrands',
array('userId' => $userId,
'brandName' => $brand));
}
// Complete transaction.
$this->db->trans_complete();
return $userId;
}
/**
* Look up a user with a certain e-mail/password combination. To be used for logging in.
*
* @param string $email An e-mail address.
* @param string $password A password, yet unhashed.
* @param string &$username If a user is found, its username is stored in here.
*
* @return int The userId of this user, or null if no such user exists.
*/
public function lookup($email, $password)
{
// Hash the password.
$hash = $this->hashPassword($password);
// Query the user.
$result = $this->db->select('userId')->from('Users')
->where(array('email'=> $email, 'passwordHash' => $hash))
->get()->row();
if(count($result) > 0)
{
return $result->userId;
}
else
{
return null;
}
}
/**
* Delete the currently active user.
*/
public function deleteSelf()
{
// Determine which user is logged in, if any.
$userId = $this->authentication->currentUserId();
if($userId === null)
{
throw new Exception('User is not logged in.');
}
// Delete this user.
$this->deleteUser($userId);
}
public function deleteUser($userId)
{
$this->db->trans_start();
// Also delete references to user in Likes and UserBrands.
$this->db->or_where(array('userLiking' => $userId, 'userLiked' => $userId))
->delete('Likes');
$this->db->delete('UserBrands', array('userId' => $userId));
// Delete user itself.
$this->db->delete('Users', array('userId' => $userId));
$this->db->trans_complete();
}
/**
* Makes the current user 'like' another user.
*
* @param int $likedUser ID of the user to like.
*/
public function like($likedUser)
{
// Determine which user is logged in, if any.
$userId = $this->authentication->currentUserId();
if($userId === null)
{
throw new Exception('Not logged in.');
}
if($userId == $likedUser)
{
throw new Exception("Can't like yourself.");
}
// For learning, retrieve the current alpha setting.
$alpha = $this->db->select('alpha')->from('Configuration')
->get()->row()->alpha;
$beta = 1 - $alpha;
// Start a transaction.
$this->db->trans_start();
// Determine the new personality preference of this user.
$ownPref = $this->db->select(array('preferenceI', 'preferenceN',
'preferenceT', 'preferenceJ'))
->from('Users')
->where('userId', $userId)
->get()->row_array();
$likedPers = $this->db->select(array('personalityI', 'personalityN',
'personalityT', 'personalityJ'))
->from('Users')
->where('userId', $likedUser)
->get()->row_array();
$newPref = array();
foreach(array('I', 'N', 'T', 'J') as $d)
{
$newPref["preference$d"] = $alpha * $ownPref["preference$d"]
+ $beta * $likedPers["personality$d"];
}
// Now update it.
$this->db->where('userId', $userId)
->update('Users', $newPref);
// Add to Likes table (unique and foreign key constraints enforce $likedUser is an
// existing user id and that there are no duplicates).
$this->db->insert('Likes', array(
'userLiking' => $userId,
'userLiked' => $likedUser
));
// Complete transaction.
$this->db->trans_complete();
}
/**
* Indicates the 'like-status' between the current user and another one.
* @param int $otherUser The other user.
*
* @return array(bool) An array, containing two booleans A and B, where A is true iff the
* current user has liked the other one and B is true iff the other user
* likes this one.
*/
public function getLikeStatus($otherUser)
{
$userA = $this->authentication->currentUserId();
$userB = $otherUser;
if($userA === null)
{
throw new Exception('User is not logged in.');
}
// Query whether this user likes the other one.
$likeAB = (bool) $this->db->from('Likes')
->where('userLiking', $userA)
->where('userLiked', $userB)
->get()->row();
// Query whether the other user likes this one.
$likeBA = (bool) $this->db->from('Likes')
->where('userLiking', $userB)
->where('userLiked', $userA)
->get()->row();
return array($likeAB, $likeBA);
}
/**
* Get the id's of all users with a certain like status towards the current user.
*
* @param array(bool) $status Formatted in the same way as the result of getLikeStatus(..).
* An empty array is returned when this is [false, false].
*
* @return array(int) The id's of the users with this status.
*/
public function usersWithLikeStatus($status)
{
// Get current user.
$userId = $this->authentication->currentUserId();
if($userId === null)
{
throw new Exception('User is not logged in.');
}
// Start a transaction.
$this->db->trans_start();
if($status[0])
{
// Find others liked by the current one.
$liked = $this->db->select('userLiked AS userId')->from('Likes')
->where('userLiking', $userId)
->get()->result();
//Only examine id's.
foreach($liked as &$id)
{
$id = $id->userId;
}
}
if($status[1])
{
// Find others liking the current one.
$liking = $this->db->select('userLiking AS userId')->from('Likes')
->where('userLiked', $userId)
->get()->result();
foreach($liking as &$id)
{
$id = $id->userId;
}
}
// Commit transaction.
$this->db->trans_complete();
// Determine what to return.
$result = array();
if($status[0] && $status[1])
{
// Combine liked and liking.
$result = array_intersect($liked, $liking);
}
else if($status[0])
{
$result = $liked;
}
else if($status[1])
{
$result = $liking;
}
return $result;
}
public function getRandomUsers($amount)
{
// Do query.
$result = $this->db->select('userId')
->from('Users')
->order_by('userId', 'random')
->limit($amount)
->get()->result();
// Only return id's.
foreach($result as &$row)
{
$row = $row->userId;
}
return $result;
}
public function getUserProfile($userId)
{
// The library for calculating the personality type is loaded
$this->load->library('personality');
// Load the user data into the profile
$profile = $this->user->load($userId);
$profile['userId'] = $userId;
// Get the dominant personality and preference and add them to the profile
$personality = $this->personality->dominantPersonalityComponents($profile);
$preference = $this->personality->dominantPersonalityComponents($profile, true);
$profile['personality'] = "";
$profile['preference'] = "";
// For each dominant personality, add the key to the personality in the profile
foreach($personality as $key => $value) {
$profile['personality'] .= $key;
}
// For each dominant preference, add the key to the preference in the profile
foreach($preference as $key => $value) {
$profile['preference'] .= $key;
}
// If the current user is logged in and watching someone else's profile,
// add the likestatus with that person to the profile.
$userLoggedIn = $this->authentication->currentUserId();
if($userLoggedIn != null && $userLoggedIn != $userId) {
$profile['likestatus'] = $this->getLikeStatus($userId);
}
return $profile;
}
}<file_sep><!DOCTYPE html>
<html>
<head>
<title>LuciferMaker</title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url() . '/css/secondStyle.css'; ?>" />
<script type="text/javascript" src="<?php echo base_url() . '/js/jquery.js'; ?>"> </script>
</head>
<body>
<div id='container'>
<header>
<h1>
LuciferMaker, matchmaking since 2012
</h1>
</header><file_sep><div id="loginbox">
<?php
$home = base_url() . 'index.php';
// Get CodeIgniter object.
$ci =& get_instance();
// Check which user is logged in.
$uname = $ci->authentication->currentUserName();
if($uname !== null)
{
// User is logged in, show a welcome message with logout option.
echo '<p><strong>Welcome, ' . form_prep($uname) . '!</strong>'
. ' (<a href="' . "$home/home/logout" . '">logout</a>)';
// Show option for deleting the account.
echo '<p><strong id="deleter">Delete account</strong></p>';
}
else
{
// If nobody is logged in, show login form.
echo '<h3>Login or <a href="' . "$home/register" . '">Register</a> </h3>';
echo form_open('home/login')
. form_label('E-mail:      ', 'email')
. form_input('email')
. '<br/>'
. form_label('Password: ', '<PASSWORD>')
. form_password('<PASSWORD>')
. form_submit('submit', 'Login')
. form_close();
}
?>
</div>
<script type="text/javascript">
// Add mouse listener to delete link.
$('#deleter').click(function()
{
var ok = confirm('You are about to delete your account. Are you absolutely sure?');
if(ok)
{
// Send delete request.
$.post('<?php echo "$home/home/delete"; ?>',
{sure: 'yes'},
function()
{
// Refresh page when done.
window.location.reload();
});
}
});
</script><file_sep><!DOCTYPE html>
<html>
<head>
<title>Risa - <?php
if(isset($pagename))
{
echo $pagename;
}
?>
</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url() . '/css/style.css'; ?>" />
<script type="text/javascript" src="<?php echo base_url() . '/js/jquery.js'; ?>"> </script>
</head>
<body>
<div id='container'>
<header>
<h1>
Risa, matchmaking since 2012
</h1>
</header><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class AdminPanel extends CI_Controller
{
// A simple validator that checks whether the input has the right format.
// Returns null if it validates, or a string containing an error if it doesn't.
// This function also removes excess keys from the input array.
private function _validateInput(&$input)
{
$s = $input['similarityMeasure'];
$x = $input['xFactor'];
$a = $input['alpha'];
if($s === null || $s < 0 || $s > 3)
{
return 'Invalid similarity measure.';
}
if($x === null || $x < 0 || $x > 1)
{
return 'Invalid X-factor.';
}
if($a === null || $a < 0 || $a > 1)
{
return 'Invalid alpha factor.';
}
// Rebuild array to remove unnessecary input.
$input = array('similarityMeasure' => $s,
'xFactor' => $x,
'alpha' => $a);
// Validation passed.
return null;
}
public function index()
{
// Only admins should have access to this page.
$this->authentication->assertAdministrator();
// Load configuration model.
$this->load->model('Configuration', 'conf');
// Load form helper.
$this->load->helper('form');
$error = null;
// Check whether configurations have been changed.
$input = $this->input->post();
if($input !== false)
{
// Validate input.
$error = $this->_validateInput($input);
if($error === null)
{
// Update configuration.
$this->conf->save($input);
}
}
// Load current configuration.
$data = $this->conf->load();
// Add error.
$data['error'] = $error;
// Header.
$this->load->view('header', array('pagename' => 'Configuration'));
$this->load->view('nav');
$this->load->view('loginbox');
// Show admin panel view with data.
$this->load->view('adminpanel', $data);
// Footer.
$this->load->view('footer');
}
}
<file_sep>BEGIN TRANSACTION;
PRAGMA encoding = "UTF-8";
PRAGMA foreign_keys = 1;
CREATE TABLE "Users"
(
"userId" integer NOT NULL,
"username" varchar(30) NOT NULL,
"email" varchar(256) NOT NULL,
"passwordHash" char(40) NOT NULL, -- For SHA-1 hashes.
"firstName" varchar(30) NOT NULL,
"lastName" varchar(50) NOT NULL,
"gender" bool NOT NULL, -- 0: male, 1: female
"birthdate" date NOT NULL,
"description" varchar(300) NOT NULL,
"minAgePref" integer NOT NULL,
"maxAgePref" integer NOT NULL,
"genderPref" bool, -- NULL in case of bisexuality
-- Personality values, each is an integer between 0 and 100; E,S,F and P can be derived
"personalityI" integer NOT NULL,
"personalityN" integer NOT NULL,
"personalityT" integer NOT NULL,
"personalityJ" integer NOT NULL,
-- Personality preferences
"preferenceI" integer NOT NULL,
"preferenceN" integer NOT NULL,
"preferenceT" integer NOT NULL,
"preferenceJ" integer NOT NULL,
-- Contains the filename of an uploaded picture
"picture" varchar(20),
"admin" bool NOT NULL DEFAULT '0',
PRIMARY KEY("userId"),
UNIQUE("username"),
UNIQUE("email")
);
CREATE TABLE "Brands"
(
"brandName" varchar(30) NOT NULL,
PRIMARY KEY ("brandName")
);
CREATE TABLE "UserBrands"
(
"userId" integer NOT NULL,
"brandName" varchar(30) NOT NULL,
FOREIGN KEY ("userId")
REFERENCES "Users"
ON DELETE CASCADE,
FOREIGN KEY ("brandName")
REFERENCES "Brands"
ON DELETE CASCADE,
UNIQUE ("userId", "brandName")
);
CREATE TABLE "Likes"
(
"userLiking" integer NOT NULL,
"userLiked" integer NOT NULL,
UNIQUE("userLiking", "userLiked"),
FOREIGN KEY ("userLiking")
REFERENCES "Users"
ON DELETE CASCADE,
FOREIGN KEY ("userLiked")
REFERENCES "Users"
ON DELETE CASCADE
);
-- Table should have exactly one row.
CREATE TABLE "Configuration"
(
"similarityMeasure" integer NOT NULL, -- 0: Dice's, 1: Jaccard's, 2: cosine, 3: overlap
"xFactor" float NOT NULL,
"alpha" float NOT NULL
);
-- Default configuration.
INSERT INTO "Configuration" ("similarityMeasure", "xFactor", "alpha")
VALUES (0, 0.5, 0.5);
-- Session table. Automaticallt managed by CodeIgniter's session class.
CREATE TABLE "Sessions"
(
"session_id" varchar(40) DEFAULT '0' NOT NULL,
"ip_address" varchar(16) DEFAULT '0' NOT NULL,
"user_agent" varchar(120) NOT NULL,
"last_activity" unsigned integer(10) DEFAULT 0 NOT NULL,
"user_data" text NOT NULL,
PRIMARY KEY (session_id)
);
CREATE INDEX "last_activity_idx"
ON "Sessions" ("last_activity");
-- Admin user.
INSERT INTO "Users"
VALUES (
1,
'admin',
'<EMAIL>',
'105c075b400c0ac2ebacaf91da608e3f947a22e0',
'Admin',
'The Admin',
0,
'1991-02-06',
'I am the almighty administrator of this website! Bow and tremble before my mighty administrative capabilities!',
18,
25,
1,
50, 50, 50, 50, 50, 50, 50, 50,
NULL,
1
);
-- Brands.
-- Top 50 most popular brands on Twitter on March 7 2011.
-- Source: http://tweetedbrands.com/
INSERT INTO "Brands" ("brandName") VALUES ('Twitter');
INSERT INTO "Brands" ("brandName") VALUES ('Youtube');
INSERT INTO "Brands" ("brandName") VALUES ('Facebook');
INSERT INTO "Brands" ("brandName") VALUES ('iPhone');
INSERT INTO "Brands" ("brandName") VALUES ('Google');
INSERT INTO "Brands" ("brandName") VALUES ('Apple');
INSERT INTO "Brands" ("brandName") VALUES ('Android');
INSERT INTO "Brands" ("brandName") VALUES ('Blackberry');
INSERT INTO "Brands" ("brandName") VALUES ('Myspace');
INSERT INTO "Brands" ("brandName") VALUES ('Amazon');
INSERT INTO "Brands" ("brandName") VALUES ('BBC');
INSERT INTO "Brands" ("brandName") VALUES ('Nokia');
INSERT INTO "Brands" ("brandName") VALUES ('MTV');
INSERT INTO "Brands" ("brandName") VALUES ('CNN');
INSERT INTO "Brands" ("brandName") VALUES ('Microsoft');
INSERT INTO "Brands" ("brandName") VALUES ('Starbucks');
INSERT INTO "Brands" ("brandName") VALUES ('Yahoo!');
INSERT INTO "Brands" ("brandName") VALUES ('eBay');
INSERT INTO "Brands" ("brandName") VALUES ('Nike');
INSERT INTO "Brands" ("brandName") VALUES ('Disney');
INSERT INTO "Brands" ("brandName") VALUES ('Sony');
INSERT INTO "Brands" ("brandName") VALUES ('Mashable');
INSERT INTO "Brands" ("brandName") VALUES ('Samsung');
INSERT INTO "Brands" ("brandName") VALUES ('BP');
INSERT INTO "Brands" ("brandName") VALUES ('Ford');
INSERT INTO "Brands" ("brandName") VALUES ('Canon');
INSERT INTO "Brands" ("brandName") VALUES ('Motorola');
INSERT INTO "Brands" ("brandName") VALUES ('Guardian');
INSERT INTO "Brands" ("brandName") VALUES ('KFC');
INSERT INTO "Brands" ("brandName") VALUES ('Toyota');
INSERT INTO "Brands" ("brandName") VALUES ('Techcrunch');
INSERT INTO "Brands" ("brandName") VALUES ('Coca-Cola');
INSERT INTO "Brands" ("brandName") VALUES ('Dell');
INSERT INTO "Brands" ("brandName") VALUES ('Gucci');
INSERT INTO "Brands" ("brandName") VALUES ('BMW');
INSERT INTO "Brands" ("brandName") VALUES ('British Airways');
INSERT INTO "Brands" ("brandName") VALUES ('Pepsi');
INSERT INTO "Brands" ("brandName") VALUES ('Intel');
INSERT INTO "Brands" ("brandName") VALUES ('McDonald');
INSERT INTO "Brands" ("brandName") VALUES ('Honda');
INSERT INTO "Brands" ("brandName") VALUES ('Adidas');
INSERT INTO "Brands" ("brandName") VALUES ('IBM');
INSERT INTO "Brands" ("brandName") VALUES ('Panasonic');
INSERT INTO "Brands" ("brandName") VALUES ('T-Mobile');
INSERT INTO "Brands" ("brandName") VALUES ('Spotify');
INSERT INTO "Brands" ("brandName") VALUES ('Lego');
INSERT INTO "Brands" ("brandName") VALUES ('Digg');
INSERT INTO "Brands" ("brandName") VALUES ('Mercedes');
INSERT INTO "Brands" ("brandName") VALUES ('IKEA');
INSERT INTO "Brands" ("brandName") VALUES ('VW');
COMMIT;
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class ProfileBrowser extends CI_Controller
{
function __construct() {
parent::__construct();
}
public function displayProfiles(/* ... */)
{
$userIds = func_get_args();
if(count($userIds) == 1 && is_array($userIds[0]))
{
$userIds = $userIds[0];
}
// There shouldn't be more than six profiles to display.
if(count($userIds) > 6)
{
throw new Exception("Can't display more than six profiles");
}
// Output nothing if there are no id's.
if(count($userIds) == 0)
{
return;
}
// Load the user model.
$this->load->model('User', 'user');
// Load profiles.
$profiles = array();
foreach($userIds as $id)
{
$profiles[] = $this->user->getUserProfile($id);
}
// The profiles are placed in the data array and the profile type is set.
$data['profiles'] = $profiles;
$data['profileType'] = 'small';
// Display profile overviews.
$this->parser->parse('content/profile', $data);
}
/**
* Prints a browser for user profiles.
*
* @param array(int) $ids The id's of the users that should be browsable.
*/
public function userBrowser($ids)
{
$ids = array_values($ids);
// Display the first six results (or less, if there aren't as much).
$toDisplay = array_splice($idscopy = $ids, 0, min(6, count($ids)));
$this->displayProfiles($toDisplay);
// Add the search browser and give it all the found id's.
// We restrict the number of id's send to 600 to prevent generating a gigantic javascript
// file when there are a lot of matches. 600 is more than enough since I doubt many people
// will click 'next' more than a hundred times.
$data = array('ids' => array());
for($i = 0; $i < min(600, count($ids)); ++$i)
{
$data['ids'][] = array('id' => $ids[$i]);
}
$this->parser->parse('searchbrowser', $data);
}
}
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Register extends CI_Controller
{
// After succesfully validating a filled in form, use the POST data to add a new user to the
// database.
private function _registerUser()
{
// Load libraries and models.
$this->load->library('picture');
$this->load->model('user');
// Fetch input.
$input = $this->input->post();
// This will be contain the parsed data as added to the user model.
$data = array();
// Values that can be directly put to the data array (after a rename of their keys).
$rename = array(
'username' => 'username',
'firstName' => 'firstName',
'lastName' => 'lastName',
'email' => 'email',
'gender' => 'gender',
'description' => 'description',
'ageprefmin' => 'minAgePref',
'ageprefmax' => 'maxAgePref',
'birthdate' => 'birthdate'
);
foreach($rename as $key => $newkey)
{
$data[$newkey] = $input[$key];
}
// Get password (will be hashed by User::createUser).
$password = $input['<PASSWORD>'];
// Parse gender preference.
$data['genderPref'] = $input['genderPref'] == 2 ? null : (int) $input['genderPref'];
// Parse brand preferences.
$brands = $input['brandpref'];
// Process uploaded image. 'picture' will be set to null if none are specified.
$data['picture'] = $this->picture->uploadAndProcess();
// Determine personality from questionnaire.
// Also set initial personality preference to the opposite of that.
{
// Parse answers.
$answers = array();
for($q = 1; $q <= 19; ++$q)
{
$answers[$q] = $input["question$q"];
}
// E versus I.
$e = 50;
for($i = 1; $i <= 5; ++$i)
{
if($answers[$i] == 'A')
{
$e += 10;
}
else if($answers[$i] == 'B')
{
$e -= 10;
}
}
$data['personalityI'] = 100 - $e;
$data['preferenceI'] = $e;
// N versus S.
$n = 50;
for($i = 1; $i <= 5; ++$i)
{
if($answers[$i] == 'A')
{
$n += 12.5;
}
else if($answers[$i] == 'B')
{
$n -= 12.5;
}
}
$data['personalityN'] = (int) $n;
$data['preferenceN'] = 100 - (int) $n;
// T versus F.
$t = 50;
for($i = 1; $i <= 5; ++$i)
{
if($answers[$i] == 'A')
{
$t += 12.5;
}
else if($answers[$i] == 'B')
{
$t -= 12.5;
}
}
$data['personalityT'] = (int) $t;
$data['preferenceT'] = 100 - (int) $t;
// J versus P.
$j = 50;
for($i = 1; $i <= 5; ++$i)
{
if($answers[$i] == 'A')
{
$j += 8.3333;
}
else if($answers[$i] == 'B')
{
$j -= 8.3333;
}
}
$data['personalityJ'] = (int) $j;
$data['preferenceJ'] = 100 - (int) $j;
}
// Actually create the user.
$this->user->createUser($data, $password, $brands);
}
public function index()
{
$this->load->model('user','',true);
$this->load->library(array('personality', 'form_validation'));
$this->load->helper('html');
$this->load->helper('form');
$this->load->view('header',array("pagename" => "Register"));
$this->load->view('loginbox');
$this->load->view('nav');
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|min_length[4]|max_length[20]'
//TODO controleer dat de naam uniek is. Zie is_unique[table.field]bij form_validation
),
array(
'field' => 'firstName',
'label' => 'Firstname',
'rules' => 'required'
),
array(
'field' => 'lastName',
'label' => 'Lastname',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|min_length[8]|max_length[20]'
),
array(
'field' => 'passconf',
'label' => 'Repeat password',
'rules' => 'required|matches[password]|min_length[8]|max_length[20]'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|valid_email'
),
array(
'field' => 'gender',
'label' => 'Gender',
'rules' => 'required'
),
array(
'field' => 'birthdate',
'label' => 'Birthdate',
'rules' => 'required|alpha-dash|callback_validateDate'
),
array(
'field' => 'description',
'label' => 'About you',
'rules' => ''
),
array(
'field' => 'genderPref',
'label' => 'Gender preference',
'rules' => 'required'
),
array(
'field' => 'ageprefmin',
'label' => 'Minimum age',
'rules' => 'required|numeric|greater_than[17]|callback_validAgePref[ageprefmax]'
),
array(
'field' => 'ageprefmax',
'label' => 'Maximum age',
'rules' => 'required|numeric|less_than[123]'
),
array(
'field' => 'picture',
'label' => 'Upload picture',
'rules' => ''
)
);
// The list of brands is loaded from the database
$this->load->model('brand');
$brands = $this->brand->getBrands();
foreach($brands as $brand)
{
$config[] = array(
'field' => $brand,
'label' => $brand,
'rules' => '');
}
// For each of the 20 personality question, the rule required is set
for($q = 1; $q <= 19; ++$q)
{
$config[] = array(
'field' => "question$q",
'label' => "Personality question $q",
'rules' => 'required'
);
}
//TODO Hier gaat het fout.
//$config = $this->rules_storage->getRules();
// And all the rules are added to the form_validation
$this->form_validation->set_rules($config);
// All errors are placed in a div with the error class
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
// Check if there is a post result. If there is, the brandpref list is handed
// to the brandCheckBoxes function for re-populating.
if(array_key_exists('brandpref',$_POST)) {
$brandpref = $_POST['brandpref'];
}
else {
// If there is a profile, its brandspreferences are used as the re-populate list.
$brandpref = null;
}
$data = array('brands' => $brands,
'brandPreferences' => $brandpref);
// Display the form while it is invalid.
if ($this->form_validation->run() === false)
{
$this->load->view('content/registerView', $data);
}
else
{
// The form input is validated, the user is registeredand the succesmessage is displayed.
$this->_registerUser();
$this->load->view('content/register_succes', $_POST);
}
$this->load->view('footer');
}
/**
*
* Our own date-validation rule.
* @param string $date The date that will be checked
* @return boolean False if failed
*/
public function validateDate($date)
{
$dummy = array();
$validDate = !!preg_match_all('/[0-9]{4}-[0-9]{2}-[0-9]{2}/', $date, $dummy);
$year; $month; $day;
sscanf($date, '%D-%D-%D', $year, $month, $day);
$thisYear = date('o');
$validDate &= $year > $thisYear - 122 && $year <= $thisYear - 18
&& $month >= 1 && $month <= 12
&& $day >= 1 && $day <= 31;
if(!$validDate) {
if(is_numeric($year) && $year < $thisYear - 122)
$this->form_validation->set_message('validateDate',
'If you are older than 122, please contact the Guiness Book of World Records.');
else
$this->form_validation->set_message('validateDate',
'Invalid date');
return false;
}
else {
return true;
}
}
/**
*
* Checks if ageprefmin is smaller or equal to ageprefmax.
* @param int $ageprefmin The minimum age preference
* @param string $ageprefmax The name for the maximum age preference in the post
* @return boolean false if fails
*/
public function validAgePref($ageprefmin, $ageprefmax)
{
if($ageprefmin > $this->input->post($ageprefmax)) {
$this->form_validation->set_message('validAgePref',
'The %s field can not be greater than the Maximum age');
return false;
}
else {
return true;
}
}
}
<file_sep><?php
function boldShow($type, $content, $textblock = false)
{
global $profileType;
if($profileType == "form") {
if($textblock) {
$content = form_textarea($type, $content, "rows=\"6\" cols=\"80\"");
}
else {
$content = form_input($type, $content);
}
}
return "<p><b>". htmlentities($type, ENT_QUOTES, "UTF-8"). ":</b> ".
htmlentities($content, ENT_QUOTES, "UTF-8"). "</p>";
}
foreach($user as $key => $val) {
echo boldShow($key, $val). br(1);
}
?><file_sep><?php
class ViewProfile extends CI_Controller
{
public function index($msg = null)
{
if($this->authentication->userLoggedIn()) {
$this->showProfile($this->authentication->currentUserId(), 'form');
}
else {
$this->load->view('header',array("pagename" => "Profile"));
$this->load->view('loginbox');
$this->load->view('nav');
$this->load->view('error',array('error' => "You need to be logged in to edit your profile."));
$this->load->view('footer');
}
}
public function showProfile($userId, $profileType = 'big')
{
$this->load->model('user','',true);
$this->load->view('header',array("pagename" => "Profile"));
$this->load->view('loginbox');
$this->load->view('nav');
$data = array( 'profileType' => $profileType,
'profiles' => array($this->user->getUserProfile($userId)));
$this->load->view('content/profile',$data);
$this->load->view('footer');
}
public function like()
{
$otherUser = $this->input->post('otherId');
if($otherUser !== false)
{
$this->load->model('User', 'user');
$this->user->like($otherUser);
}
}
}
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Model for queries on brands.
*/
class Brand extends CI_Model
{
public function __construct()
{
parent::__construct();
}
/**
* Returns the names of all available brands.
*
* @return array(string)
*/
public function getBrands()
{
$result = $this->db->select('brandName')->from('Brands')->get()->result();
// Only return brand names.
foreach($result as &$brand)
{
$brand = $brand->brandName;
}
return $result;
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class SearchModel extends CI_Model
{
public function search($input)
{
// Query expression to determine the age of a user.
$age = "(strftime('%Y', 'now') - strftime('%Y', birthdate)
- (strftime('%j', 'now') < strftime('%j', birthdate)))";
// Build query.
$query = $this->db->select('u.userId')->from('Users u');
// Restrict users in result by wanted gender.
if($input['genderPref'] != 'either')
{
$query->where('gender', $input['genderPref'] == 'female');
}
// Restrict on age.
$query->where('minAgePref <=', (int) $input['ownAge']);
$query->where('maxAgePref >=', (int) $input['ownAge']);
$query->where("$age <=", (int) $input['maxAge']);
$query->where("$age >=", (int) $input['minAge']);
// 0: male, 1: female.
$gpref_bool = $input['ownGender'] == 'female' ? '1' : '0';
// Add gender preference to query.
$query->where("(genderPref IS NULL OR genderPref = $gpref_bool)");
// Parse brand preference list.
$brands = array_filter(array_map('trim', explode(',', $input['brands'])));
// If at least one brand is specified, add them to the query.
if(count($brands) > 0)
{
$query->join('UserBrands b', 'b.userId = u.userId', 'left')
->where_in('brandName', $brands);
}
// Retrieve personality preference.
$personPref = array($input['attitude'],
$input['perceiving'],
$input['judging'],
$input['lifestyle']
);
$dicts1 = 'INTJ';
$dicts2 = 'ESFP';
for($i = 0; $i < 4; ++$i)
{
$col = 'preference' . $dicts1[$i];
if($personPref[$i] == $dicts1[$i])
{
$query->where("$col >= 0.5");
}
else
{
$query->where("$col < 0.5");
}
}
// Execute query.
$result = $query->get()->result_array();
// Return userId's.
foreach($result as &$row)
{
$row = $row['userId'];
}
return array_merge($result);
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Authentication
{
/**
* @return bool Whether somebody is logged in.
*/
public function userLoggedIn()
{
return $this->currentUserId() !== null;
}
/**
* @return int The ID of the user that is currently logged in, or null of none is.
*/
public function currentUserId()
{
// Get CodeIgniter object.
$ci =& get_instance();
// Fetch id from session data.
// If the session ID in the user's cookie does not match a session in the database,
// CodeIgniter will have destroyed the session already and this will return false.
$id = $ci->session->userdata('userId');
if($id !== false)
{
return $id;
}
else
{
return null;
}
}
public function currentUserName()
{
$ci =& get_instance();
$ci->load->model('User','user');
$id = $this->currentUserId();
if($id === null)
{
return null;
}
else
{
$result = $ci->user->load($id);
return $result['username'];
}
}
public function userIsAdmin()
{
// Fetch current user.
$id = $this->currentUserId();
if($id !== null)
{
// Get CodeIgniter object.
$ci =& get_instance();
// Confirm whether admin with database.
$result = $ci->db->select('admin')->from('Users')
->where('userId', $id)->get()->row();
if($result->admin)
{
// If an admin, return true.
return true;
}
}
// No admin.
return false;
}
/**
* Throws an exception if the currently logged in user, if any, is not an administrator.
*
* This should be used to protect admin only functionality at the server side against forged
* requests. This function shouldn't be used in areas reachable by regular users.
*
* @throws Exception If no administrator is logged in.
*/
public function assertAdministrator()
{
if(!$this->userIsAdmin())
{
throw new Exception('Access denied.');
}
}
/**
* Logs in a user.
*
* @param email The e-mail adres the user has entered.
* @param password The <PASSWORD> the user has entered.
*
* @return int The user ID of the user that has been succesfully logged in, if any.
* If no user with the provided e-mail/password combination exists. This will
* return null.
*/
public function login($email, $password)
{
// Get CodeIgniter object.
$ci =& get_instance();
if($this->userLoggedIn())
{
// You can't log in twice.
return null;
}
// Load user model.
$ci->load->model('user');
// Look up which user belongs to this e-mail address and password.
$id = $ci->user->lookup($email, $password);
if($id === null)
{
// Login failed. Return null.
return null;
}
else
{
// Add the user's ID to the session data.
$ci->session->set_userdata('userId', $id);
// Return the username.
return $id;
}
}
/**
* Logs out the current user.
*/
public function logout()
{
// Simply destroy the current session.
$ci =& get_instance();
$ci->session->set_userdata('userId', null);
$ci->session->sess_destroy();
}
}
| 31868d8e70309e4b98d5cc1d8d0adf31d7e2ad2b | [
"SQL",
"Text",
"PHP"
] | 33 | PHP | TomTervoort/webtech3 | dc2b630ff9e977a60567f31f8da0f177aa9ae7dd | 6f1a35fff28c88a71a86a51fd2ecf79890779800 | |
refs/heads/master | <repo_name>KarolSz001/IODeliverSystemApp<file_sep>/README.md
"# IODeliverSystemApp"
<file_sep>/repo/src/main/java/com/app/repo/impl/PaymentRepositoryImpl.java
package com.app.repo.impl;
import com.app.model.Payment;
import com.app.repo.generic.AbstractCrudRepository;
import com.app.repo.generic.PaymentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class PaymentRepositoryImpl extends AbstractCrudRepository<Payment,Long> implements PaymentRepository {
@Autowired
public PaymentRepositoryImpl() {
super();
}
}
<file_sep>/repo/src/main/java/com/app/repo/impl/TradeRepositoryImpl.java
package com.app.repo.impl;
import com.app.model.Trade;
import com.app.repo.generic.AbstractCrudRepository;
import com.app.repo.generic.TradeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import java.util.Optional;
@Component
public class TradeRepositoryImpl extends AbstractCrudRepository<Trade, Long> implements TradeRepository {
@Autowired
public TradeRepositoryImpl() {
super();
}
@Override
public Optional<Trade> findByName(String name) {
EntityManager em = null;
EntityTransaction tx = null;
Optional<Trade> tradeByName = Optional.empty();
try {
em = emf.createEntityManager();
tx = em.getTransaction();
tx.begin();
tradeByName = em
.createQuery("select t from Trade t where t.name = :name", Trade.class)
.setParameter("name", name)
.getResultStream().findFirst();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
return tradeByName;
}
}
<file_sep>/repo/src/main/java/com/app/repo/impl/ErrorRepositoryImpl.java
package com.app.repo.impl;
import com.app.repo.generic.AbstractCrudRepository;
import com.app.repo.generic.ErrorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ErrorRepositoryImpl extends AbstractCrudRepository<Error, Long> implements ErrorRepository {
@Autowired
public ErrorRepositoryImpl() {
super();
}
}
| 165e3d523791deee8f3730a9ee9e4b61a9ace279 | [
"Markdown",
"Java"
] | 4 | Markdown | KarolSz001/IODeliverSystemApp | 2cb85ecb230c4588674e804b9c555dec77b5bd2c | 0c087b1d0de028fe3f9c09a3570849136051922a | |
refs/heads/master | <file_sep>import boto3
import json
dynamo = boto3.client('dynamodb')
def lambda_handler(event, context):
operation = event['httpMethod']
if operation == 'GET': #Only need Primary Key Value and Table Name
response = dynamo.get_item(Key=event['body'],TableName=event['TblName'])
resdict = {
"PhoneNumber":response['Item']['phonenumber']['S'],
"Name":response['Item']['uname']['S'],
"Email":response['Item']['mailid']['S'],
"Address":response['Item']['pass']['S']
}
return (resdict)
elif operation == 'DELETE': #Only need Primary Key Value and Table Name
dynamo.delete_item(Key=event['body'],TableName=event['TblName'])
return ("Delete Successful")
elif operation == 'POST': #Needs Items to be inserted and Table Name
dynamo.put_item(Item=event['body2'],TableName=event['TblName'])
return ("Insert Successful")
elif operation == 'PUT': #Needs Key, UpdateExpression, ExpressionAttributeValues and Table Name
dynamo.update_item(Key=event['body'],TableName=event['TblName'],
UpdateExpression=event['UE'],ExpressionAttributeValues=event['EAV'])
return ("Update Successful")
else:
print("Possible Operations are GET, POST, PUT & DELETE only\n")
# Documentation : https://boto3.amazonaws.com/v1/documentation/api/1.9.42/reference/services/dynamodb.html?highlight=dynamodb.#client | 039a5dc6316b0bc27f29651ddb62116d32de60ec | [
"Python"
] | 1 | Python | Reetam-Nandi/AWS-DynamoDB | 578e9c5fb5b2dce767961615962efad9ccd73939 | efab367c945689d7aa324a15cebe2e52184c16a3 | |
refs/heads/master | <repo_name>mosen/autopkg-recipes<file_sep>/JetBrains/JetbrainsURLProvider.py
#!/usr/bin/env python
#
# Copyright 2014
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import urllib
import urllib2
from autopkglib import Processor, ProcessorError
__all__ = ["JetbrainsURLProvider"]
# Jetbrains IDEA first checks with www.jetbrains.com/updates/updates.xml
# It also sends a request to /updates/updates.xml?uid={UUID}&os=Mac+OS+X+10.8.5&build=IU-133.193
# which returns a slightly different version of updates.xml (Please elaborate/different update message or xml structure)
# It also sends a plugin update request to plugins.jetbrains.com/plugins/list/?build=IU-133.193&crc32={CRC}
# It fetches plugins first through GET /pluginManager/?action=download&id=com.jetbrains.php&build=IU-133.193&uuid={uuid}
# and downloads each plugin individually.
# Somewhere along the line it fetches GET /idea/IU-133.193-133.331-patch-mac.jar (Filename determined by reading updates.xml
# and subbing the current value, value from updates.xml, and platform)
# Conclusion: because AutoPkg isn't designed to import IntelliJ's jar patcher, just download the retail package.
# Actually sends to http://www.jetbrains.com/idea/download
# Download button POSTs form#sendEmail with 2 POST vars os, edition
# edition is IU/IC
# os is win/mac/linux
PRODUCTS = ("IntelliJ IDEA", "RubyMine", "PyCharm", "PhpStorm", "WebStorm", "AppCode")
# Product download landing page
PRODUCT_URLS = {
"IntelliJ IDEA": "http://www.jetbrains.com/idea/download/index.html",
"RubyMine": "http://www.jetbrains.com/ruby/download/index.html",
"PyCharm": "http://www.jetbrains.com/pycharm/download/index.html",
"PhpStorm": "http://www.jetbrains.com/phpstorm/download/index.html",
"WebStorm": "http://www.jetbrains.com/webstorm/download/index.html",
"AppCode": "http://www.jetbrains.com/objc/" # Odd one out, has no platform selector
}
# POST to this page to get download
THANKYOU_URLS = {
"IntelliJ IDEA": "http://www.jetbrains.com/idea/download/download_thanks.jsp",
"RubyMine": "http://www.jetbrains.com/ruby/download/download_thanks.jsp",
"PyCharm": "http://www.jetbrains.com/pycharm/download/download_thanks.jsp",
"PhpStorm": "http://www.jetbrains.com/phpstorm/download/download_thanks.jsp",
"WebStorm": "http://www.jetbrains.com/webstorm/download/download_thanks.jsp"
}
DEFAULT_PRODUCT = "IntelliJ IDEA"
DEFAULT_CODE = "IU" # Only used for IDEA IU=Ultimate, IC=Community
DEFAULT_PLATFORM = "mac"
class JetbrainsURLProvider(Processor):
description = "Provides URL to the latest JetBrains IDE release"
input_variables = {
"product": {
"required": True,
"description": "Jetbrains IDE product name, is one of: 'IntelliJ IDEA', 'RubyMine', 'PyCharm', 'PhpStorm', 'WebStorm', 'AppCode'."
},
"product_code": {
"required": False,
"description": "[optional] For IntelliJ IDEA, The product edition: ultimate or community, which is one of: 'IU', 'IC'. For PyCharm 'prof' or 'comm'"
},
"platform": {
"required": False,
"description": "[optional] The operating system platform, one of 'mac', 'pc', 'linux'"
}
}
output_variables = {
"url": {
"description": "URL to the latest JetBrains IDE release",
}
}
__doc__ = description
def get_jetbrains_url(self, download_post_url, product, product_code):
params = {
"os": "mac"
}
if (product == "IntelliJ IDEA" or product == "PyCharm"):
params['edition'] = product_code
request = urllib2.Request(download_post_url, urllib.urlencode(params))
try:
url_handle = urllib2.urlopen(request)
html_response = url_handle.read()
url_handle.close()
except BaseException as e:
raise ProcessorError("Can't get download page for JetBrains Product: %s" % product)
search_download_link = re.compile('href\s*=\s*[\'"]+(.*\.[dD][mM][gG])[\'"]+', re.MULTILINE).search(
html_response)
if (search_download_link):
download_link = search_download_link.group(1)
else:
raise ProcessorError("Couldn't find download link for JetBrains Product: %s" % product)
return download_link
def main(self):
# Take input params
product = self.env.get("product", DEFAULT_PRODUCT) # TODO: validate against PRODUCTS
product_code = self.env.get("product_code", DEFAULT_CODE)
platform = self.env.get("platform", DEFAULT_PLATFORM)
self.env["url"] = self.get_jetbrains_url(
THANKYOU_URLS[product], product, product_code)
self.output("Found URL %s" % self.env["url"])
if __name__ == "__main__":
processor = JetbrainsURLProvider()
processor.execute_shell()
| 2df49b02f3583267b8d3aadccadaee887d4b66e4 | [
"Python"
] | 1 | Python | mosen/autopkg-recipes | 3eafae3473b44420ba15a1b444310a544eb34054 | 3c3ba0fa983794c33e83e52667484f21d7d51945 | |
refs/heads/master | <repo_name>Carnivoroys/TARA-Server<file_sep>/src/test/java/ee/ria/sso/config/ThymeleafSupportTest.java
package ee.ria.sso.config;
import ee.ria.sso.Constants;
import ee.ria.sso.authentication.AuthenticationType;
import ee.ria.sso.flow.ThymeleafSupport;
import ee.ria.sso.service.manager.ManagerService;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.model.core.CasServerProperties;
import org.apereo.cas.services.OidcRegisteredService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.webflow.core.collection.SharedAttributeMap;
import org.springframework.webflow.execution.RequestContextHolder;
import org.springframework.webflow.test.MockExternalContext;
import org.springframework.webflow.test.MockRequestContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
@RunWith(MockitoJUnitRunner.class)
public class ThymeleafSupportTest {
@Mock
ManagerService managerService;
@Mock
CasConfigurationProperties casProperties;
@Mock
TaraProperties taraProperties;
private ThymeleafSupport thymeleafSupport;
@Before
public void setUp() {
thymeleafSupport = new ThymeleafSupport(managerService, casProperties, taraProperties, "paramName");
}
@Test
public void isAuthMethodAllowedShouldReturnTrueWhenMethodsEnabledAndAllowedInSession() {
Arrays.stream(AuthenticationType.values())
.forEach(method -> {
Mockito.when(taraProperties.isPropertyEnabled(Mockito.eq(method.getPropertyName()+ ".enabled"))).thenReturn(true);
setRequestContextWithSessionMap(Collections.singletonMap(
Constants.TARA_OIDC_SESSION_AUTH_METHODS, Collections.singletonList(method)
));
Assert.assertTrue(this.thymeleafSupport.isAuthMethodAllowed(method));
});
}
@Test
public void isAuthMethodAllowedShouldReturnFalseWhenMethodsEnabledButNotAllowedInSession() {
setRequestContextWithSessionMap(Collections.singletonMap(
Constants.TARA_OIDC_SESSION_AUTH_METHODS, Collections.emptyList()
));
Arrays.stream(AuthenticationType.values())
.forEach(method -> Assert.assertFalse(this.thymeleafSupport.isAuthMethodAllowed(method)));
}
@Test
public void isAuthMethodAllowedWhenNoAttrSetInSession() {
Arrays.stream(AuthenticationType.values())
.forEach(method -> {
Mockito.when(taraProperties.isPropertyEnabled(Mockito.eq(method.getPropertyName()+ ".enabled"))).thenReturn(true);
setRequestContextWithSessionMap(new HashMap<>());
Assert.assertTrue("Method " + method + " should be allowed", this.thymeleafSupport.isAuthMethodAllowed(method));
});
}
@Test
public void isAuthMethodAllowedShouldReturnFalseWhenMethodsDisabledButAllowedInSession() {
final ThymeleafSupport thymeleafSupport = new ThymeleafSupport(null,
casProperties, taraProperties, null);
Arrays.stream(AuthenticationType.values())
.forEach(method -> {
Mockito.when(taraProperties.isPropertyEnabled(Mockito.eq(method.getPropertyName()+ ".enabled"))).thenReturn(false);
setRequestContextWithSessionMap(Collections.singletonMap(
Constants.TARA_OIDC_SESSION_AUTH_METHODS, Collections.singletonList(method)
));
Assert.assertFalse("Method " + method + " should not be allowed", thymeleafSupport.isAuthMethodAllowed(method));
});
}
@Test
public void isAuthMethodAllowedShouldReturnFalseWhenMethodsDisabledAndNotAllowedInSession() {
final ThymeleafSupport thymeleafSupport = new ThymeleafSupport(null,
casProperties, taraProperties, null);
setRequestContextWithSessionMap(Collections.singletonMap(
Constants.TARA_OIDC_SESSION_AUTH_METHODS, Collections.emptyList()
));
Arrays.stream(AuthenticationType.values())
.forEach(method -> Assert.assertFalse("Method " + method + " should be allowed", thymeleafSupport.isAuthMethodAllowed(method)));
}
@Test
public void getHomeUrlShouldReturnEmptyUrlWhenRedirectUriNotPresentInSession() {
setRequestContextWithSessionMap(null);
Assert.assertEquals("#", this.thymeleafSupport.getHomeUrl());
}
@Test
public void getHomeUrlShouldReturnValidHomeUrlWhenValidRedirectUriPresentInSession() {
OidcRegisteredService oidcRegisteredService = Mockito.mock(OidcRegisteredService.class);
Mockito.when(oidcRegisteredService.getInformationUrl()).thenReturn("https://client/url");
ManagerService managerService = Mockito.mock(ManagerService.class);
Mockito.when(managerService.getServiceByID("https://client/url"))
.thenReturn(Optional.of(oidcRegisteredService));
ThymeleafSupport thymeleafSupport = new ThymeleafSupport(managerService, null, null, null);
setRequestContextWithSessionMap(
Collections.singletonMap(Constants.TARA_OIDC_SESSION_REDIRECT_URI, "https://client/url")
);
Assert.assertEquals("https://client/url", thymeleafSupport.getHomeUrl());
}
@Test
public void getHomeUrlShouldReturnEmptyUrlWhenInvalidRedirectUriPresentInSession() {
ManagerService managerService = Mockito.mock(ManagerService.class);
Mockito.when(managerService.getServiceByID("https://client/url"))
.thenReturn(Optional.empty());
ThymeleafSupport thymeleafSupport = new ThymeleafSupport(managerService, casProperties, null, null);
setRequestContextWithSessionMap(Collections.singletonMap(Constants.TARA_OIDC_SESSION_REDIRECT_URI, "https://client/url"));
Assert.assertEquals("#", thymeleafSupport.getHomeUrl());
}
@Test
public void getLocaleUrlShouldReturn() throws Exception {
setRequestContextWithSessionMap(new HashMap<>());
CasServerProperties casServerProperties = new CasServerProperties();
casServerProperties.setName("https://example.tara.url");
Mockito.when(casProperties.getServer()).thenReturn(casServerProperties);
ThymeleafSupport thymeleafSupport = new ThymeleafSupport(null, casProperties, null, "somelocaleparam");
Assert.assertEquals("https://example.tara.url:443?somelocaleparam=et", thymeleafSupport.getLocaleUrl("et"));
}
@Test
public void getBackUrlShouldReturnPac4jRequestedUrlWithSpecifiedLocale() throws Exception {
setRequestContextWithSessionMap(new HashMap<>());
ThymeleafSupport thymeleafSupport = new ThymeleafSupport(null, casProperties, null, "somelocaleparam");
Assert.assertEquals("https://example.tara.ee?somelocaleparam=et", thymeleafSupport.getBackUrl("https://example.tara.ee", Locale.forLanguageTag("et")));
}
@Test
public void getBackUrlShouldReturnHashTagWhenEmpty() throws Exception {
setRequestContextWithSessionMap(new HashMap<>());
ThymeleafSupport thymeleafSupport = new ThymeleafSupport(null, casProperties, null, "somelocaleparam");
Assert.assertEquals("#", thymeleafSupport.getBackUrl("", Locale.forLanguageTag("et")));
Assert.assertEquals("#", thymeleafSupport.getBackUrl(" ", Locale.forLanguageTag("et")));
Assert.assertEquals("#", thymeleafSupport.getBackUrl(null, Locale.forLanguageTag("et")));
}
@Test
public void isNotLocaleShouldReturnTrue() {
ThymeleafSupport thymeleafSupport = new ThymeleafSupport(null, null, null, null);
Assert.assertTrue(thymeleafSupport.isNotLocale("en", Locale.forLanguageTag("et")));
Assert.assertTrue(thymeleafSupport.isNotLocale("xxx", Locale.forLanguageTag("et")));
}
@Test
public void isNotLocaleShouldReturnFalse() {
ThymeleafSupport thymeleafSupport = new ThymeleafSupport(null, null, null, null);
Assert.assertFalse(thymeleafSupport.isNotLocale("ET", Locale.forLanguageTag("et")));
Assert.assertFalse(thymeleafSupport.isNotLocale("et", Locale.forLanguageTag("et")));
}
@Test
public void getTestEnvironmentAlertMessageIfAvailableShouldReturnProperyValue() {
String testMessage = "test123";
Mockito.when(taraProperties.getTestEnvironmentWarningMessage()).thenReturn(testMessage);
ThymeleafSupport thymeleafSupport = new ThymeleafSupport(null, null, taraProperties, null);
Assert.assertEquals(testMessage, thymeleafSupport.getTestEnvironmentAlertMessageIfAvailable());
}
@Test
public void getTestEnvironmentAlertMessageIfAvailableShouldReturnNull() {
Mockito.when(taraProperties.getTestEnvironmentWarningMessage()).thenReturn(null);
ThymeleafSupport thymeleafSupport = new ThymeleafSupport(null, null, taraProperties, null);
Assert.assertEquals(null, thymeleafSupport.getTestEnvironmentAlertMessageIfAvailable());
}
@Test
public void getCurrentRequestIdentifierShouldReturnIdFromRequestAttributes() {
String uniqueRequestId = UUID.randomUUID().toString();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setAttribute(Constants.MDC_ATTRIBUTE_REQUEST_ID, uniqueRequestId);
ThymeleafSupport thymeleafSupport = new ThymeleafSupport(null, null, taraProperties, null);
Assert.assertEquals(uniqueRequestId, thymeleafSupport.getCurrentRequestIdentifier(request));
}
private static void setRequestContextWithSessionMap(final Map<String, Object> sessionMap) {
mockSpringServletRequestAttributes();
final MockRequestContext requestContext = new MockRequestContext();
final MockExternalContext externalContext = new MockExternalContext();
final SharedAttributeMap<Object> map = externalContext.getSessionMap();
if (sessionMap != null) sessionMap.forEach(
(k, v) -> map.put(k, v)
);
externalContext.setNativeRequest(new MockHttpServletRequest());
requestContext.setExternalContext(externalContext);
RequestContextHolder.setRequestContext(requestContext);
}
private static void mockSpringServletRequestAttributes() {
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
org.springframework.web.context.request.RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request, response));
}
}
<file_sep>/src/test/resources/dynamic.properties
tara.version=x.y.z<file_sep>/src/main/java/ee/ria/sso/config/mobileid/MobileIDConfiguration.java
package ee.ria.sso.config.mobileid;
import ee.ria.sso.service.mobileid.MobileIDAuthenticationClient;
import ee.ria.sso.service.mobileid.MobileIDAuthenticationService;
import ee.ria.sso.service.mobileid.rest.MobileIDRESTAuthClient;
import ee.ria.sso.statistics.StatisticsHandler;
import ee.sk.mid.MidClient;
import ee.sk.mid.rest.MidLoggingFilter;
import lombok.extern.slf4j.Slf4j;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ConditionalOnProperty("mobile-id.enabled")
@Configuration
@Slf4j
public class MobileIDConfiguration {
@Autowired
private StatisticsHandler statisticsHandler;
@Autowired
private MobileIDConfigurationProvider configurationProvider;
@Bean
public MobileIDAuthenticationClient constructAuthenticationClient() {
log.info("Initializing REST protocol based authentication client for Mobile-ID REST service");
return new MobileIDRESTAuthClient(configurationProvider, midClient());
}
@Bean
public MobileIDAuthenticationService mobileIDAuthenticationService() {
return new MobileIDAuthenticationService(
statisticsHandler, configurationProvider, constructAuthenticationClient());
}
private MidClient midClient() {
return MidClient.newBuilder()
.withHostUrl(configurationProvider.getHostUrl())
.withRelyingPartyUUID(configurationProvider.getRelyingPartyUuid())
.withRelyingPartyName(configurationProvider.getRelyingPartyName())
.withNetworkConnectionConfig(clientConfig())
.withLongPollingTimeoutSeconds(configurationProvider.getSessionStatusSocketOpenDuration())
.build();
}
private ClientConfig clientConfig() {
ClientConfig clientConfig = new ClientConfig();
clientConfig.property(ClientProperties.CONNECT_TIMEOUT, configurationProvider.getConnectionTimeout());
clientConfig.property(ClientProperties.READ_TIMEOUT, configurationProvider.getReadTimeout());
clientConfig.register(new MidLoggingFilter());
return clientConfig;
}
}<file_sep>/src/main/java/ee/ria/sso/oidc/OidcAuthorizeRequestValidationServletFilter.java
package ee.ria.sso.oidc;
import ee.ria.sso.Constants;
import ee.ria.sso.authentication.AuthenticationType;
import ee.ria.sso.authentication.LevelOfAssurance;
import ee.ria.sso.config.TaraProperties;
import ee.ria.sso.config.eidas.EidasConfigurationProvider;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.nio.charset.StandardCharsets.UTF_8;
@Slf4j
@AllArgsConstructor
public class OidcAuthorizeRequestValidationServletFilter implements Filter {
private final OidcAuthorizeRequestValidator oidcAuthorizeRequestValidator;
private final EidasConfigurationProvider eidasConfigurationProvider;
private final TaraProperties taraProperties;
@Override
public void init(FilterConfig filterConfig) {
log.debug("Initialize filter: {}", OidcAuthorizeRequestValidationServletFilter.class.getName());
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletResponse response = (HttpServletResponse) servletResponse;
try {
this.oidcAuthorizeRequestValidator.validateAuthenticationRequestParameters(request);
this.saveOidcRequestParametersToSession(request);
filterChain.doFilter(servletRequest, servletResponse);
} catch (OidcAuthorizeRequestValidator.InvalidRequestException e) {
log.error("Invalid OIDC authorization request: " + e.getMessage());
if (isInvalidClient(e)) {
throw new IllegalStateException("Invalid authorization request, cannot redirect", e);
} else {
response.sendRedirect(getRedirectUrlToRelyingParty(request, e));
}
}
}
private boolean isInvalidClient(OidcAuthorizeRequestValidator.InvalidRequestException e) {
return e.getInvalidParameter() == OidcAuthorizeRequestParameter.REDIRECT_URI || e.getInvalidParameter() == OidcAuthorizeRequestParameter.CLIENT_ID;
}
private String getRedirectUrlToRelyingParty(HttpServletRequest request, OidcAuthorizeRequestValidator.InvalidRequestException e) {
String redirectUri = request.getParameter(OidcAuthorizeRequestParameter.REDIRECT_URI.getParameterKey());
try {
StringBuilder sb = new StringBuilder();
sb.append(redirectUri);
sb.append(redirectUri.contains("?") ? "&" : "?");
sb.append(String.format("error=%s", URLEncoder.encode(e.getErrorCode(), UTF_8.name())));
sb.append(String.format("&error_description=%s", URLEncoder.encode(e.getErrorDescription(), UTF_8.name())));
String state = request.getParameter(OidcAuthorizeRequestParameter.STATE.getParameterKey());
if (StringUtils.isNotBlank(state)) {
sb.append(String.format("&state=%s", URLEncoder.encode(state, UTF_8.name())));
}
return sb.toString();
} catch (UnsupportedEncodingException ex) {
throw new IllegalStateException(ex);
}
}
private void saveOidcRequestParametersToSession(final HttpServletRequest request) {
final HttpSession session = request.getSession(true);
String[] scopeElements = getScopeElements(request);
List<TaraScope> scopes = parseScopes(scopeElements);
session.setAttribute(Constants.TARA_OIDC_SESSION_SCOPES, scopes);
if (eidasConfigurationProvider != null) {
session.setAttribute(Constants.TARA_OIDC_SESSION_SCOPE_EIDAS_COUNTRY, parseScopeEidasCountry(scopeElements).orElse(null));
}
session.setAttribute(Constants.TARA_OIDC_SESSION_CLIENT_ID,
request.getParameter(OidcAuthorizeRequestParameter.CLIENT_ID.getParameterKey())
);
session.setAttribute(Constants.TARA_OIDC_SESSION_REDIRECT_URI,
request.getParameter(OidcAuthorizeRequestParameter.REDIRECT_URI.getParameterKey())
);
List<AuthenticationType> authenticationMethodsList = getListOfAllowedAuthenticationMethods(scopes);
log.debug("List of authentication methods to display on login page: {}", authenticationMethodsList);
session.setAttribute(Constants.TARA_OIDC_SESSION_AUTH_METHODS,
authenticationMethodsList
);
final String acrValues = request.getParameter(OidcAuthorizeRequestParameter.ACR_VALUES.getParameterKey());
if (acrValues != null) session.setAttribute(Constants.TARA_OIDC_SESSION_LOA,
LevelOfAssurance.findByAcrName(acrValues));
}
private String[] getScopeElements(HttpServletRequest request) {
String scopeParameter = request.getParameter(OidcAuthorizeRequestParameter.SCOPE.getParameterKey());
if (StringUtils.isBlank(scopeParameter)) {
return new String[0];
}
return scopeParameter.split(" ");
}
private List<TaraScope> parseScopes(String[] scopeElements) {
return Arrays.stream(scopeElements)
.map(scopeElement -> {
try {
return TaraScope.getScope(scopeElement);
} catch (IllegalArgumentException e) {
log.warn("Invalid scope value '{}', entry ignored!", scopeElement);
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
private Optional<TaraScopeValuedAttribute> parseScopeEidasCountry(String[] scopeElements) {
return Arrays.stream(scopeElements)
.filter(eidasConfigurationProvider.getAllowedEidasCountryScopeAttributes()::contains)
.map(this::constructValuedScopeAttribute)
.filter(Objects::nonNull)
.findFirst();
}
private TaraScopeValuedAttribute constructValuedScopeAttribute(String scopeElement) {
int lastIndexOf = scopeElement.lastIndexOf(":");
String scopeAttributeFormalName = scopeElement.substring(0, lastIndexOf);
String scopeAttributeValue = scopeElement.substring(lastIndexOf + 1);
TaraScopeValuedAttribute scopeAttribute = null;
if (StringUtils.isNotBlank(scopeAttributeValue)) {
scopeAttribute = TaraScopeValuedAttribute.builder()
.name(TaraScopeValuedAttributeName.getByFormalName(scopeAttributeFormalName))
.value(scopeAttributeValue)
.build();
}
return scopeAttribute;
}
private List<AuthenticationType> getListOfAllowedAuthenticationMethods(final List<TaraScope> scopes) {
if (scopes.contains(TaraScope.EIDASONLY)) {
return Arrays.asList(AuthenticationType.eIDAS);
} else if (isAuthMethodSpecificScopePresent(scopes)) {
return Arrays.stream(AuthenticationType.values())
.filter(e -> scopes.contains(e.getScope()) )
.collect(Collectors.toList());
} else {
return taraProperties.getDefaultAuthenticationMethods();
}
}
private boolean isAuthMethodSpecificScopePresent(List<TaraScope> scopes) {
return !Collections.disjoint(scopes, TaraScope.SUPPORTS_AUTHENTICATION_METHOD_SELECTION);
}
@Override
public void destroy() {
log.debug("Destroy filter: {}", OidcAuthorizeRequestValidationServletFilter.class.getName());
}
}
| 4c5f7e45dcab47907b9dd87b9cb9771522343533 | [
"Java",
"INI"
] | 4 | Java | Carnivoroys/TARA-Server | e29905fa1c8f5966e7f38dbb3428c1ec0380754e | 2ef4a44af77e6cf74dcfa9c0d51c3f634506e4d8 | |
refs/heads/main | <file_sep>import os
import pyowm
from dotenv import load_dotenv
from os.path import join, dirname
from generate_countries import read_file
dotenv_path = join(dirname(__file__),'.env')
load_dotenv(dotenv_path)
#Checks if the user gave a correct country
def getTag(country):
countries = read_file()
code = ""
try:
code = countries[country.strip()]
except:
pass
return code
#Checks if the user gave a correct location
def valid_location(message):
tuple = message.strip().split(",")
if len(tuple) != 2:
return False, "Not valid"
code = getTag(tuple[1])
if code == "":
return False, "Not valid"
APIKEY = os.environ.get("API_KEY")
owm = pyowm.OWM(APIKEY)
reg = owm.city_id_registry()
list_of_locations = reg.locations_for(tuple[0], country=code)
if len(list_of_locations) == 0:
return False, "Not valid"
return True, (tuple[0] + "," + code).strip()
<file_sep># Twitter Bot that tweets the Weather everyday!
Works by tweeting at the bot with the location you want to be notified
## Usage
`@bot_tag Lisbon, Portugal`
The bot will tweet at you everyday at 08:00 Lisbon Time the maximum and minimum expected temperature for Madrid, Spain
## Bot features
- Tweets everyday at 9am Lisbon Time
- Doesn't allow multiple locations for 1 user automatically (can be done manually by changing your users_accepted.txt)
- Auto follow back (if enabled)
- Information provided:
- Forecast for maximum and minimum temperature
- Actual temperature and sensation temperature
- Bad conditions warning (Rain & Snow)
- UV Index
- Advice for sunscreen on high UV
- Tell if the weather is good to go to the beach
- Sunset time (Lisbon Time)
## Dependencies
`pip install tweepy`
`pip install pycountry`
`pip install pyowm`
`pip install google-trans-new`
`pip install python-dotenv`
## API Keys
To use this repository create a file named `.env` on `weather_twitterbot` directory
For this you need to create a Developer Twitter Account
```
CONSUMER_KEY=YOUR_CONSUMER_KEY_TWITTER_DEVELOPER_ACCOUNT
CONSUMER_SECRET=YOUR_CONSUMER_SECRET_KEY_TWITTER_DEVELOPER_ACCOUNT
ACCESS_TOKEN=YOUR_ACCESS_TOKEN_TWITTER_DEVELOPER_ACCOUNT
ACCESS_TOKEN_SECRET=YOUR_ACCESS_TOKEN_SECRET_TWITTER_DEVELOPER_ACCOUNT
API_KEY=YOUR_API_KEY_OWM
```
## Create a service
On `line 8` in `twitterbot.service`
Change `~/github/weather_twitterbot/bot.py` to `your_path_to_file/bot.py`
If you aren't sure what's the path to the file go inside the directory that contains the file and do `pwd` on the terminal
Now open the terminal on `weather_twitterbot/` and run
```
sudo cp twitterbot.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl start twitterbot.service
sudo systemctl enable twitterbot.service
```
The last command is to make sure that the service is started on system startup
<file_sep>import os
import time
import pytz
import json
import pyowm #import Python Open Weather Map
import tweepy
import datetime
import traceback
from dotenv import load_dotenv
from os.path import join, dirname
from generate_countries import read_file
from tweet_handler import valid_location
from google_trans_new import google_translator
#Get the last 20 mentions on the timeline and store it on a file
def getMention(api):
tweets = api.mentions_timeline()
with open(text_path, 'r') as f:
users_accepted = json.load(f)
print(users_accepted)
with open(text_path, 'w') as f:
user_exists = False
location_exists = False
data = []
for tweet in tweets:
tag = str(tweet.user.screen_name)
#Sees if the user is already in the database
for dic in users_accepted:
if dic.get(tag) is not None:
user_exists = True
break #If its already in the database skip
else:
user_exists = False
#If the user isnt already in the databse then add him
if not user_exists:
message = str(tweet.text.replace('@WeatherDailyBot', '').strip())
location_exists, place = valid_location(message)
if location_exists:
d = {tag: place}
data.append(dict(d))
for dat in data:
users_accepted.append(dat)
json.dump(users_accepted, f)
#Follows everyone back
def followBack(api):
print("\nFollowers:")
for follower in tweepy.Cursor(api.followers).items():
follower.follow()
print(follower.screen_name)
print()
#Check if there will be rain or snow in the location
def checkBadConditions(onecall):
status = onecall.forecast_daily[0].detailed_status
info = ""
if "snow" in status:
info = "\nHoje vai nevar " + '\U0001F328'
elif "rain" in status:
translator = google_translator()
translate_text = translator.translate(status, lang_tgt='pt')
info = "\nHoje vai ter " + translate_text + " " + '\U0001F327'
return info
#Tweets the weather
def tweetWeather(api):
now = datetime.datetime.now()
if now.hour == 8:
with open(text_path, 'r') as f:
users_accepted = json.load(f) #Do a list of dictionaries that are inside the .txt
for user in users_accepted:
key, value = list(user.items())[0] #Get the handler as a string
city, country = value.split(",")
place = reg.locations_for(city, country)[0]
one_call = mgr.one_call(place.lat, place.lon) #Creates a One Call object
forecast = one_call.forecast_daily[0].temperature('celsius') #Get information for the day
tweet_content = "Dia " + str(now.day) + " de " + months[now.month-1] + " @" + key + " vai ter máximas de " + str(round(forecast['max'], 1)) + "ºC com mínimas de " + str(round(forecast['min'], 1)) + "ºC. Atualmente estão " + str(round(one_call.current.temperature('celsius')['temp'], 1)) + "ºC em " + city + ", " + country
tweet_content += "\nA sensação de temperatura é de " + str(round(one_call.current.temperature('celsius')['feels_like'], 1)) + "ºC"
#Bad conditions warning (rain, snow, thunder?)
tweet_content += checkBadConditions(one_call)
uvi = mgruv.uvindex_around_coords(place.lat, place.lon).to_dict()['value']
tweet_content += "\nÍndice UV: " + str(round(uvi, 1))
#Sunscreen warning
if uvi >= 9.0:
tweet_content += " mete protetor solar! " + '\U0001F9F4'
#Beach time
if forecast['max'] >= 29:
tweet_content += "\nHoje vai estar bom para ir à praia! " + '\U0001F60E'
#Sunset information
observation = mgr.weather_at_place(city + ", " + country)
sunset = observation.weather.sunset_time(timeformat='date')
tweet_content += "\nO pôr-do-sol vai ser às " + sunset.astimezone(pytz.timezone("Europe/Lisbon")).strftime("%H:%M")
api.update_status(tweet_content)
print(tweet_content) #Debug
time.sleep(20)
time.sleep(2 * 60* 60) #Wait 2 hours
#Setting up enviorment variables
dotenv_path = join(dirname(__file__),'.env')
text_path = join(dirname(__file__),'users_accepted.txt')
load_dotenv(dotenv_path)
CONSUMER_KEY = os.environ.get("CONSUMER_KEY")
CONSUMER_SECRET = os.environ.get("CONSUMER_SECRET")
ACCESS_TOKEN = os.environ.get("ACCESS_TOKEN")
ACCESS_TOKEN_SECRET = os.environ.get("ACCESS_TOKEN_SECRET")
#Authenticate Twitter Credentials
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
#OpenWeatherMap API Setup
APIKEY = os.environ.get("API_KEY")
owm = pyowm.OWM(APIKEY)
mgr = owm.weather_manager()
mgruv = owm.uvindex_manager()
reg = owm.city_id_registry()
months = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"]
while True:
#Create API object
api = tweepy.API(auth, wait_on_rate_limit = True)
#Terminal debug
try:
api.verify_credentials()
print("Authentication OK")
#followBack(api)
getMention(api)
tweetWeather(api)
except:
print("Error during authentication")
traceback.print_exc()
print("Waiting...")
time.sleep(2 * 60) #Request every 2 minutes
<file_sep>import pycountry
import json
#To read this dictionary to a file
def write_file():
countries = {}
for country in pycountry.countries:
countries[country.name] = country.alpha_2
with open('countries.txt', 'w') as f:
f.write(json.dumps(countries))
#To read this dictionary and save it on your code use the following function
def read_file():
with open('countries.txt', 'r') as f:
data = f.read()
dict = json.loads(data)
"""
print(dict)
print(dict["Portugal"]) """
return dict
| 4bdc2d93299d3e59ce0dd777ff36ed5d85fbc7e4 | [
"Markdown",
"Python"
] | 4 | Python | andreclerigo/weather_twitterbot | 280e0b1092c17ca50d3d51d1d1e3a29ed2550a6c | fa5e9c599d2e05d7adf04bfddc2750fb3927da22 | |
refs/heads/main | <repo_name>nilsjc/PIC18F-MidiToCV<file_sep>/README.md
# PIC18F-MidiToCV
A midi to control voltage converter made with Microchip pic 18F4620.
It should be no problem to compile this code to other 18F-models.
This is in a experimental state. For now it takes the note number and put it on PORTD, while RB0 puts the gate out. However in future i will use a separate DAC instead, connected with SPI.
It works in monophonic state.
Internal clock is used.
Connect MIDI thru a optocoupler to the RC7 pin.
Easiest way to compile this is just to create a new project in MPLABX for your selected MCU and copypaste this code into the main file. Note my configuration settings in the beginning though, it is made for 18F4620. Replace them if other controller is used.
Have fun!
<file_sep>/main.c
/*
* File: main.c
* Author: <NAME>
*
* Created on den 6 september 2020, 20:35
*/
// PIC18F4620 Configuration Bit Settings
// 'C' source line config statements
// CONFIG1H
#pragma config OSC = INTIO67 // Oscillator Selection bits (Internal oscillator block, port function on RA6 and RA7)
#pragma config FCMEN = OFF // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor disabled)
#pragma config IESO = OFF // Internal/External Oscillator Switchover bit (Oscillator Switchover mode disabled)
// CONFIG2L
#pragma config PWRT = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = SBORDIS // Brown-out Reset Enable bits (Brown-out Reset enabled in hardware only (SBOREN is disabled))
#pragma config BORV = 3 // Brown Out Reset Voltage bits (Minimum setting)
// CONFIG2H
#pragma config WDT = OFF // Watchdog Timer Enable bit (WDT disabled (control is placed on the SWDTEN bit))
#pragma config WDTPS = 32768 // Watchdog Timer Postscale Select bits (1:32768)
// CONFIG3H
#pragma config CCP2MX = PORTC // CCP2 MUX bit (CCP2 input/output is multiplexed with RC1)
#pragma config PBADEN = OFF // PORTB A/D Enable bit (PORTB<4:0> pins are configured as analog input channels on Reset)
#pragma config LPT1OSC = OFF // Low-Power Timer1 Oscillator Enable bit (Timer1 configured for higher power operation)
#pragma config MCLRE = OFF // MCLR Pin Enable bit (MCLR pin enabled; RE3 input pin disabled)
// CONFIG4L
#pragma config STVREN = ON // Stack Full/Underflow Reset Enable bit (Stack full/underflow will cause Reset)
#pragma config LVP = ON // Single-Supply ICSP Enable bit (Single-Supply ICSP enabled)
#pragma config XINST = OFF // Extended Instruction Set Enable bit (Instruction set extension and Indexed Addressing mode disabled (Legacy mode))
// CONFIG5L
#pragma config CP0 = OFF // Code Protection bit (Block 0 (000800-003FFFh) not code-protected)
#pragma config CP1 = OFF // Code Protection bit (Block 1 (004000-007FFFh) not code-protected)
#pragma config CP2 = OFF // Code Protection bit (Block 2 (008000-00BFFFh) not code-protected)
#pragma config CP3 = OFF // Code Protection bit (Block 3 (00C000-00FFFFh) not code-protected)
// CONFIG5H
#pragma config CPB = OFF // Boot Block Code Protection bit (Boot block (000000-0007FFh) not code-protected)
#pragma config CPD = OFF // Data EEPROM Code Protection bit (Data EEPROM not code-protected)
// CONFIG6L
#pragma config WRT0 = OFF // Write Protection bit (Block 0 (000800-003FFFh) not write-protected)
#pragma config WRT1 = OFF // Write Protection bit (Block 1 (004000-007FFFh) not write-protected)
#pragma config WRT2 = OFF // Write Protection bit (Block 2 (008000-00BFFFh) not write-protected)
#pragma config WRT3 = OFF // Write Protection bit (Block 3 (00C000-00FFFFh) not write-protected)
// CONFIG6H
#pragma config WRTC = OFF // Configuration Register Write Protection bit (Configuration registers (300000-3000FFh) not write-protected)
#pragma config WRTB = OFF // Boot Block Write Protection bit (Boot Block (000000-0007FFh) not write-protected)
#pragma config WRTD = OFF // Data EEPROM Write Protection bit (Data EEPROM not write-protected)
// CONFIG7L
#pragma config EBTR0 = OFF // Table Read Protection bit (Block 0 (000800-003FFFh) not protected from table reads executed in other blocks)
#pragma config EBTR1 = OFF // Table Read Protection bit (Block 1 (004000-007FFFh) not protected from table reads executed in other blocks)
#pragma config EBTR2 = OFF // Table Read Protection bit (Block 2 (008000-00BFFFh) not protected from table reads executed in other blocks)
#pragma config EBTR3 = OFF // Table Read Protection bit (Block 3 (00C000-00FFFFh) not protected from table reads executed in other blocks)
// CONFIG7H
#pragma config EBTRB = OFF // Boot Block Table Read Protection bit (Boot Block (000000-0007FFh) not protected from table reads executed in other blocks)
// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.
#include <xc.h>
// variables
unsigned char MIDI_CHANNEL = 0; // selected midi channel
unsigned char waiting = 0; // this is a rough way to check data bytes in correct order
unsigned char velocity = 0;
unsigned char pitch = 0;
unsigned char oldPitch = 0; // used when checking note of
unsigned char busyPlaying = 0; // for filtering other notes if one is playing, should be changed
unsigned char buffer[32]; // kind of midi buffer, could probably be much smaller
unsigned int index = 0; // index is used to indicate the use of the buffer
unsigned char noteRecently = 0; // for checking if the previous status was note on
unsigned char incomingMidiChannel = 0; // used when to check which midi channel is playing
void helloThere(void)
{
unsigned int x;
PORTBbits.RB1 = 1;
for(x=0; x<0xFFFF; x++){
// do nothing
}
PORTBbits.RB1 = 0;
}
char uartRead(){
while(!RCIF){
// do nothing
}
return RCREG;
}
void processMidimessage(unsigned char* midiMessage)
{
// if this two bytes of no interest is detected: return
if(*midiMessage==0xFE)
{
return;
}
else if(*midiMessage==0xF8)
{
return;
}
// this is to check if incoming byte is status or data
unsigned char dataBit = 0;
dataBit = *midiMessage & 0b10000000;
if(dataBit > 0)
{ // it is a status byte
incomingMidiChannel = *midiMessage & 0b00001111;
noteRecently = 0;
if(*midiMessage == 0x90) // note on
{
waiting = 3;
}else
{
}
return;
}else{
// it is data byte
// check if it is correct midi channel,
// otherwise return
if(incomingMidiChannel != MIDI_CHANNEL)
{
return;
}
// was the last status byte a note on?
// then the data byte is note information
if(noteRecently == 1)
{
waiting = 3;
}
if(waiting == 3)
{
pitch = *midiMessage;// take key
waiting = 2;
return;
}
if(waiting == 2)
{
noteRecently = 1;
velocity = *midiMessage;// take velocity
if(velocity > 0)
{
if(busyPlaying == 0)
{
oldPitch = pitch;
busyPlaying = 1;
PORTBbits.RB0 = 1;
PORTD = pitch;
}
waiting = 0;
return;
}else{
if (pitch == oldPitch)
{
PORTBbits.RB0 = 0;
busyPlaying = 0;
waiting = 0;
return;
}}
}
}
}
void __interrupt() myISR()
{
if(RCIF == 1)
{
unsigned char incomingMessage = uartRead();
buffer[index] = incomingMessage;
index++;
if(index>31)
{
// buffer overflow
// feel free to experiment ;-)
helloThere();
index = 31;
}
}
}
void main(void) {
OSCCON=0x70; // Select 8 MHz internal clock
INTCONbits.GIE=1; // Enable all unmasked global INT
INTCONbits.PEIE=1; // Enable Peripheral interrupt
PIR1bits.RCIF=1;
PIE1bits.RCIE=1; // enable usart receive interrupt
SWDTEN = 0; // disable watchdog timer
TRISC = 0b10000000; // Set All on PORTC as Output
TRISB = 0b00000000;
TRISD = 0b00000000;
PORTC = 0x00; // Turn Off all PORTC
PORTB = 0x00;
SPBRG = 15; // set correct baud rate
BRGH = 1;
TX9 = 0;
SYNC = 0;
SPEN = 1;
CREN = 1;
TXEN = 1;
helloThere();
// actual program
for(;;)
{
// endless loop
if(index>2) // something is in the buffer
{
unsigned int scan;
for(scan=0; scan<index; scan++) // scan thru the buffer
{
processMidimessage(&buffer[scan]);
}
index = 0; // we have checked the buffer and set index from start again
}
}
return;
}
| 080b20371e618e28b37d6a7cb5e4a73056d7deae | [
"Markdown",
"C"
] | 2 | Markdown | nilsjc/PIC18F-MidiToCV | 1451a07be101bb23fc31ee53695692648426e8f4 | 7d225b374b71d7a940027704d919bfa61cec6202 | |
HEAD | <repo_name>DavisReef/angular-depth-viewer<file_sep>/src/lib/directive.js
'use strict';
import Depth from './Depth/Depth';
/**
* Depth photo directive
*/
export default function DepthDirective(depthConfig) {
'ngInject';
return {
restrict: 'EA',
scope: {
src: '@',
debug: '@',
fit: '@',
width: '@',
height: '@',
enlarge: '@',
trace: '@',
quality: '@',
size: '@',
animate: '@',
animateDuration: '@',
depthFactor: '@',
depthFocus: '@',
depthEqualize: '@',
depthmapSrc: '@',
depthPreview: '@',
depthBlurSize: '@',
mouseTracking: '@',
gyroTracking: '@',
gyroTrackingFactor: '@',
faceTracking: '@',
faceTrackingFactor: '@',
faceTrackingDebug: '@',
refocus: '@',
focusPoint: '@',
focusPointChangeable: '@',
focusBlur: '@',
focusBlurChangeable: '@',
onRefocus: '&'
},
link: (scope, element, attrs) => {
let depth;
let options = {};
let optionsList = {
src: 'string',
debug: 'boolean',
trace: 'boolean',
fit: 'string|false',
enlarge: 'number',
quality: 'number|false',
size: 'size',
animate: 'boolean',
animateDuration: 'number',
depthFactor: 'number',
depthFocus: 'number',
depthEqualize: 'boolean',
depthmapSrc: 'string|null',
depthPreview: 'number',
depthBlurSize: 'number',
mouseTracking: 'boolean',
gyroTracking: 'boolean',
gyroTrackingFactor: 'number',
faceTracking: 'boolean',
faceTrackingFactor: 'number',
faceTrackingDebug: 'boolean',
refocus: 'boolean',
focusPoint: 'point',
focusPointChangeable: 'boolean',
focusBlur: 'number',
focusBlurChangeable: 'boolean'
};
// init options
Object.keys(optionsList).forEach(key => initOption(key, optionsList[key]));
// parse width/height
if (attrs.width && attrs.height) {
options.size = {width: parseInt(attrs.width), height: parseInt(attrs.height)};
attrs.size = `${options.size.width}x${options.size.height}`;
}
options.debug && debugPrint('options', options);
depth = new Depth(element[0], options);
// show when ready
depth.on('ready', () => {
element.addClass('ready');
});
depth.on('refocus', () => {
if (angular.isFunction(scope.onRefocus)) {
scope.$evalAsync(scope.onRefocus({
refocus: {
focusPoint: depth.options.focusPoint,
focusBlur: depth.options.focusBlur
}
}));
}
});
scope.$on('$destroy', () => depth && depth.destroy());
/**
* Init directive option
*/
function initOption(name, type = 'string') {
if ('undefined' !== typeof attrs[name]) {
options[name] = convertOption(attrs[name], type);
} else if ('undefined' !== typeof depthConfig.defaults[name]) {
options[name] = convertOption(depthConfig.defaults[name], type);
}
attrs.$observe(name, (val) => {
if (depth && 'undefined' !== typeof val) {
options[name] = convertOption(val, type);
options.debug && debugPrint(`${name} => ${angular.toJson(val)}`, typeof val);
depth.setOption(name, options[name]);
}
});
}
}
};
}
/**
* Convert option
* @param {*} val
* @param {string} type
* @returns {*}
*/
function convertOption(val, type) {
switch (type) {
case 'boolean':
val = convertBool(val);
break;
case 'number|false':
val = val === '' ? false : parseFloat(val);
break;
case 'string|false':
val = val === '' ? false : val;
break;
case 'string|null':
val = val === '' ? null : val;
break;
case 'number':
val = val === '' ? .0 : parseFloat(val);
break;
case 'point':
// XxY
if (val === '') {
val = null;
} else {
val = val.split(/[x\,\;\*]/);
val = {x: parseFloat(val[0]), y: parseFloat(val[1])};
}
break;
case 'size':
// WxH
if (val === '') {
val = null;
} else {
val = val.split(/[x\,\;\*]/);
val = {width: parseInt(val[0]), height: parseInt(val[1])};
}
break;
default:
break;
}
return val;
}
/**
* Convert boolean value
*/
function convertBool(val) {
val = val.toString().trim().toLowerCase();
switch (val) {
case 'false':
case '0':
case '':
return false;
break;
default:
return true;
}
}
/**
* Debug print
* @param objects
*/
function debugPrint(...objects) {
objects.unshift('[directive]');
console.log(...objects);
}
<file_sep>/dev/gulp/tasks/demo/optimize-assets.js
/**
* Optimize assets
* - concatenate
* - minify
**/
var gulp = require('gulp');
var gulpIf = require('gulp-if');
var config = require('../../config');
var gulpNgAnnotate = require('gulp-ng-annotate');
var gulpUglify = require('gulp-uglify');
gulp.task('demo:optimize-assets', function () {
return gulp.src(config.paths.demo_build + '/**')
// minify js
.pipe(gulpIf('*.js', gulpNgAnnotate()))
.pipe(gulpIf('*.js', gulpUglify()))
.pipe(gulp.dest(config.paths.demo_build));
});
<file_sep>/src/lib/Depth/Facetracker.js
/**
* Face tracker
*
* Events:
* track {x: -1..1, y: -1..1}
* noCamera
*
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*/
import headtrackr from 'headtrackr';
import EventEmitter from 'eventemitter3';
const CANVAS_WIDTH = 320;
const CANVAS_HEIGHT = 240;
export default class Facetracker extends EventEmitter {
constructor(options = {}) {
super();
// default options
this._options = {
debug: true,
debugOverlay: true
};
this._isTracking = false;
this.options = options;
this._attachEventlisteners();
this.start();
}
/**
* Options property setter
* @param val
*/
set options(val) {
this._options = Object.assign(this._options, val);
}
get x() {
return Math.max(-1, Math.min(1, this._x || 0));
}
get y() {
return Math.max(-1, Math.min(1, this._y || 0));
}
get isTracking() {
return this._isTracking;
}
/**
* Listen to headtrackr events
* @private
*/
_attachEventlisteners() {
document.addEventListener('headtrackrStatus', (event) => {
if (event.status === 'no camera') {
if (this._options.debug) {
this._debugPrint('No camera access');
}
this.emit('noCamera');
this._isTracking = false;
}
});
document.addEventListener('facetrackingEvent', (event) => {
this._x = (event.x / CANVAS_WIDTH) * 2 - 1 /* -1..1 */;
this._y = (event.y / CANVAS_HEIGHT) * 2 - 1 /* -1..1 */;
this.emit('track', {x: this.x, y: this.y});
});
}
/**
* Initlaization
* @private
*/
start() {
this._canvas = this._createCanvas();
this._video = this._createVideo();
this._ht = new headtrackr.Tracker({ui: false, debug: this._options.debugOverlay ? this._canvas : undefined});
this._ht.init(this._video, this._canvas);
this._ht.start();
this._isTracking = true;
}
/**
* Stop tracking/free resources
*/
stop() {
// stop video
// !!! todo submit PR to headtrackr with a fix to stopStream()
this._ht.stream && this._ht.stream.getVideoTracks().forEach((track) => {
track.stop();
});
this._ht.stop();
this._ht = null;
// remove canvas element
if (this._canvasAppended) {
document.body.removeChild(this._canvas);
this._canvasAppended = false;
}
// destroy elements
this._canvas = null;
this._video = null;
this._isTracking = false;
}
/**
* Create canvas
* @returns {HTMLCanvasElement}
* @private
*/
_createCanvas() {
let canvas = document.createElement('canvas');
canvas.setAttribute('style', 'display:none');
canvas.setAttribute('width', CANVAS_WIDTH);
canvas.setAttribute('height', CANVAS_HEIGHT);
// show video overlay in the center
if (this._options.debugOverlay) {
canvas.setAttribute(
'style',
'position:absolute;opacity:0.5;left:50%;top:50%;margin-left:-160px;margin-top:-120px'
);
document.body.appendChild(canvas);
this._canvasAppended = true;
}
return canvas;
}
/**
* Create video element
* @returns {Element}
* @private
*/
_createVideo() {
let video = document.createElement('video');
video.setAttribute('autoplay', 'true');
video.setAttribute('loop', 'true');
return video;
}
/**
* Debug printout
* @param objects
* @private
*/
_debugPrint(...objects) {
objects.unshift('[facetracker]');
console.log(...objects);
}
}
<file_sep>/src/lib/Depth/Normalizer/HistorgramEqualizer.js
/**
* Historgram equalizer algorithm for Normalizer
*
* Based on https://pixelero.wordpress.com/2014/11/16/median-filter-for-html5js/
*
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*/
export default class HistorgramEqualizer {
/**
* @param {imageData} imageData
*/
process(imageData) {
let data = imageData.data;
let hists = this._calculateHistograms(data);
hists[0] = this._blurHistogram(hists[0]);
hists[1] = this._blurHistogram(hists[1]);
hists[2] = this._blurHistogram(hists[2]);
const bins = 64;
// histograms of how values of each channel are distributed:
// note: this is a modified version: it doesn't equalize the channels,
// but tries to equalize their sum:
let tst = this._equalizeHistogramSum(hists[0], hists[1], hists[2], bins),
rarr = tst[0],
garr = tst[1],
barr = tst[2];
// apply normalized histogram for red channel to depth map
for (let i = 0; i < data.length; i += 4) {
data[i] = data[i + 1] = data[i + 2] = rarr[data[i]] << 2;
data[i + 3] = 0xff; // discard alpha channel
}
return imageData;
}
/**
* Loops through an image, and adds rgb-values to corresponding histogram bins:
* @param {ImageData} data
* @returns {*[]}
* @private
*/
_calculateHistograms(data, N = 5) {
let rarr = new Uint32Array(256),
garr = new Uint32Array(256),
barr = new Uint32Array(256);
// in case of a very large image this could be sped up
// by sample only every 2nd, 3rd or Nth pixel: i+=6, i+=10, i+=2+4*N
for (let i = 0; i < data.length; i += 2 + 4 * N) {
rarr[data[i++]]++;
garr[data[i++]]++;
barr[data[i]]++;
}
return [rarr, garr, barr];
}
/**
* Applies a running average of three [previous,this,next] to an array:
* @param {array} hst
* @returns {Uint32Array}
* @private
*/
_blurHistogram(hst) {
let hst2 = new Uint32Array(hst.length);
hst2[0] = hst2[1] = 1.5 * hst[0];
let i = hst.length - 1;
hst2[i] = hst[i - 1] = 1.5 * hst[i];
for (i = 1; i < hst.length - 1; i++) {
hst2[i - 1] = hst2[i] = hst2[i + 1] = hst[i];
}
for (i = 0; i < hst2.length; i++) {
hst2[i] /= 3;
}
return hst2;
}
_equalizeHistogramSum(rh, gh, bh, bins = 64) {
let total_sum = 0, N = rh.length;
for (let i = 0; i < N; i++) {
total_sum += rh[i] + gh[i] + bh[i];
}
let m = total_sum / bins,
sum = 0,
ir = 0, ig = 0, ib = 0,
j = 0,
r, g, b, min, max,
rh2 = new Uint32Array(N),
gh2 = new Uint32Array(N),
bh2 = new Uint32Array(N);
while (ir < N || ig < N || ib < N) {
r = ir < N ? rh[ir] : 0;
g = ig < N ? gh[ig] : 0;
b = ib < N ? bh[ib] : 0;
if (r < g) {
min = r;
max = g;
} else {
min = g;
max = r;
}
if (b < min) {
min = b;
} else if (b > max) {
max = b;
}
if (max >= 0.9 * (r + g + b)) {
rh2[ir++] =
gh2[ig++] =
bh2[ib++] = j;
sum += r + g + b;
} else {
if (r == min) {
rh2[ir++] = j;
} else if (g == min) {
gh2[ig++] = j;
} else {
bh2[ib++] = j;
}
if (r == max) {
rh2[ir++] = j;
} else if (g == max) {
gh2[ig++] = j;
} else {
bh2[ib++] = j;
}
sum += min + max;
}
while (sum > m) {
sum -= m;
j++;
}
}
return [rh2, gh2, bh2];
}
}
<file_sep>/dev/shim/depth-reader.js
module.exports = window.DepthReader;
<file_sep>/src/demo/vendors.js
'use strict';
import 'angular';
import PIXI from 'pixi.js/bin/pixi.min.js';
<file_sep>/src/lib/Depth/filters/DepthPerspectiveFilter.js
/**
Experimental shader giving perspective effect on image with depthmap.
Quality is controlled by defined profiles 1, 2 and 3.
---------------
The MIT License
Copyright (c) 2014 <NAME>. http://panrafal.github.com/depthy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@author <NAME>
@author <NAME> <<EMAIL>>
@author <NAME> <<EMAIL>>
*/
'use strict';
import fragment from './DepthPerspectiveFilter.frag!text';
import PIXI from 'pixi.js/bin/pixi.min.js';
export default class DepthPerspectiveFilter extends PIXI.AbstractFilter {
constructor(texture, quality) {
super();
this.passes = [this];
// set the uniforms
this.uniforms = {
displacementMap: {type: 'sampler2D', value: texture},
scale: {type: '1f', value: 0.015},
offset: {type: 'v2', value: {x: 0, y: 0}},
mapDimensions: {type: 'v2', value: {x: 1, y: 5112}},
dimensions: {type: '4fv', value: [0, 0, 0, 0]},
focus: {type: '1f', value: 0.5},
enlarge: {type: '1f', value: 1.06},
refocusedImage: {type: 'sampler2D', value: texture/* !!! init with null */},
refocusEnabled: {type: '1f', value: 1}
};
if (texture.baseTexture.hasLoaded) {
this.uniforms.mapDimensions.value.x = texture.width;
this.uniforms.mapDimensions.value.y = texture.height;
} else {
this.boundLoadedFunction = this.onTextureLoaded.bind(this);
texture.baseTexture.on('loaded', this.boundLoadedFunction);
}
this.fragmentSrc = fragment;
this.quality = quality;
if (quality) {
this.fragmentSrc = (`#define QUALITY ${quality} \n`) + this.fragmentSrc;
}
}
onTextureLoaded() {
this.uniforms.mapDimensions.value.x = this.uniforms.displacementMap.value.width;
this.uniforms.mapDimensions.value.y = this.uniforms.displacementMap.value.height;
this.uniforms.displacementMap.value.baseTexture.off('loaded', this.boundLoadedFunction);
}
/**
* The texture used for the displacemtent map * must be power of 2 texture at the moment
*/
set map(value) {
this.uniforms.displacementMap.value = value;
}
get map() {
return this.uniforms.displacementMap.value;
}
/**
* The multiplier used to scale the displacement result from the map calculation.
*/
set scale(value) {
this.uniforms.scale.value = value;
}
get scale() {
return this.uniforms.scale.value;
}
/**
* Focus point in paralax
*/
set focus(value) {
this.uniforms.focus.value = Math.min(1, Math.max(0, value));
}
get focus() {
return this.uniforms.focus.value;
}
/**
* Image enlargment
*/
set enlarge(value) {
this.uniforms.enlarge.value = value;
}
get enlarge() {
return this.uniforms.enlarge.value;
}
/**
* The offset used to move the displacement map.
*/
set offset(value) {
this.uniforms.offset.value = value;
}
get offset() {
return this.uniforms.offset.value;
}
/**
* Refocused image
* @param {PIXI.Texture} value
*/
set refocusedImage(value) {
this.uniforms.refocusedImage.value = value;
}
/**
* Refocused image
* @return {PIXI.Texture}
*/
get refocusedImage() {
return this.uniforms.refocusedImage.value;
}
set refocusEnabled(value) {
this.uniforms.refocusEnabled.value = value;
}
get refocusEnabled() {
return this.uniforms.refocusEnabled.value;
}
}
<file_sep>/README.md
# Depth Viewer
__AngularJS Component / Library__
Viewer component for images with embedded depth map created with devices based on Intel RealSense tech and others.
## Development Requirements
|Dependency|OS X Installation|
|:--|:--|
|node.js 4.x+|`brew install nodejs`|
|gulp|`npm install -g gulp`|
|jspm|`npm install -g jspm`|
## Development
### Installation
```
npm i
jspm i
```
### Demo App
`gulp demo:serve`
### Build for Bower
`gulp dist`
Dependencies must be listed in `bower.json` and `dev/gulp/tasks/dist.js`
## Available Gulp Tasks
|Command|Desc|
|:--|:--|
|`gulp demo:cleanup`|Demp App: Remove build files|
|`gulp demo:serve` _(default)_|Demp App: Launch demo with live reload|
|`gulp demo:build:development`|Demp App: Build demo app for development environment|
|`gulp demo:build:production`|Demp App: Build demo app for production environment|
|`gulp demo:bundle-vendors`|Demp App: Bundle vendors for faster reload in develeopment|
|`gulp demo:compile-scripts`|Demp App: Compile scripts into sfx bundle|
|`gulp demo:optimize-assets`|Demp App: Optimize assets|
|`gulp demo:set-environment:production`|Demp App: Update environment|
|`gulp demo:set-environment:development`|Demp App: Update environment|
## License
MIT
<file_sep>/dev/gulp/tasks/demo/compile-scripts.js
/**
* Compile scripts into a self-containg bundle
*/
var gulp = require('gulp');
var gulpShell = require('gulp-shell');
var utils = require('../../utils');
var config = require('../../config');
gulp.task('demo:compile-scripts', (function () {
var command = 'jspm bundle-sfx ' + // create self-sufficient bundle
utils.escapeShellArg(config.demoComplileScripts.src) + ' ' + // source
utils.escapeShellArg(config.demoComplileScripts.dest) + // dest
''; // minify
return gulpShell.task([command]);
})());
<file_sep>/src/lib/Depth/filters/filters.js
'use strict';
import PIXI from 'pixi.js/bin/pixi.min.js';
import './ColorMatrixFilter2';
import DepthPerspectiveFilter from './DepthPerspectiveFilter';
import BokehBlurFilter from './BokehBlurFilter';
import BlurCalculationFilter from './BlurCalculationFilter';
import RefocusCompoundFilter from './RefocusCompoundFilter';
/**
* Create PIXI filter to discard alpha channel
* @param alphaConst
* @returns {PIXI.ColorMatrixFilter2}
*/
export function createDiscardAlpaFilter(alphaConst = 0.0) {
let filter = new PIXI.ColorMatrixFilter2();
filter.matrix = [1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0];
filter.shift = [0.0, 0.0, 0.0, alphaConst];
return filter;
}
/**
* Depth blur filter
* @return {PIXI.BlurFilter}
*/
export function createDepthBlurFilter() {
return new PIXI.filters.BlurFilter();
}
/**
*
* @param {PIXI.RenderTexture} texture
* @param {number} quality
*/
export function createDepthPerspectiveFilter(texture, quality) {
return new DepthPerspectiveFilter(texture, quality);
}
/**
* @param {PIXI.RenderTexture} texture
* @param {number} quality
*/
export function createRefocusCompoundFilter(texture) {
return new RefocusCompoundFilter(texture);
}
<file_sep>/dev/gulp/tasks/demo/serve.js
/**
* Serve the client with live reload
**/
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
var config = require('../../config');
var path = require('path');
var os = require('os');
gulp.task('demo:serve', ['demo:build:development'], function () {
// serve with BrowserSync
browserSync({
startPath: '/intel-cf-depth/src/demo/',
server: {
baseDir: config.paths.root,
routes: {
"/intel-cf-depth": ''
}
},
notify: true
});
gulp.watch(config.demoBundleVendors.src, ['demo:bundle-vendors']);
});
<file_sep>/src/lib/Depth/Normalizer/Normalizer.js
/**
* Image brightness normalizer
*/
import RangeStretcher from './RangeStretcher';
import HistorgramEqualizer from './HistorgramEqualizer';
export default class Normalizer {
/**
* @param {string} uri
*/
constructor(uri) {
this.debug = true;
this._image = new Image();
this._image.src = uri;
}
/**
* Process image
* @returns {Promise}
*/
process() {
return new Promise((resolve, reject) => {
if (this._image.complete /* image is loaded */) {
this._process();
resolve(this._uri);
} else /* image is not yet loaded */ {
this._image.onload = (e) => {
this._image.onload = null;
this._process();
resolve(this._uri);
};
}
});
}
_process() {
// create canvas
this._canvas = document.createElement('canvas');
this._canvas.width = this._image.width;
this._canvas.height = this._image.height;
// draw original image
this._ctx = this._canvas.getContext('2d');
this._ctx.drawImage(this._image, 0, 0);
if (this._debug) {
this._debugPrint('Map before normalization', this._canvas.toDataURL());
}
this._imageData = this._ctx.getImageData(0, 0, this._image.width, this._image.height);
// normalize map
this._runProcessor(new HistorgramEqualizer());
this._runProcessor(new RangeStretcher());
// put image data to canvas, update uri
this._ctx.putImageData(this._imageData, 0, 0);
this._uri = this._canvas.toDataURL();
}
/**
* @param {object} processor
* @private
*/
_runProcessor(processor) {
this._imageData = processor.process(this._imageData);
if (this._debug) {
this._ctx.putImageData(this._imageData, 0, 0);
this._debugPrint('Normalized map', this._canvas.toDataURL());
}
}
/**
* Debug print
* @param {*} objects
* @private
*/
_debugPrint(...objects) {
objects.unshift('[debug]');
console.log(...objects);
}
// <editor-fold desc="Accessors" defaultstate="collapsed">
set debug(val) {
this._debug = !!val;
}
get debug() {
return !!this._debug;
}
// </editor-fold>
}
<file_sep>/dev/shim/eventemitter3.js
module.exports = window.EventEmitter;
<file_sep>/src/lib/Depth/Normalizer/RangeStretcher.js
/**
* Range stretcher algorithm for Normalizer
*
* @author <NAME> <<EMAIL>>
*/
export default class RangeStretcher {
/**
* @param {imageData} imageData
*/
process(imageData) {
// number of levels for histogram
const levels = 256;
// treshold for searching white/black point 0..1
const bpTreshold = 0.001;
const wpTreshold = 0.01;
let data = imageData.data;
let hist = new Uint32Array(levels);
let sum = 0;
// calculate histogram
for (let i = 0; i < data.length; i += 4) {
hist[~~(data[i] / 256 * levels)]++;
sum += data[i];
}
// find everage
let avg = sum / levels;
// find white and black points
let whitePointTreshold = wpTreshold * avg;
let blackPointTreshold = bpTreshold * avg;
let b = 0;
let w = hist.length - 1;
while (hist[b] < bpTreshold) {
b++;
}
while (hist[w] < whitePointTreshold) {
w--;
}
// offset and scale image data
let scale = levels / (w - b + 1);
let offset = b / levels * 255;
for (let i = 0; i < data.length; i += 4) {
data[i] = ~~(-offset + data[i] * scale);
for (let j = 0; j < 3; j++) {
data[i + j] = data[i];
}
data[i + 3] = 255; // discard alpha
}
return imageData;
}
}
<file_sep>/src/lib/Depth/filters/BokehBlurFilter.js
/**
* Bokeh blur filter
* Based on http://devlog-martinsh.blogspot.com/2011/11/glsl-depth-of-field-with-bokeh-v21.html
* @author <NAME>
*/
'use strict';
import fragment from './BokehBlurFilter.frag!text';
import PIXI from 'pixi.js/bin/pixi.min.js';
export default class BokehBlurFilter extends PIXI.AbstractFilter {
/**
* @param {PIXI.Texture} displacementMap
*/
constructor(displacementMap) {
super();
this.uniforms = {
displacementMap: {type: 'sampler2D', value: displacementMap},
mapDimensions: {type: 'v2', value: {x: 1, y: 5112}},
focusPoint: {type: 'v2', value: {x: 0.5671875, y: 0.6875}/* todo: set focus point automatically */},
blurIntensity: {type: '1f', value: 1},
blurGrowth: {type: '1f', value: 3},
blur: {type: '1f', value: 0.75/* todo: adjust default value and range */},
cssWidth: {type: '1f', value: 100.0},
cssHeight: {type: '1f', value: 100.0}
};
if (displacementMap.baseTexture.hasLoaded) {
this.uniforms.mapDimensions.value.x = displacementMap.width;
this.uniforms.mapDimensions.value.y = displacementMap.height;
} else {
this.boundLoadedFunction = this.onTextureLoaded.bind(this);
displacementMap.baseTexture.on('loaded', this.boundLoadedFunction);
}
this.displacementMap = displacementMap;
this.fragmentSrc = fragment;
}
onTextureLoaded() {
this.uniforms.mapDimensions.value.x = this.uniforms.displacementMap.value.width;
this.uniforms.mapDimensions.value.y = this.uniforms.displacementMap.value.height;
this.uniforms.displacementMap.value.baseTexture.off('loaded', this.boundLoadedFunction);
}
// <editor-fold desc="Accessors" defaultstate="collapsed">
set displacementMap(value) {
this.uniforms.displacementMap.value = value;
}
get displacementMap() {
return this.uniforms.displacementMap.value;
}
/**
* Focus point: {x: 0..1, y: 0..1}
* Starting from top-left corner
*/
set focusPoint(value) {
this.uniforms.focusPoint.value = value;
}
get focusPoint() {
return this.uniforms.focusPoint.value;
}
set blur(value) {
this.uniforms.blur.value = value;
}
get blur() {
return this.uniforms.blur.value;
}
set blurIntensity(value) {
this.uniforms.blurIntensity.value = value;
}
get blurIntensity() {
return this.uniforms.blurIntensity.value;
}
set blurGrowth(value) {
this.uniforms.blurGrowth.value = value;
}
get blurGrowth() {
return this.uniforms.blurGrowth.value;
}
set cssWidth(value) {
this.uniforms.cssWidth.value = value;
}
get cssWidth() {
return this.uniforms.cssWidth.value;
}
set cssHeight(value) {
this.uniforms.cssHeight.value = value;
}
get cssHeight() {
return this.uniforms.cssHeight.value;
}
// </editor-fold>
}
<file_sep>/src/lib/Depth/Error.js
/**
* Depth photo error
*/
'use strict';
export default class extends Error {
constructor(message, code) {
super();
this.message = message || '';
this.code = code || 0;
}
}
<file_sep>/src/lib/index.js
/**
* Depth Viewer
*/
'use strict';
import 'angular';
import DepthDirective from './directive';
import DepthDirectiveConfig from './config';
export default angular
.module('angular-depth', [])
.provider('depthConfig', DepthDirectiveConfig)
.directive('depth', DepthDirective);
<file_sep>/src/demo/demoImages.js
export default [
'images/xdm_sample_1-sm.jpg',
'images/xdm_sample_2-sm.jpg',
'images/xdm_sample_3-sm.jpg',
'images/xdm_sample_4-sm.jpg',
'images/xdm_sample_5-sm.jpg',
'images/xdm_sample_6-sm.jpg',
'images/xdm_sample_7-sm.jpg',
'images/dec14-2-sm.jpg',
'images/dec14-3-sm.jpg',
'images/dec14-4-sm.jpg',
'images/IMG_DEPTH_2015120822065086-sm.jpg',
'images/IMG_DEPTH_20151209000719899-sm.jpg',
'images/glb1-sm.jpg',
'images/glb2-sm.jpg',
'images/z1-sm.jpg',
'images/z2-sm.jpg',
'images/z3-sm.jpg',
'images/z4-sm.jpg',
'images/z5-sm.jpg',
'images/z6-sm.jpg',
'images/z7-sm.jpg',
'images/z8-sm.jpg',
'images/z9-sm.jpg',
'images/z10-sm.jpg',
'images/z11-sm.jpg',
'images/z12-sm.jpg',
'images/z13-sm.jpg',
'images/z14-sm.jpg',
'images/z15-sm.jpg',
'images/z16-sm.jpg',
'images/z17-sm.jpg',
'images/z18-sm.jpg',
'images/z19-sm.jpg',
'images/z20-sm.jpg',
'images/z21-sm.jpg',
'images/z22-sm.jpg',
'images/z23-sm.jpg',
'images/z24-sm.jpg',
'images/z25-sm.jpg',
'images/z26-sm.jpg',
'images/z27-sm.jpg',
'images/z28-sm.jpg',
'images/z29-sm.jpg',
'images/z30-sm.jpg',
'images/z31-sm.jpg',
'images/z32-sm.jpg',
'images/z33-sm.jpg',
'images/z34-sm.jpg',
'images/z35-sm.jpg',
'images/z36-sm.jpg',
'images/z37-sm.jpg',
'images/z38-sm.jpg',
'images/z39-sm.jpg',
'images/z40-sm.jpg',
'images/z41-sm.jpg',
'images/d1-sm.jpg',
'images/d2-sm.jpg',
'images/d3-sm.jpg',
'images/d4-sm.jpg',
'images/d5-sm.jpg',
'images/d6-sm.jpg',
'images/d7-sm.jpg',
'images/d8-sm.jpg',
'images/d9-sm.jpg',
'images/d10-sm.jpg',
'images/d11-sm.jpg',
'images/d12-sm.jpg',
'images/d13-sm.jpg',
'images/d14-sm.jpg',
'images/d15-sm.jpg',
'images/d16-sm.jpg',
'images/d17-sm.jpg',
'images/d18-sm.jpg',
'images/d19-sm.jpg',
'images/d20-sm.jpg',
'images/d21-sm.jpg',
'images/d22-sm.jpg',
'images/glb3.jpg',
'images/glb4.jpg'
];
<file_sep>/dev/gulp/config.js
/**
* Gulp configuration
*/
'use strict';
// paths
exports.paths = {};
exports.paths.root = __dirname + '/../..';
exports.paths.tests = exports.paths.root + '/src/tests';
exports.paths.demo = exports.paths.root + '/src/demo';
exports.paths.demo_build = exports.paths.root + '/src/demo/build';
exports.demoBundleVendors = {
src: exports.paths.demo + '/vendors.js',
dest: exports.paths.demo_build + '/vendors-bundle.js'
}
exports.demoComplileScripts = {
src: exports.paths.demo + '/app.js',
dest: exports.paths.demo_build + '/build.js'
}
<file_sep>/src/demo/app.js
/**
* Demo app
*/
'use strict';
import angular from 'angular';
import depthViewerModule from '../lib/index';
import dat from 'dat-gui';
import demoImages from './demoImages';
// load app modules
let app = angular.module('app', [depthViewerModule.name]);
app.config(($sceProvider, depthConfigProvider) => {
'ngInject';
$sceProvider.enabled(false);
depthConfigProvider.defaults.debug = true;
depthConfigProvider.defaults.src = 'images/xdm_sample_6-sm.jpg';
depthConfigProvider.defaults.size = '640x480';
});
// main controller
app.controller('MainController', ($scope, depthConfig) => {
'ngInject';
let gui = new dat.GUI({width: 350});
let localSrcFileInput = document.getElementById('local-src-file-input');
let srcSelector = {
src: '',
localSrc: () => localSrcFileInput.click()
};
$scope.attrs = angular.copy(depthConfig.defaults);
function onChange() {
$scope.$digest();
}
localSrcFileInput.addEventListener('change', function() {
let file = localSrcFileInput.files[0];
if (!file) {
return;
}
let reader = new FileReader();
reader.onload = (event) => {
$scope.$apply(() => $scope.attrs.src = event.target.result);
};
reader.readAsDataURL(file);
});
// monitor parameters
gui.add(srcSelector, 'src', demoImages).onChange(() => $scope.$apply(() => $scope.attrs.src = srcSelector.src));
gui.add(srcSelector, 'localSrc');
gui.add($scope.attrs, 'debug').onChange(onChange);
gui.add($scope.attrs, 'trace').onChange(onChange);
gui.add($scope.attrs, 'size').onChange(onChange);
gui.add($scope.attrs, 'enlarge', 0.5, 2).onChange(onChange);
gui.add($scope.attrs, 'animate').onChange(onChange);
gui.add($scope.attrs, 'animateDuration', 0, 10).onChange(onChange);
gui.add($scope.attrs, 'depthFocus', 0, 1).onChange(onChange);
gui.add($scope.attrs, 'depthFactor', 0, 5).onChange(onChange);
gui.add($scope.attrs, 'depthEqualize').onChange(onChange);
gui.add($scope.attrs, 'depthmapSrc').onChange(onChange);
gui.add($scope.attrs, 'depthPreview', 0, 1).onChange(onChange);
gui.add($scope.attrs, 'depthBlurSize', 0, 25).onChange(onChange);
gui.add($scope.attrs, 'mouseTracking').onChange(onChange);
gui.add($scope.attrs, 'gyroTracking').onChange(onChange);
gui.add($scope.attrs, 'gyroTrackingFactor', 0, 3).onChange(onChange);
gui.add($scope.attrs, 'faceTracking').onChange(onChange);
gui.add($scope.attrs, 'faceTrackingDebug').onChange(onChange);
gui.add($scope.attrs, 'faceTrackingFactor', 0, 5).onChange(onChange);
gui.add($scope.attrs, 'refocus').onChange(onChange);
gui.add($scope.attrs, 'focusPoint').listen().onChange(onChange);
gui.add($scope.attrs, 'focusPointChangeable').onChange(onChange);
gui.add($scope.attrs, 'focusBlur', 0, 1).listen().onChange(onChange);
gui.add($scope.attrs, 'focusBlurChangeable').onChange(onChange);
$scope.onRefocus = (refocus) => {
$scope.attrs.focusPoint = `${refocus.focusPoint.x}x${refocus.focusPoint.y}`;
$scope.attrs.focusBlur = refocus.focusBlur;
}
});
// bootstrap applicatiuon
angular.element(window.document).ready(() => angular.bootstrap(window.document, ['app']));
<file_sep>/dev/gulp/tasks/demo/build.js
/**
* Build
**/
'use strict';
var gulp = require('gulp');
var runSequence = require('run-sequence');
gulp.task('demo:build:development', function (callback) {
runSequence(
'demo:cleanup',
'demo:set-environment:development',
'demo:bundle-vendors',
callback
);
});
gulp.task('demo:build:production', function (callback) {
runSequence(
'demo:cleanup',
'demo:set-environment:production',
'demo:compile-scripts',
'demo:optimize-assets',
callback
);
});
<file_sep>/dev/gulp/tasks/demo/cleanup.js
/**
* Cleanup build files
**/
'use strict';
var gulp = require('gulp');
var del = require('del');
var config = require('../../config');
gulp.task('demo:cleanup', function () {
del.sync(config.demoBundleVendors.dest + '*');
});
<file_sep>/dev/gulp/tasks/demo/set-environment.js
/**
* Set environment (and write it to relevant files)
**/
'use strict';
var gulp = require('gulp');
var fs = require('fs');
var config = require('../../config');
function setEnvironment(environment) {
// set environment
fs.writeFileSync(config.paths.demo + '/environment', environment); // global
fs.writeFileSync(config.paths.demo + '/_environment.js', 'export const environment="' + environment + '";'); // js
}
// create tasks for each environment
gulp.task('demo:set-environment:production', function () {
setEnvironment('production');
});
gulp.task('demo:set-environment:development', function () {
setEnvironment('development');
});
| c0608a89cc9a55c5d94b9fb88111449778543630 | [
"JavaScript",
"Markdown"
] | 23 | JavaScript | DavisReef/angular-depth-viewer | 9f43bcd6c22236553c10bb6980a06f5ef50b710f | 7c7cafaceef6650da7b3d04465297b45443d2c21 | |
refs/heads/master | <file_sep>var data = [
{
country: 'Peru',
'code-postal': 51,
photo: 'peru.svg'
},
{
country: 'Chile',
'code-postal': 56,
photo: 'chile.svg'
},
{
country: 'Mexico',
'code-postal': 52,
photo: 'mexico.svg'
},
{
country: 'Colombia',
'code-postal': 57,
photo: 'colombia.svg'
}
];
<file_sep>### Reto: Lyft
***
### Objetivo:
* Desarrollar una aplicación web de la página de Lyft, para registro de usuario.
### Descripción:
* El siguiente proyecto consiste en desarrollar una web-app que replique el sitio de Lyft, en este reto se deberá cumplir los pasos necesarios para que tu usuario pueda registrarse.
### Flujo de la aplicación:
* Vista splash con duración de 2 a 5 segundos que redirecciona a tu vista de inicio.
La vista de inicio cuenta con dos botones, en esta ocasión seguiremos el flujo de SING UP.

* En la siguiente vista tenemos un formulario donde nuestro usuario puede escoger el país y debe ingresar su número de teléfono. El botón de NEXT debe estar deshabilitado hasta que se ingrese un número de 10 dígitos.

* Una vez ingresado el número de teléfono se habilita el botón y al dar click debe enviar una alerta con un código generado aleatoriamente (LAB-000) y redireccionar a la siguiente vista.

* En esta vista se debe ingresar el código dado anteriormente y una vez hecho esto se habilita el botón que redirecciona a nuestro usuario a la vista donde ingresa sus datos. (Puede tener la opción de enviar otro código.)

* Para ingresar sus datos necesitamos un formulario que le pida su nombre, apellido y correo electrónico. Deberá también tener un checkbox para que se acepten los términos y condiciones del servicio.

* Ya que se ha realizado lo anterior, sólo se deberá mostrar una vista al usuario que le indique que ha concluido con el registro exitosamente.

**NOTA:** Todas nuestras vistas deben de contar con una manera de regresar a la vista anterior
***
### Recursos Utilizados:
* HTML5.
* CSS.
* BOOTSTRAP.
* JAVASCRIPT.
* jQuery.
<file_sep>$(document).ready(function() {
var verifyFistName = false;
var verifyLastName = false;
var verifyEmail = false;
var verifyCheck = false;
function validateText(event) {
var patternText = /^[a-zA-Z_áéíóúñ_ÁÉÍÓÚÑ]*$/;
var centinel = false;
if (patternText.test(event.key)) {
centinel = true;
} else {
centinel = false;
}
return centinel;
}
function validateEmail(event) {
var patternEmail = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
patternEmail.test(event);
}
function verifyCamposText(text) {
var centinel = false;
if (text) {
centinel = true;
enabledButton();
} else {
centinel = false;
desabledButton();
}
return centinel;
}
function desabledButton(btn) {
$(btn).attr('disabled', '');
$(btn).removeClass('btn-enabled-register-data');
}
function enabledButton(btn) {
$(btn).removeAttr('disabled');
$(btn).addClass('btn-enabled-register-data');
}
function verifyData() {
if (verifyFistName && verifyLastName && verifyEmail && verifyCheck) {
enabledButton('.btn-next-register-data');
} else {
desabledButton('.btn-next-register-data');
}
}
// Validar firstName y lastName para ingresar solo texto
$('#firstName').on('keypress', validateText);
$('#lastName').on('keypress', validateText);
// Validar cada input ingresado
$('#firstName').on('input', function() {
verifyFistName = verifyCamposText($(this).val());
verifyData();
});
$('#lastName').on('input', function() {
verifyLastName = verifyCamposText($(this).val());
verifyData();
});
$('#email').on('input', function() {
patternEmail = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
var resulEmail = patternEmail.test($(this).val());
if (resulEmail) {
verifyEmail = true;
} else {
verifyEmail = false;
}
verifyData();
});
$('input[type="checkbox"]').on('click', function(event) {
if (event.target.checked) {
verifyCheck = true;
} else {
verifyCheck = false;
}
verifyData();
});
$('.btn-prev-verify-number').click(function() {
window.location.href = './verifynumber.html';
});
$('.btn-next-register-data').on('click', function() {
window.location.href = './registersuccess.html';
});
});
<file_sep>$(document).ready(function() {
// Animación del logo-lyft
$('img').animate({
marginBottom: '4in',
opacity: 0.4
}, 5000);
// Abrir la vista singup
setTimeout(function() {
window.location.href = './views/singup.html';
}, 5000);
});
<file_sep>$(document).ready(function() {
var code = (sessionStorage.code);
var digitOneCode = code.charAt(0);
var digitTwoCode = code.charAt(1);
var digitThreeCode = code.charAt(2);
var stateDigitOne = false;
var stateDigitTwo = false;
var stateDigitThree = false;
function clearInput() {
$('.digit-one').val('');
$('.digit-two').val('');
$('.tercerDig').val('');
$('.digit-one').focus();
desabledButton($('.btn-next-verify-number'));
}
function desabledButton(btn) {
$(btn).attr('disabled', '');
$(btn).removeClass('btn-enabled-verify');
}
function enabledButton(btn) {
$(btn).removeAttr('disabled');
$(btn).addClass('btn-enabled-verify');
}
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function verifyCode() {
if (stateDigitOne && stateDigitTwo && stateDigitThree) {
enabledButton($('.btn-next-verify-number'));
} else {
desabledButton($('.btn-next-verify-number'));
}
}
function validateOnlyNumber(event) {
var numberCodeASCII = event.keyCode;
var centinel = false;
if (numberCodeASCII >= 48 && numberCodeASCII <= 57) {
centinel = true;
}
return centinel;
}
// Inicializando
desabledButton($('.btn-next-verify-number'));
// Agregando el número
$('.help-block').text('Enter the code sent to +' + sessionStorage.number);
// Validar el código con cada valor ingresado en los input's
$('.digit-one').on('input', function() {
var valueDigit = $(this).val();
if (valueDigit === digitOneCode) {
stateDigitOne = true;
} else {
stateDigitOne = false;
}
verifyCode();
});
$('.digit-two').on('input', function() {
var valueDigit = $(this).val();
if (valueDigit === digitTwoCode) {
stateDigitTwo = true;
} else {
stateDigitTwo = false;
}
verifyCode();
});
$('.digit-three').on('input', function() {
var valueDigit = $(this).val();
if (valueDigit === digitThreeCode) {
stateDigitThree = true;
} else {
stateDigitThree = false;
}
verifyCode();
});
$('.digit-one').on('keypress', validateOnlyNumber);
$('.digit-two').on('keypress', validateOnlyNumber);
$('.digit-three').on('keypress', validateOnlyNumber);
$('.btn-prev-register-number').click(function() {
window.location.href = './registernumber.html';
});
// Generar otro código y validarlo
$('.btn-resend').on('click', function() {
clearInput();
code = getRandomArbitrary(100, 999);
alert('Su nuevo código es LAB-' + code);
sessionStorage.code = code;
digitOneCode = sessionStorage.code.charAt(0);
digitTwoCode = sessionStorage.code.charAt(1);
digitThreeCode = sessionStorage.code.charAt(2);
verifyCode();
});
$('.btn-next-verify-number').click(function() {
window.location.href = './registerdata.html';
});
});
<file_sep>$(document).ready(function() {
$('.btn-singup').click(function() {
window.location.href = './registernumber.html';
});
});
| 885cf655835414ca44839a6c2093687e83573a80 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | MelynaPernia/Lyft-webapp | f40f1aa3f76dfe78adb9d469eb08e548949c0a69 | a47e1410e26cea56000c92df1ade71a0e14e49ea | |
refs/heads/master | <file_sep>from pysc2.agents import base_agent
from pysc2.lib import actions
from pysc2.lib import features
from pysc2.env import run_loop
from pysc2.env import sc2_env
from pysc2.tests import utils
from absl import flags
from absl.testing import absltest
from pysc2.maps.lib import Map
import sys
# GAFT
from gaft import GAEngine
from gaft.components import GAIndividual, GAPopulation
from gaft.operators import RouletteWheelSelection, UniformCrossover, FlipBitMutation
# Analysis plugin base class.
from gaft.plugin_interfaces.analysis import OnTheFlyAnalysis
# Functions
_NOOP = actions.FUNCTIONS.no_op.id
_SELECT_POINT = actions.FUNCTIONS.select_point.id
_RALLY_UNITS_MINIMAP = actions.FUNCTIONS.Rally_Units_minimap.id
_SELECT_ARMY = actions.FUNCTIONS.select_army.id
_ATTACK_MINIMAP = actions.FUNCTIONS.Attack_minimap.id
_TRAIN_ZEALOT = actions.FUNCTIONS.Train_Zealot_quick.id
_TRAIN_STALKER = actions.FUNCTIONS.Train_Stalker_quick.id
_TRAIN_DARK = actions.FUNCTIONS.Train_DarkTemplar_quick.id
# Features
_PLAYER_RELATIVE = features.SCREEN_FEATURES.player_relative.index
_UNIT_TYPE = features.SCREEN_FEATURES.unit_type.index
# Unit IDs
_PROTOSS_GATEWAY = 62
# Parameters
_PLAYER_SELF = 1
_SUPPLY_USED = 3
_SUPPLY_MAX = 4
_NOT_QUEUED = [0]
_QUEUED = [1]
# player state id
_MINERALS_ID = 1
combination_queue = []
combination_queue.append((30, 0, 0))
class SimpleAgent(base_agent.BaseAgent):
build_queue = []
building_unit = None
building_selected = False
total_reward = 0
def setup(self, obs_spec, action_spec):
super().setup(obs_spec, action_spec)
def reset(self):
super().reset()
self.total_reward = 0
def step(self, obs):
super(SimpleAgent, self).step(obs)
self.total_reward += obs.reward
print(self.total_reward)
if obs.observation['player'][_MINERALS_ID] >= 2500:
for i in range(0, 10):
self.build_queue.append('zealot')
self.build_queue.append('stalker')
self.build_queue.append('dark')
if len(self.build_queue) != 0 and self.building_unit is None:
unit = self.build_queue.pop()
if unit == 'zealot' or unit == 'stalker' or unit == 'dark':
self.building_unit = unit
unit_type = obs.observation["screen"][_UNIT_TYPE]
unit_y, unit_x = (unit_type == _PROTOSS_GATEWAY).nonzero()
if unit_y.any():
target = [int(unit_x.mean()), int(unit_y.mean())]
self.building_selected = True
return actions.FunctionCall(_SELECT_POINT, [_NOT_QUEUED, target])
elif self.building_selected:
building_unit = self.building_unit
self.building_unit = None
self.building_selected = False
if building_unit == 'zealot' and _TRAIN_ZEALOT in obs.observation['available_actions']:
return actions.FunctionCall(_TRAIN_ZEALOT, [_QUEUED])
elif building_unit == 'stalker' and _TRAIN_STALKER in obs.observation['available_actions']:
return actions.FunctionCall(_TRAIN_STALKER, [_QUEUED])
elif building_unit == 'dark' and _TRAIN_DARK in obs.observation['available_actions']:
return actions.FunctionCall(_TRAIN_DARK, [_QUEUED])
return actions.FunctionCall(_NOOP, [])
FLAGS = flags.FLAGS
FLAGS(sys.argv)
class TestScripted(utils.TestCase):
def test(self):
train_map = Map()
train_map.directory = '/home/wangjian/StarCraftII/Maps'
train_map.filename = 'Train'
with sc2_env.SC2Env(
map_name=train_map,
visualize=True,
agent_race='T',
score_index=0,
game_steps_per_episode=1000) as env:
agent = SimpleAgent()
run_loop.run_loop([agent], env)
if __name__ == '__main__':
absltest.main()
| cd2b1f3151af87876cc919a1c1093dada2ad9838 | [
"Python"
] | 1 | Python | casiaSC2/ArmyCompound | 050e661a0a4dbbe36beecfe564f9b5a6e081e627 | 2e6e4d7a62677adcec1f4e1823d366892fcba6b0 | |
refs/heads/master | <repo_name>NarsingRao13/Web-JSP<file_sep>/JSPExample/src/User/UserDatabase.java
package User;
import java.sql.*;
public class UserDatabase {
static String DRI = "com.mysql.jdbc.Driver";
static String CONNECTION_URL = "jdbc:mysql://localhost:3306/narsing?characterEncoding=latin1";
static String USERNAME = "root";
static String PASSWORD = "<PASSWORD>";
static Connection con = null;
static {
try {
Class.forName(DRI);
con = DriverManager.getConnection(CONNECTION_URL, USERNAME, PASSWORD);
} catch (Exception e) {
System.out.println(e);
}
}
public static Connection getCon() {
return con;
}
public static int register(String n,String p)
{
int stat = 0;
try {
System.out.println(con);
String query = "insert into registration values(?,?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, n);
ps.setString(2, p);
stat = ps.executeUpdate();
} catch (Exception e) {
System.out.println(e.toString() + stat);
}
return stat;
}
public static boolean login(String n,String p) {
boolean stat = false;
try {
String query = "select * from registration where userName=? and userPassword=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, n);
ps.setString(2, p);
ResultSet rs = ps.executeQuery();
stat = rs.next();
} catch (Exception e) {
System.out.println(e.toString() + stat);
}
return stat;
}
public static int updatePassword(String n,String p){
int stat = 0;
try {
String query = "update registration set userPassword=? where userName=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, p);
ps.setString(2,n);
stat = ps.executeUpdate();
} catch (Exception e) {
System.out.println(e.toString() + stat);
}
return stat;
}
}
| 3fa2a129a04bf13ab113804397e40453e6c133b0 | [
"Java"
] | 1 | Java | NarsingRao13/Web-JSP | 67eb75383b8d5f998b1bf9e70b3ba7baf2de9992 | 3166cb81ce90db2f170fe115a9c2d74496d71169 | |
refs/heads/master | <file_sep>require 'spec_helper'
describe FlowdockRails::Configuration do
describe 'retive configuration' do
before(:all) do
sources = { test1: '123', test2: '456' }
@config = FlowdockRails::Configuration.new(sources)
end
it 'should return flow token by source' do
expect(@config.test1).to eq('123')
end
it 'should return nil if source does not exist' do
expect(@config.test3).to be_nil
end
it 'should be invalid for development env' do
expect(@config.valid_env?).to be false
end
it 'should invalid for development env' do
config = FlowdockRails::Configuration.new
config.environments = %w(test development)
expect(config.valid_env?).to be true
end
it 'should deactivate using env var' do
ClimateControl.modify FLOWDOCK_ENABLED: 'false' do
config = FlowdockRails::Configuration.new
expect(config.active?).to be false
end
end
it 'should be active by default' do
expect(@config.active?).to be true
end
end
end
<file_sep>$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'flowdock_rails'
require 'webmock/rspec'
require 'byebug'
require 'climate_control'
<file_sep>require 'flowdock_rails/version'
require 'active_support'
module FlowdockRails
extend ActiveSupport::Autoload
autoload :Configuration
autoload_under 'models' do
autoload :Flowdock
autoload :Message
end
module Utils
extend ActiveSupport::Autoload
autoload :Network
end
def self.configure
yield configuration
end
def self.configuration
@configuration ||= Configuration.new
end
end
<file_sep>require 'flowdock_rails'
FlowdockRails.configure do |config|
# You can configure more than one source.
# https://www.flowdock.com/api/sources
#
# config.sources = { main: 'token', bugs: 'token' }
# Configure env allowed to post messages
# default: production
#
# config.environments = %w(production)
end
<file_sep>module FlowdockRails
class Configuration
attr_accessor :sources, :environments
def initialize(sources = {})
@sources = sources
@environments = %w(production)
end
def valid_env?
@environments.include?(ENV['RAILS_ENV'] || 'development')
end
def active?
!(ENV['FLOWDOCK_ENABLED']&.downcase == 'false')
end
def method_missing(m)
return unless @sources[m]
@sources[m]
end
end
end
<file_sep>require 'spec_helper'
describe FlowdockRails::Message do
before(:all) do
attributes = { thread_id: '123', text: 'Ok', tags: %w(a b) }
@instance = FlowdockRails::Message.new(attributes)
end
it 'should initialize attributes' do
expect(@instance.thread_id).to eq('123')
expect(@instance.text).to eq('Ok')
expect(@instance.tags).to eq(%w(a b))
end
it 'should format tags' do
expected_tags = '#a,#b'
expect(@instance.format_tags).to eq(expected_tags)
end
it 'should check if message is from a thread' do
expect(@instance.thread?).to be true
end
it 'should have sent flag false' do
expect(@instance.sent?).to be false
end
it 'should have sent flag true' do
instance = FlowdockRails::Message.new
instance.sent
expect(instance.sent?).to be true
end
it 'should create bullet message' do
lines = ['**Title**', 'bullet 1', 'time: today']
instance = FlowdockRails::Message.new(lines: lines)
expected = "**Title**\nbullet 1\ntime: today"
expect(instance.text).to eq(expected)
end
end
<file_sep>require 'faraday_middleware'
module FlowdockRails
module Utils
module Network
def connection
@conn ||= Faraday.new(url: 'https://api.flowdock.com') do |conn|
conn.request :url_encoded
conn.response :logger
conn.response :json
conn.adapter Faraday.default_adapter
end
end
def post(url, params = {})
connection.post do |req|
req.url url
req.headers['Content-Type'] = 'application/json'
req.headers['X-flowdock-wait-for-message'] = 'true'
req.body = params.to_json
end
end
end
end
end
<file_sep>require 'spec_helper'
describe FlowdockRails do
it 'has a version number' do
expect(FlowdockRails::VERSION).not_to be nil
end
end
<file_sep># Flowdock Rails
Simple to post message to flowdock
## Installation
Add this line to your application's Gemfile:
```rb
gem 'flowdock_rails'
```
## Usage
* Add initializer to use yor config
```sh
rails g flowdock_rails:config
```
Configure
* sources
* environments
```rb
# config/initializers/flowdock_rails.rb
require 'flowdock_rails'
FlowdockRails.configure do |config|
# You can configure more than one source.
# https://www.flowdock.com/api/sources
#
config.sources = { source_name: 'flowdock_token' }
# Configure env allowed to post messages
# default: production
#
config.environments = %w(production development)
end
```
Sample
```ruby
# Message
attributes = { text: 'Ok', tags: %w(a b) }
message = FlowdockRails::Message.new(attributes)
flow = FlowdockRails::Flowdock.new(:source_name)
flow.post_message(message)
```
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/aaroalan/flowdock_rails. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
<file_sep>require 'spec_helper'
describe FlowdockRails::Flowdock do
before(:each) do
sources = { test1: '123' }
configuration = FlowdockRails::Configuration.new(sources)
configuration.environments = %w(development test)
allow(FlowdockRails).to receive(:configuration).and_return(configuration)
end
it 'is initialized with a source' do
instance = FlowdockRails::Flowdock.new(:test1)
expect(instance.source).to eq(:test1)
end
it 'should not be ready if source is invalid' do
instance = FlowdockRails::Flowdock.new(:test2)
expect(instance.ready?).to be false
end
it 'should be ready if source is valid' do
instance = FlowdockRails::Flowdock.new(:test1)
expect(instance.ready?).to be true
end
it 'should format params' do
attributes = { thread_id: '456', text: 'Ok', tags: %w(a b) }
message = FlowdockRails::Message.new(attributes)
instance = FlowdockRails::Flowdock.new(:test1)
params = instance.send(:format_params, message)
expected = { thread_id: '456', content: 'Ok', tags: '#a,#b',
flow_token: '123', event: 'message' }
expect(params).to eq(expected)
end
it 'should raise error if is not ready' do
instance = FlowdockRails::Flowdock.new(:ok)
expected = 'Instance is not ready'
expect { instance.post_message(1) }.to raise_error(expected)
end
it 'should update message' do
json_response = { thread_id: 'aaazzz' }
stub_request(:any, /.*flowdock.*/)
.to_return(body: json_response.to_json, status: 200)
attributes = { text: 'Ok', tags: %w(a b) }
message = FlowdockRails::Message.new(attributes)
instance = FlowdockRails::Flowdock.new(:test1)
new_message = instance.post_message(message)
expect(new_message.thread_id).to eq('aaazzz')
expect(new_message.sent?).to be true
end
it 'should return nil if environments is not allowed' do
sources = { test1: '123' }
configuration = FlowdockRails::Configuration.new(sources)
configuration.environments = %w(production)
allow(FlowdockRails).to receive(:configuration).and_return(configuration)
instance = FlowdockRails::Flowdock.new(:test1)
expect(instance.post_message(1)).to be_nil
end
it 'should not post message if flowdock is not enabled' do
ClimateControl.modify FLOWDOCK_ENABLED: 'false' do
instance = FlowdockRails::Flowdock.new(:test1)
expect(instance.post_message(nil)).to be_nil
end
end
end
<file_sep>module FlowdockRails
class Flowdock
include FlowdockRails::Utils::Network
attr_reader :source
def initialize(source)
@source = source
@flow_token = FlowdockRails.configuration.send(source)
end
def ready?
!@flow_token.nil?
end
def post_message(message)
return unless enabled?
raise 'Instance is not ready' unless ready?
params = format_params(message)
response = post('/messages', params)
message.thread_id = response.body['thread_id']
message.sent
message
end
def enabled?
FlowdockRails.configuration.valid_env? &&
FlowdockRails.configuration.active?
end
private
def format_params(message)
{
thread_id: message.thread_id, content: message.text.to_s,
tags: message.format_tags, flow_token: @flow_token, event: 'message'
}.reject { |_, v| v.nil? }
end
end
end
<file_sep>module FlowdockRails
# Create a message you can apply markdown to text multile line
# text
class Message
attr_accessor :thread_id, :text, :tags, :lines
def initialize(attributes = {})
@thread_id = attributes[:thread_id]
@text = attributes[:text]
@tags = attributes[:tags] || []
@lines = attributes[:lines] || []
@sent = false
end
def format_tags
@tags.map { |e| '#' + e.to_s }.join(',')
end
def thread?
!@thread_id.nil?
end
def sent?
@sent
end
def sent
@sent = true
end
def text
return lines.join("\n") if @lines.any?
@text
end
end
end
| 9d835c2c037707e85f0145259d4d14f68e5389f3 | [
"Markdown",
"Ruby"
] | 12 | Ruby | Health-eFilings/flowdock_rails | ce45ea9f42012a520e67b957b2bf6ac09cd97476 | bcf2a37997bcde5ee6c6155d79844e5c5449ec26 | |
refs/heads/master | <repo_name>christianjuth/calculatorjs<file_sep>/calculator.js
/*-------------------------------------------------------------------------------------
| o88b. .d8b. db .o88b. db db db .d8b. d888888b .d88b. d8888b. |
| d8P Y8 d8' `8b 88 d8P Y8 88 88 88 d8' `8b `~~88~~' .8P Y8. 88 `8D |
| 8P 88ooo88 88 8P 88 88 88 88ooo88 88 88 88 88oobY' |
| 8b 88~~~88 88 8b 88 88 88 88~~~88 88 88 88 88`8b |
| Y8b d8 88 88 88booo. Y8b d8 88b d88 88booo. 88 88 88 `8b d8' 88 `88. |
| `Y88P' YP YP Y88888P `Y88P' ~Y8888P' Y88888P YP YP YP `Y88P' 88 YD |
---------------------------------------------------------------------------------------
---------------------------FUNCTIONS------------------------------
| |
| ini(options) - initiate the calculator |
| numberClicked - called when number is clicked |
| screen - screen functions |
| set(value) - set screen value |
| get - get screen value |
| length - get screen length |
| clear - clear screen |
|
|
| m - memory functions |
| recall - get number in memory |
| clear - clear the current memory number |
|
|
|
|
|
------------------------------------------------------------------
----------------------------VARIABLES-----------------------------
| |
| calculator.max - max legnth calculator is allowed |
| calculator.selector.screen - selector for calculator screen |
|
|
|
|
------------------------------------------------------------------*/
var calculator = {
ini : function(options){
this.storage = window[options.storage];
if(options.max == undefined || options.max > 15) options.max = 15; //validate max screen size
if(typeof options.selector !== undefined){
$.each(options.selector, function(key, data){
calculator.selector[key] = $(data);
});
$.each(options.options, function(key, data){
calculator.options[key] = data;
});
this.options.maxLength = Math.min(Math.round(($("#input-container").width() / 18) - 1), options.max); //define number max legnth
this.lastSecond = "0";
this.first = "0";
this.second = "";
this.op = "";
if(calculator.storage.radDeg == "rad") this.rad();
else this.deg();
this.screen.clear();
if(calculator.storage.m != "0") $("#m-status").text("m");
}
else{
console.error("bad or missing screen selector");
}
},
selector : {},
options : {},
numberClicked : function(lastButtonClicked){
if(calculator.clear == true) calculator.screen.clear(); //calculator.screen.clears any previous values
var validate = calculator.screen.get() == "0" && lastButtonClicked == 0 && calculator.selector.screen.text().indexOf(".") == -1;
if(calculator.op== "" && validate != true){
if(calculator.first.replace(/-/g,"").replace(/\./g,"").length < calculator.options.maxLength){
if(this.first.indexOf(".") != -1) this.first = String(parseInt(this.first.split(".")[0]) + "." + this.first.split(".")[1] + lastButtonClicked);
else this.first = String(parseInt(this.first + '' + lastButtonClicked));
this.screen.set(this.first, false);
}
}
else if(validate != true){
if(calculator.second.replace(/-/g,"").replace(/\./g,"").length < calculator.options.maxLength){
if(this.second.length == 0) this.second = String(lastButtonClicked);
else if(this.second.indexOf(".") != -1) this.second = String(parseInt(this.second.split(".")[0]) + "." + this.second.split(".")[1] + lastButtonClicked);
else this.second = String(parseInt(this.second + '' + lastButtonClicked));
this.screen.set(this.second, false);
}
}
return lastButtonClicked;
},
screen : {
set : function(number, stripZeros) {
number = String(number);
if(number == "") number = "0";
if(number.indexOf(".") != -1 && number != "-0") number = String(parseInt(number.split(".")[0]) + "." + number.split(".")[1]);
else if(number != "-0") number = String(parseInt(number));
var valid = (number != "" && number != undefined && number != "undefined"); //validate number
if(number == "NaN"|| number.split(".")[0].replace(/-/,"").length > calculator.options.maxLength || !valid){
calculator.screen.clear();
calculator.selector.screen.text("ERROR");
console.error("ERROR");
return false;
}
if(number.replace(/-/,"").length <= calculator.options.maxLength && valid){
calculator.selector.screen.text(calculator.parse.commas(number));
}
else if(number.split(".")[0].replace(/-/,"").length < calculator.options.maxLength && valid){
calculator.selector.screen.text(calculator.parse.commas(math.round(parseFloat(number), calculator.options.maxLength - number.split(".")[0].length)));
}
return calculator.selector.screen.text().replace(/,/g,"");
},
get: function(){
return calculator.selector.screen.text().replace(/,/g,"");
},
length: function(){
return this.get().replace(/\./g,"").replace(/-/g,"").length;
},
clear: function(){
if(calculator.second != "") calculator.lastSecond = calculator.second;
calculator.clear= false;
calculator.first = "0";
calculator.second = "";
calculator.selector.screen.text("");
calculator.animate.op();
calculator.op= "";
overall = "";
calculator.screen.set(0);
return;
}
},
operator: function(operator) {
if(operator == undefined) operator = "";
if(calculator.op != ""){
calculator.calculate(false, false);
calculator.clear= false;
calculator.op = operator;
calculator.animate.op(operator);
}
else{
calculator.clear= false;
calculator.op = operator;
calculator.animate.op(operator);
}
return calculator.op;
},
calculate: function(clearVaulesAfter, fromOpp){
var finalNumber = new Array();
var output = "";
if(this.second != "0" && this.second != "") this.lastSecond = this.second;
if(calculator.second != ""){
if(calculator.op== "plus"){
overall = parseFloat(calculator.first) + parseFloat(calculator.second); //addition
}
else if(calculator.op== "subtract"){
overall = parseFloat(calculator.first) - parseFloat(calculator.second); //subtraction
}
else if(calculator.op== "multiply"){
overall = parseFloat(calculator.first) * parseFloat(calculator.second); //multiplication
}
else if(calculator.op== "divide"){
overall = parseFloat(calculator.first) / parseFloat(calculator.second); //divition
}
else if(calculator.op== "mod"){
overall = parseFloat(calculator.first) % parseFloat(calculator.second); //mod
}
else if(calculator.op== "pow-of-y"){
overall = Math.pow(parseFloat(calculator.first), parseFloat(calculator.second));
}
else if(calculator.op== "square-root-y"){
overall = this.math.nthroot(parseFloat(calculator.first), parseFloat(calculator.second));
}
calculator.selector.screen.text("");
setTimeout(calculator.screen.set, 100, overall);
this.animate.op();
calculator.first = String(overall);
calculator.second = "";
overall = "";
if(clearVaulesAfter == true){
this.clear = true;
}
}
else if(calculator.lastSecond != "" && calculator.op!= "" && fromOpp != false){
if(calculator.op== "plus"){
overall = parseFloat(calculator.first) + parseFloat(calculator.lastSecond); //addition
}
else if(calculator.op== "subtract"){
overall = parseFloat(calculator.first) - parseFloat(calculator.lastSecond); //subtraction
}
else if(calculator.op== "multiply"){
overall = parseFloat(calculator.first) * parseFloat(calculator.lastSecond); //multiplication
}
else if(calculator.op== "divide"){
overall = parseFloat(calculator.first) / parseFloat(calculator.lastSecond); //divition
}
else if(calculator.op== "mod"){
overall = parseFloat(calculator.first) % parseFloat(calculator.lastSecond); //mod
}
else if(calculator.op== "pow-of-y"){
overall = Math.pow(parseFloat(calculator.first), parseFloat(calculator.lastSecond));
}
else if(calculator.op== "square-root-y"){
overall = this.math.nthroot(parseFloat(calculator.first), parseFloat(calculator.lastSecond));
}
calculator.selector.screen.text("");
setTimeout(calculator.screen.set, 100, overall);
this.animate.op();
calculator.first = String(overall);
calculator.second = "";
overall = "";
if(clearVaulesAfter == true){
this.clear = true;
}
}
return;
},
mathFunctions:{
//static functions
pi : function(){
return String(Math.PI);
},
e : function() {
return Math.E;
},
//basic functions
pow : function(x,y) {
return math.pow(x, y);
},
nthroot : function(x, n) {
try {
var negate = n % 2 == 1 && x < 0;
if(negate)
x = -x;
var possible = Math.pow(x, 1 / n);
n = Math.pow(possible, n);
if(Math.abs(x - n) < 1 && (x > 0 == n > 0))
return negate ? -possible : possible;
} catch(e){}
},
in : function(x) {
return Math.log(x);
},
log : function(x, y) {
return math.log(parseFloat(x),y);
},
//trig functions
sin : function(x) {
return math.sin(math.unit(x, calculator.storage.radDeg));
},
cos : function(x) {
return math.cos(math.unit(x, calculator.storage.radDeg));
},
tan : function(x) {
return math.tan(math.unit(x, calculator.storage.radDeg));
},
sinh : function(x) {
return math.sinh(math.unit(x, calculator.storage.radDeg));
},
cosh : function(x) {
return math.cosh(math.unit(x, calculator.storage.radDeg));
},
tanh : function(x) {
return math.tanh(math.unit(x, calculator.storage.radDeg));
},
asin : function(x) {
if(calculator.storage.radDeg == "rad") return math.asin(x);
else return math.asin(x) * (180 / Math.PI);
},
acos : function(x) {
if(calculator.storage.radDeg == "rad") return math.acos(x);
else return math.acos(x) * (180 / Math.PI);
},
atan : function(x) {
if(calculator.storage.radDeg == "rad") return math.atan(x);
else return math.atan(x) * (180 / Math.PI);
},
asinh : function(x) {
return Math.asinh(x);
},
acosh : function(x) {
return Math.acosh(x);
},
atanh : function(x) {
return Math.atanh(x);
},
},
math : function(fun, x, y){
var result = calculator["mathFunctions"][fun](parseFloat(x),parseFloat(y));
if(result !== false){
if(calculator.op == "") return calculator.first = calculator.screen.set(result);
else return calculator.second = calculator.screen.set(result);
}
else calculator.screen.get();
},
event : {
addDecimal : function() {
if(calculator.clear == true) calculator.screen.clear();
if(calculator.screen.get().indexOf(".") == -1){
if(calculator.op== ""){
calculator.first = calculator.first + ".";
calculator.screen.set(calculator.first);
}
else{
if(calculator.second == "." || calculator.second == "") calculator.second = "0.";
calculator.second = calculator.second + ".";
calculator.screen.set(calculator.second);
}
}
return;
},
posNeg : function() {
if(calculator.op== ""){
if(calculator.first.length == 0) calculator.first = "-0";
else if(calculator.first.indexOf("-") == -1) calculator.first = "-" + calculator.first;
else calculator.first = calculator.first.replace(/-/g,"");
calculator.screen.set(calculator.first);
}
if(calculator.op!= ""){
if(calculator.second.length == 0) calculator.second = "-0";
else if(calculator.second.indexOf("-") == -1) calculator.second = "-" + calculator.second;
else calculator.second = calculator.second.replace(/-/g,"");
calculator.screen.set(calculator.second);
}
return;
},
radDeg : function() {
if(calculator.selector.radDeg.text() == "rad"){
calculator.storage.radDeg = calculator.deg();
}
else if(calculator.selector.radDeg.text() == "deg"){
calculator.storage.radDeg = calculator.rad();
}
return;
},
percentage : function(){
if(calculator.op == ""){
calculator.first = String(1 * (calculator.first * 0.01));
calculator.clear = true;
return calculator.screen.set(calculator.first);
}
else{
calculator.second = String(calculator.first * (calculator.second * 0.01));
calculator.clear = true;
return calculator.screen.set(calculator.second);
}
}
},
//memory functions
m : {
recall : function() {
if(parseFloat(calculator.storage.m) != 0){
if(calculator.op== ""){
calculator.first = calculator.storage.m;
calculator.screen.set(calculator.first);
}
else{
calculator.second = calculator.storage.m;
calculator.screen.set(calculator.second);
}
}
return calculator.storage.m;
},
clear : function(){
calculator.storage.m = 0;
$("#m-status").text("");
return calculator.storage.m;
},
minus : function() {
calculator.storage.m = parseFloat(calculator.storage.m) - parseFloat(calculator.screen.get());
if(calculator.storage.m != "0") $("#m-status").text("m");
return calculator.storage.m;
},
plus : function() {
calculator.storage.m = parseFloat(calculator.storage.m) + parseFloat(calculator.screen.get());
if(calculator.storage.m != "0") $("#m-status").text("m");
return calculator.storage.m;
}
},
parse : {
commas : function(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
},
animate : {
op : function(selector){
$(".opp").css({"-webkit-transform" : "scale(1)"}); //reset scale
if(calculator.op != undefined){ //bounce shrink animation
$("#" + selector).css({"-webkit-transform" : "scale(0.90)"});
setTimeout( function() {
$("#" + selector).css({"-webkit-transform" : "scale(0.95)"});
}, 100);
}
else{
$("#" + selector).css({"-webkit-transform" : "scale(1)"});
}
return;
}
},
clipboard : {
copy : function(text) {
var copyFrom = $('<input/>');
copyFrom.val(text);
$('body').append(copyFrom);
copyFrom.select();
document.execCommand('copy');
copyFrom.remove();
return text;
},
paste : function() {
var pasteTo = $('<input/>');
$('body').append(pasteTo);
pasteTo.select();
document.execCommand('paste');
var number = parseFloat(pasteTo.val());
if(!isNaN(parseFloat(number)) && String(number) != "0"){
calculator.screen.set(number);
if(calculator.op== "") calculator.first = number;
else calculator.second = number;
}
else{
calculator.selector.screen.text("ERROR");
calculator.screen.clear();
}
pasteTo.remove();
return number;
}
},
rad : function() {
this.selector.radDeg.text("rad");
if(typeof this.selector.radDegInvert !== "undefined") this.selector.radDegInvert.text("deg");
return "rad";
},
deg : function() {
this.selector.radDeg.text("deg");
if(typeof this.selector.radDegInvert !== "undefined") this.selector.radDegInvert.text("rad");
return "deg";
}
}
<file_sep>/README.md
<h1>Example JS Code</h1>
```
$(document).ready(function() {
calculator.ini({
storage : "localStorage", // storage object
selector : {
screen : "#input", // screen selector
radDeg : "#rad-deg", // rad/deg selector
radDegInvert : "#rad-deg-invert" // inverted rad/deg selector
}
max : 15 // max number allowed
});
});
```
<h1>Functions & VARIABLES</h1>
```
/*-------------------------FUNCTIONS------------------------------
| |
| ini(options) - initiate the calculator |
| numberClicked - called when number is clicked |
| screen - screen functions |
| set(value) - set screen value |
| get - get screen value |
| length - get screen length |
| clear - clear screen |
|
|
| m - memory functions |
| recall - get number in memory |
| clear - clear the current memory number |
|
|
|
|
|
------------------------------------------------------------------
----------------------------VARIABLES-----------------------------
| |
| calculator.max - max legnth calculator is allowed |
| calculator.selector.screen - selector for calculator screen |
|
|
|
|
------------------------------------------------------------------*/
```
| 83155523785c7a0194e0244fb0517e589fd844b5 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | christianjuth/calculatorjs | c4eec07892291f8c19806a10eda7209c28a26987 | 8635e13bf4511f83393e34bd2508fdef351cec5e | |
refs/heads/master | <file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Application\UseCase\Command;
class ResetPassword
{
public function __construct(string $passwordResetToken, string $newEmail)
{
}
}
<file_sep><?php declare(strict_types=1);
namespace App\Kernel\Identity\Application\UseCase\CommandHandler;
use App\Kernel\Identity\Application\UseCase\Command\ResetPassword;
interface ResetPasswordHandler
{
public function handle(ResetPassword $command): void;
}
<file_sep><?php declare(strict_types=1);
namespace App\Kernel\MoneyTransferring\Application\UseCase\CommandHandler;
use App\Kernel\MoneyTransferring\Application\UseCase\Command\BookTransaction;
final class BookTransactionConcreteHandler implements BookTransactionHandler
{
public function handle(BookTransaction $command): int
{
// Orchestrate domain to do stuff.
// E.g. retrieve entity from repository, call method on entity & etc.
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Domain\Model\User\Entity;
class User
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Application\UseCase\Command;
class InitiatePasswordReset
{
public function __construct(string $email)
{
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\UserInterface\Web\Controller;
use App\Kernel\Identity\Application\UseCase\Command\RegisterUser;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class RegisterUserController
{
private $commandBus;
public function __construct($commandBus)
{
$this->commandBus = $commandBus;
}
public function __invoke(Request $request): Response
{
$this->commandBus->handle(
new RegisterUser(
$request->request->get('email'),
$request->request->get('password')
),
);
}
}
<file_sep><?php declare(strict_types=1);
namespace App\Kernel\MoneyTransferring\Domain\Model\Transaction\Entity;
class Transaction
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Infrastructure\Persistance\InMemory;
use App\Kernel\Identity\Domain\Model\Entity\User;
use App\Kernel\Identity\Domain\Model\UserRepository;
use App\Kernel\Identity\Domain\Model\ValueObject\UserId;
/**
* User repository In-memory implementation used for test environments
*/
final class UserInMemoryRepository implements UserRepository
{
public function add(User $user): void
{
}
public function get(UserId $userId): User
{
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Application\UseCase\CommandHandler;
use App\Kernel\Identity\Application\UseCase\Command\InitiatePasswordReset;
class InitiatePasswordResetConcreteHandler
{
public function handle(InitiatePasswordReset $command): void
{
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Domain\Model\User;
interface PasswordHasher
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\SharedKernel\Domain\Service;
interface EventDispatcher
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Domain\Model\User\Event;
use App\Kernel\Identity\Domain\Model\User\ValueObject\UserId;
use App\SharedKernel\Domain\ValueObject\Email;
final class UserRegistered
{
public function __construct(UserId $userId, Email $email)
{
}
}
<file_sep><?php declare(strict_types=1);
namespace App\Kernel\Identity\Application\UseCase\CommandHandler;
use App\Kernel\Identity\Application\UseCase\Command\RegisterUser;
interface RegisterUserHandler
{
public function handle(RegisterUser $command): void;
}
<file_sep><?php
declare(strict_types=1);
namespace App\SharedKernel\Application\Mailer;
interface Mailer
{
}
<file_sep><?php declare(strict_types=1);
namespace App\Kernel\MoneyTransferring\Domain\Model\Transaction\ValueObject;
class TransactionId
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Domain\Model\User\ValueObject;
final class UserId
{
}
<file_sep><?php declare(strict_types=1);
namespace App\Kernel\MoneyTransferring\Application\UseCase\Command;
class BookTransaction
{
}
<file_sep><?php declare(strict_types=1);
namespace App\Kernel\MoneyTransferring\Domain\Model\Transaction;
interface TransactionRepository
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\SharedKernel\Domain\ValueObject;
final class Money
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Infrastructure\Persistance\Doctrine\ORM;
use App\Kernel\Identity\Domain\Model\Entity\User;
use App\Kernel\Identity\Domain\Model\UserRepository;
use App\Kernel\Identity\Domain\Model\ValueObject\UserId;
final class UserDoctrineOrmRepository implements UserRepository
{
public function add(User $user): void
{
}
public function get(UserId $userId): User
{
}
}
<file_sep><?php declare(strict_types=1);
namespace App\Kernel\MoneyTransferring\Application\UseCase\CommandHandler;
use App\Kernel\MoneyTransferring\Application\UseCase\Command\BookTransaction;
interface BookTransactionHandler
{
public function handle(BookTransaction $command): int;
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Application\UseCase\CommandHandler;
use App\Kernel\Identity\Application\UseCase\Command\ResetPassword;
class ResetPasswordConcreteHandler
{
public function handle(ResetPassword $command): void
{
}
}
<file_sep><?php declare(strict_types=1);
namespace App\Kernel\Identity\Domain\Model\User;
final class BcryptPasswordHasher implements PasswordHasher
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Domain\Model\User\Exception;
use RuntimeException;
class UserNotFound extends RuntimeException
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\SharedKernel\Domain\ValueObject;
final class Email
{
}
<file_sep><?php declare(strict_types=1);
namespace App\Kernel\MoneyTransferring\Domain\Model\Transaction\Exception;
use RuntimeException;
/**
* Throw when trying to book transaction with negative amount
*/
class NegativeAmountError extends RuntimeException
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\SharedKernel\Application\Mailer;
final class NullMailer implements Mailer
{
}
<file_sep><?php declare(strict_types=1);
namespace App\Kernel\MoneyTransferring\Domain\Model\Transaction\Event;
class TransactionBooked
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\SharedKernel\Infrastructure\Mailer\SwiftMailer;
use App\SharedKernel\Application\Mailer\Mailer;
final class SwiftMailer implements Mailer
{
public function __construct(/* Swift_Mailer $mailer */)
{
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\UserInterface\Console\Command;
use App\Kernel\Identity\Application\UseCase\Command\RegisterUser;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
final class RegisterUserCommand extends Command
{
private $commandBus;
public function __construct($commandBus)
{
parent::__construct();
$this->commandBus = $commandBus;
}
public function execute(InputInterface $input, OutputInterface $output)
{
$this->commandBus->handle(
new RegisterUser(
$input->getArgument('email'),
$input->getArgument('password')
),
);
}
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Application\UseCase\Command;
class RegisterUser
{
public function __construct(string $email, string $password)
{
}
}
<file_sep># Skeleton
Skeleton acts as an application architecture example that uses:
- DDD
- Hexagonal / Layers
- CQRS
## About the structure
* ***Kernel (aka `Core`)*** - code that represents whole application. `Kernel` consists of bounded contexts that solve single problem (e.g. `Identity`).
* ***SharedKernel*** - code that is shared across all bounded contexts.
### Bounded contexts in depth
Each module consists of 4 layers:
- Domain
- Infrastructure
- Application
- UserInterface
#### Domain layer
Domain layer is responsible for defining and maintaining business rules of the application. This layer contains classes like entities, repositories (usually interfaces), domain events, value objects and domain services.
#### Infrastructure layer
This layer consist most vendor specific implementations of the interfaces defined by Domain and Application layers (e.g. `UserRepository` interface is implemented using Doctrine ORM or `Mailer` interface is implemented using SwiftMailer library).
#### Application layer
Application layer acts as a middle-man between infrastructure and domain. For example, controller accepts HTTP request (Infrastructure layer), converts that request into use-case (e.g. `RegisterUser`) command and dispatches it for command handler (Application layer) to take care of it by orchestrating entities, domain services (Domain layer).
This layer can also consist code that is needed by the application itself, but does not necessarily fall into Domain (e.g. `Mailer`, `Logger`).
#### UserInterface layer
UserInterface layer is the part through which user (be it actual user or 3rd party system) enters the application, for example Web API or Console commands.
Services in this layer are mostly implemented using frameworks & libraries, similar to Infrastructure layer, that's why it commonly referred as primary infrastructure layer.
## Reference
Example code in this repository _tries_ to follow architecture defined in this [schema](https://herbertograca.files.wordpress.com/2018/11/070-explicit-architecture-svg.png?w=1100).
## Code example
See `/src` directory of this repository for minimal example.<file_sep><?php declare(strict_types=1);
namespace App\Kernel\MoneyTransferring\Infrastructure\Persistance\Doctrine\ORM;
use App\Kernel\MoneyTransferring\Domain\Model\Transaction\TransactionRepository;
final class TransactionDoctrineOrmRepository implements TransactionRepository
{
}
<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Domain\Model\User\ValueObject;
final class Password
{
}
<file_sep># Identity bounded context
Each bounded context contains brief description of what it does.
It could also describe abbreviations and/or terms used in the bounded context or provide high level documentation.<file_sep><?php
declare(strict_types=1);
namespace App\Kernel\Identity\Domain\Model\User;
use App\Kernel\Identity\Domain\Model\User\Entity\User;
use App\Kernel\Identity\Domain\Model\User\ValueObject\UserId;
interface UserRepository
{
public function add(User $user): void;
public function get(UserId $userId): User;
}
| 4e88789ca526834a9f8be82c2c5d4ec7e739ed1b | [
"Markdown",
"PHP"
] | 36 | PHP | sarjon/skeleton | 958d226edd70f6cb280d953608508b0152ecd85f | 3baddb263c8096542e9f5bd7318c7da6ec817db1 | |
refs/heads/master | <file_sep># Kafka for Go 101
<file_sep>package main
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/Shopify/sarama"
)
func main() {
producer, err := sarama.NewAsyncProducer([]string{"localhost:9092"}, nil)
if err != nil {
log.Fatal(err)
}
defer func() {
if err := producer.Close(); err != nil {
log.Fatal(err)
}
}()
consumer, err := sarama.NewConsumer([]string{"localhost:9092"}, nil)
if err != nil {
log.Fatal(err)
}
defer func() {
if err := consumer.Close(); err != nil {
log.Fatal(err)
}
}()
ch := make(chan string)
go produceTextMessage(producer)
go consumeTextMessage(consumer, ch)
go handle(ch)
sig := make(chan os.Signal)
signal.Notify(sig, os.Interrupt, os.Kill, syscall.SIGTERM)
<-sig
}
// produceTextMessage generate text message and produce message on kafka.
func produceTextMessage(producer sarama.AsyncProducer) {
for i := 0; ; i++ {
producer.Input() <- &sarama.ProducerMessage{
Topic: "wingyplus",
Key: nil,
Value: sarama.StringEncoder(fmt.Sprintf("From producer %d", i)),
}
time.Sleep(1 * time.Second)
}
}
// consumeTextMessage consume text message from kafka producer and send text message to ch.
func consumeTextMessage(producer sarama.Consumer, ch chan<- string) {
pc, err := producer.ConsumePartition("wingyplus", 0, sarama.OffsetNewest)
if err != nil {
// NOTE: this is bad practice. don't do this in production!!!
panic(err)
}
for msg := range pc.Messages() {
ch <- string(msg.Value)
}
}
// handle receive text message from ch and print to standard output.
func handle(ch <-chan string) {
for s := range ch {
fmt.Println(s)
}
}
<file_sep>#!/bin/sh
cd kafka_2.11-2.0.0
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic wingyplus
| b3e514b644222c16da2a660650606b42ec77fa75 | [
"Markdown",
"Go",
"Shell"
] | 3 | Markdown | wingyplus/kafka101 | 5af7b73e19b2aa79c83f4654905dd6e6e1c290b7 | 3bd91abd2bfef9f2ff823c39fa802249e616928f | |
refs/heads/master | <repo_name>limkokholefork/Screenshot-without-root<file_sep>/src/pl/polidea/asl/ScreenshotService.java
package pl.polidea.asl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.security.InvalidParameterException;
import java.util.UUID;
import android.app.Service;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Matrix;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
public class ScreenshotService extends Service {
/*
* Action name for intent used to bind to service.
*/
public static final String BIND = "pl.polidea.asl.ScreenshotService.BIND";
/*
* Name of the native process.
*/
private static final String NATIVE_PROCESS_NAME = "asl-native";
/*
* Port number used to communicate with native process.
*/
private static final int PORT = 42380;
/*
* Timeout allowed in communication with native process.
*/
private static final int TIMEOUT = 1000;
/*
* Directory where screenshots are being saved.
*/
private static final String SCREENSHOT_FOLDER = "/sdcard/screens/";
/*
* An implementation of interface used by clients to take screenshots.
*/
private final IScreenshotProvider.Stub mBinder = new IScreenshotProvider.Stub() {
public String takeScreenshot() throws RemoteException {
try {
return ScreenshotService.this.takeScreenshot();
} catch (Exception e) {
return null;
}
}
public boolean isAvailable() throws RemoteException {
return isNativeRunning();
}
};
@Override
public void onCreate() {
Log.i("service", "Service created.");
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/*
* Checks whether the internal native application is running,
*/
private boolean isNativeRunning() {
try {
Socket sock = new Socket();
sock.connect(new InetSocketAddress("localhost", PORT), 10); // short
// timeout
} catch (Exception e) {
return false;
}
return true;
// ActivityManager am =
// (ActivityManager)getSystemService(Service.ACTIVITY_SERVICE);
// List<ActivityManager.RunningAppProcessInfo> ps =
// am.getRunningAppProcesses();
//
// if (am != null) {
// for (ActivityManager.RunningAppProcessInfo rapi : ps) {
// if (rapi.processName.contains(NATIVE_PROCESS_NAME))
// // native application found
// return true;
// }
//
// }
// return false;
}
/*
* Internal class describing a screenshot.
*/
static final class Screenshot {
public Buffer pixels;
public int width;
public int height;
public int bpp;
public boolean isValid() {
if (pixels == null || pixels.capacity() == 0 || pixels.limit() == 0)
return false;
if (width <= 0 || height <= 0)
return false;
return true;
}
}
/*
* Determines whether the phone's screen is rotated.
*/
private int getScreenRotation() {
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
Display disp = wm.getDefaultDisplay();
// check whether we operate under Android 2.2 or later
try {
Class<?> displayClass = disp.getClass();
Method getRotation = displayClass.getMethod("getRotation");
int rot = ((Integer) getRotation.invoke(disp)).intValue();
switch (rot) {
case Surface.ROTATION_0:
return 0;
case Surface.ROTATION_90:
return 90;
case Surface.ROTATION_180:
return 180;
case Surface.ROTATION_270:
return 270;
default:
return 0;
}
} catch (NoSuchMethodException e) {
// no getRotation() method -- fall back to getOrientation()
int orientation = disp.getOrientation();
// Sometimes you may get undefined orientation Value is 0
// simple logic solves the problem compare the screen
// X,Y Co-ordinates and determine the Orientation in such cases
if (orientation == Configuration.ORIENTATION_UNDEFINED) {
Configuration config = getResources().getConfiguration();
orientation = config.orientation;
if (orientation == Configuration.ORIENTATION_UNDEFINED) {
// if height and widht of screen are equal then
// it is square orientation
if (disp.getWidth() == disp.getHeight()) {
orientation = Configuration.ORIENTATION_SQUARE;
} else { // if widht is less than height than it is portrait
if (disp.getWidth() < disp.getHeight()) {
orientation = Configuration.ORIENTATION_PORTRAIT;
} else { // if it is not any of the above it will
// defineitly be landscape
orientation = Configuration.ORIENTATION_LANDSCAPE;
}
}
}
}
return orientation == 1 ? 0 : 90; // 1 for portrait, 2 for landscape
} catch (Exception e) {
return 0; // bad, I know ;P
}
}
/*
* Communicates with the native service and retrieves a screenshot from it
* as a 2D array of bytes.
*/
private Screenshot retreiveRawScreenshot() throws Exception {
try {
// connect to native application
// We use SocketChannel,because is more convenience and fast
SocketChannel socket = SocketChannel.open(new InetSocketAddress(
"localhost", PORT));
socket.configureBlocking(false);
// Send Commd to take screenshot
ByteBuffer cmdBuffer = ByteBuffer.wrap("SCREEN".getBytes("ASCII"));
socket.write(cmdBuffer);
// build a buffer to save the info of screenshot
// 3 parts,width height cpp
byte[] info = new byte[3 + 3 + 2 + 2];// 3 bytes width + 1 byte
// space + 3 bytes heigh + 1
// byte space + 2 bytes bpp
ByteBuffer infoBuffer = ByteBuffer.wrap(info);
// we must make sure all the data have been read
while (infoBuffer.position() != infoBuffer.limit())
socket.read(infoBuffer);
// we must read one more byte,because after this byte,we will read
// the image byte
socket.read(ByteBuffer.wrap(new byte[1]));
// set the position to zero that we can read it.
infoBuffer.position(0);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < (3 + 3 + 2 + 2); i++) {
sb.append((char) infoBuffer.get());
}
String[] screenData = sb.toString().split(" ");
if (screenData.length >= 3) {
Screenshot ss = new Screenshot();
ss.width = Integer.parseInt(screenData[0]);
ss.height = Integer.parseInt(screenData[1]);
ss.bpp = Integer.parseInt(screenData[2]);
// retreive the screenshot
// (this method - via ByteBuffer - seems to be the fastest)
ByteBuffer bytes = ByteBuffer.allocate(ss.width * ss.height
* ss.bpp / 8);
while (bytes.position() != bytes.limit()) {
// in the cycle,we must make sure all the image data have
// been read,maybe sometime the socket will delay a bit time
// and return some invalid bytes.
socket.read(bytes); // reading all at once for speed
}
bytes.position(0); // reset position to the beginning of
// ByteBuffer
ss.pixels = bytes;
return ss;
}
} catch (Exception e) {
throw new Exception(e);
} finally {
}
return null;
}
/*
* Saves given array of bytes into image file in the PNG format.
*/
private void writeImageFile(Screenshot ss, String file) {
if (ss == null || !ss.isValid())
throw new IllegalArgumentException();
if (file == null || file.length() == 0)
throw new IllegalArgumentException();
// resolve screenshot's BPP to actual bitmap pixel format
Bitmap.Config pf;
switch (ss.bpp) {
case 16:
pf = Config.RGB_565;
break;
case 32:
pf = Config.ARGB_8888;
break;
default:
pf = Config.ARGB_8888;
break;
}
// create appropriate bitmap and fill it wit data
Bitmap bmp = Bitmap.createBitmap(ss.width, ss.height, pf);
bmp.copyPixelsFromBuffer(ss.pixels);
// handle the screen rotation
int rot = getScreenRotation();
if (rot != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(-rot);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
bmp.getHeight(), matrix, true);
}
// save it in PNG format
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new InvalidParameterException();
}
bmp.compress(CompressFormat.PNG, 100, fos);
}
/*
* Takes screenshot and saves to a file.
*/
private String takeScreenshot() throws IOException {
// make sure the path to save screens exists
File screensPath = new File(SCREENSHOT_FOLDER);
if (!screensPath.exists())
screensPath.mkdir();
// construct screenshot file name
StringBuilder sb = new StringBuilder();
sb.append(SCREENSHOT_FOLDER);
sb.append(Integer.toHexString(UUID.randomUUID().hashCode())); // hash
// code
// of
// UUID
// should
// be
// quite
// random
// yet
// short
sb.append(".png");
String file = sb.toString();
// fetch the screen and save it
Screenshot ss = null;
try {
ss = retreiveRawScreenshot();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
writeImageFile(ss, file);
return file;
}
}
| fe240caf1057c88986e7a5a94e71e84c33594e4e | [
"Java"
] | 1 | Java | limkokholefork/Screenshot-without-root | bb7add9997be042a292f6bd6d57fed32e71abc7d | 6c6f228ab04e6a52cc71cf686ada825c3ba85ee5 | |
refs/heads/master | <repo_name>NicolaiNisbeth/CDIO3<file_sep>/src/test/java/Utilities/TextReaderTest.java
package Utilities;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import static org.junit.Assert.*;
public class TextReaderTest {
@Test
public void textReader() throws IOException {
int[] fieldsPrice = {2,1,1,0,1,1,0,2,2,0,2,2,0,3,3,0,3,3,0,4,4,0,5,5};
String file = ".\\src\\Resources\\SquarePrice";
HashMap fieldPricesFile = TextReader.textReader(file);
assertEquals(fieldsPrice.length, fieldPricesFile.size());
for (int price = 0; price < fieldsPrice.length; price++) {
assertEquals(fieldsPrice[price], fieldPricesFile.get(price));
}
}
}<file_sep>/src/main/java/Model/Fields/Start.java
package Model.Fields;
import Controller.PlayerController;
public class Start extends Field {
public Start(int positionOnBoard) {
super(positionOnBoard);
}
@Override
public int getPositionOnBoard() {
return super.getPositionOnBoard();
}
@Override
public int landedOnStreet(PlayerController playerC, int ref) {
return -1;
}
}
<file_sep>/src/main/java/Model/Fields/Parking.java
package Model.Fields;
import Controller.PlayerController;
public class Parking extends Field {
public Parking(int positionOnBoard) {
super(positionOnBoard);
}
@Override
public int getPositionOnBoard() {
return super.getPositionOnBoard();
}
@Override
public int landedOnStreet(PlayerController playerC, int ref) {
return -1;
}
}
<file_sep>/src/test/java/Model/Fields/ChanceTest.java
package Model.Fields;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class ChanceTest {
Chance chance;
@Before
public void initialize() {
chance = new Chance(3);
}
@Test
public void instantiateCards() {
int[] chanceD = chance.getChanceCards();
// Makes sure there are no duplicates in deck
for (int i = 0; i < chanceD.length; i++) {
int j = (i + 1) % chanceD.length;
assertTrue(chanceD[i] != chanceD[j]);
}
}
@Test
public void mixCards() {
for (int i = 0; i < chance.getChanceCards().length; i++) {
int firstCard = chance.getChanceCards()[0];
int secondCard = chance.getChanceCards()[1];
chance.mixCards();
int cardOnTop = chance.getChanceCards()[0];
int cardInBottom = chance.getChanceCards()[20-1];
assertEquals(firstCard, cardInBottom);
assertEquals(secondCard, cardOnTop);
}
}
}<file_sep>/src/main/java/View/CarColor.java
package View;
import java.awt.*;
public class CarColor {
private Color[] colorArray = new Color[4];
private int numOfColors = 4;
private int colorsChosen;
private String[] colorStringArray;
private String[] colorStringArray2;
private String colorChosenString;
public CarColor() {
instaColorArray();
instaColorStringArray();
}
public Color colorChosen(String colorChoiceString) {
Color returnColor;
colorChosenString = colorChoiceString;
if (colorChoiceString.equalsIgnoreCase("grey")) {
returnColor = colorArray[0];
} else if (colorChoiceString.equalsIgnoreCase("green")) {
returnColor = colorArray[1];
} else if (colorChoiceString.equalsIgnoreCase("blue")) {
returnColor = colorArray[2];
} else {
//If choice is magenta
returnColor = colorArray[3];
}
colorsChosen++;
updateColorStringArray(colorChoiceString);
return returnColor;
}
public void updateColorStringArray(String lastChosen) {
colorStringArray2 = new String[colorStringArray.length];
for (int i = 0; i < colorStringArray.length; i++) {
colorStringArray2[i] = colorStringArray[i];
}
colorStringArray = new String[(numOfColors - colorsChosen)];
for (int i = 0; i < colorStringArray.length; i++) {
if (!colorStringArray2[i].equalsIgnoreCase(lastChosen)) {
colorStringArray[i] = colorStringArray2[i];
}
if (colorStringArray2[i].equalsIgnoreCase(lastChosen)) {
colorStringArray[i] = colorStringArray2[i + 1];
for (int j = i; j < colorStringArray.length; j++) {
colorStringArray[j] = colorStringArray2[j + 1];
}
break;
}
}
}
public String colorsToChooseFrom() {
String returnString = "";
for (int i = 0; i < colorStringArray.length; i++) {
returnString = returnString + colorStringArray[i] + " ";
}
return returnString;
}
private void instaColorArray() {
colorArray[0] = Color.darkGray;
colorArray[1] = Color.GREEN;
colorArray[2] = Color.BLUE;
colorArray[3] = Color.MAGENTA;
}
public void instaColorStringArray() {
colorStringArray = new String[4];
colorStringArray[0] = "Grey";
colorStringArray[1] = "Green";
colorStringArray[2] = "Blue";
colorStringArray[3] = "Magenta";
}
public String[] getColorStringArray() {
return colorStringArray;
}
public String getColorChosenString() {
return colorChosenString;
}
}<file_sep>/src/test/java/Model/AccountTest.java
package Model;
import Model.Fields.Street;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class AccountTest {
Account account2Players;
@Before
public void initialize(){
account2Players = new Account(2);
}
@Test
public void startAccount() {
assertEquals(20, account2Players.getBalance());
Account account3Players = new Account(3);
assertEquals(18, account3Players.getBalance());
Account account4Players = new Account(4);
assertEquals(16, account4Players.getBalance());
}
@Test
public void addProperty() {
Street burgerJoint = new Street(1, 1, false);
Street boardwalk = new Street(23, 5, false);
assertEquals(0, account2Players.getSumOfStreets());
account2Players.addStreet(burgerJoint);
account2Players.addStreet(boardwalk);
assertEquals(6, account2Players.getSumOfStreets());
}
@Test
public void updateBalance() {
assertEquals(20, account2Players.getBalance());
account2Players.updateBalance(2);
assertEquals(22, account2Players.getBalance());
}
}<file_sep>/src/main/java/Model/Fields/GoToPrison.java
package Model.Fields;
import Controller.PlayerController;
public class GoToPrison extends Field {
public GoToPrison(int positionOnBoard) {
super(positionOnBoard);
}
@Override
public int getPositionOnBoard() {
return super.getPositionOnBoard();
}
@Override
public int landedOnStreet(PlayerController playerC, int ref) {
playerC.setPosition(6,ref);
playerC.setInJail(ref, true);
return -18;
}
}
<file_sep>/src/main/java/Model/Player.java
package Model;
import Model.Fields.Street;
import java.util.ArrayList;
public class Player {
private String name = "";
private int oldPosition;
private int curPosition = 0;
private int objectNumber;
private Account account;
private boolean broke = false;
private boolean inJail = false;
private boolean jailCard = false;
private boolean specialCard = false;
public Player(int objectNumber, int numOfPlayers){
this.objectNumber = objectNumber;
this.account = new Account(numOfPlayers);
}
public int getSumOfProperties(){
return account.getSumOfStreets();
}
public void setSumOfProperties(int sumOfProperties){
account.setSumOfStreets(sumOfProperties);
}
public void addStreet(Street street){
account.addStreet(street);
}
public void setBalance(int newBalance){ account.setBalance(newBalance);}
public int getBalance() {
return account.getBalance();
}
public void updateBalance(int amount) {
this.account.updateBalance(amount);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCurPosition() {
return curPosition;
}
public void setCurPosition(int curPosition) {
this.curPosition = curPosition;
}
public int getObjectNumber() {
return objectNumber;
}
public boolean getBroke(){
return broke;
}
public void setBroke(boolean broke) {
this.broke = broke;
}
public int getOldPosition() {
return oldPosition;
}
public void setOldPosition(int oldPosition) {
this.oldPosition = oldPosition;
}
public boolean getJailCard(){
return jailCard;
}
public void setJailCard(Boolean bool){
jailCard = bool;
}
public boolean getInJail(){
return inJail;
}
public void setInJail(Boolean bool){
inJail = bool;
}
public boolean getSpecialCard() {return specialCard;}
public void setSpecialCard(Boolean bool) {specialCard = bool; }
public ArrayList getAllPlayersStreets(){
return this.account.getPlayersStreets();
}
public boolean ownsStreetAheadOrBehind(int lfStreetPos){
return account.ownsStreetAheadOrBehind(lfStreetPos);
}
}
<file_sep>/src/main/java/View/GuiHandler.java
package View;
import Controller.GameBoard;
import Controller.PlayerController;
import Utilities.TextReader;
import Model.Die;
import Model.Fields.Field;
import gui_codebehind.GUI_Center;
import gui_fields.*;
import gui_main.GUI;
import java.awt.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import static gui_fields.GUI_Car.Type.*;
public class GuiHandler {
private MessageHandler message;
private GUI gui;
private GUI_Field[] fields;
private GUI_Player[] gui_Players;
private GUI_Car[] gui_cars;
private HashMap streetNames;
private HashMap streetDesc;
private HashMap chanceDesc;
//Construktor
public GuiHandler() throws IOException {
message = new MessageHandler();
fields = new GUI_Field[24];
streetNames = TextReader.textReader(".\\src\\Resources\\SquareNames");
streetDesc = TextReader.textReader(".\\src\\Resources\\SquareDescription");
chanceDesc = TextReader.textReader(".\\src\\Resources\\ChanceCard");
for (int i = 0; i < fields.length; i++) {
fields[i] = new GUI_Street((String) streetNames.get(i), "", (String) streetDesc.get(i), "", Color.YELLOW, Color.BLACK);
}
setSpecificFields();
gui = new GUI(fields);
}
public void changeBorderColor(PlayerController playerC, int i) {
GUI_Field field;
GUI_Street street;
Color carColor = getGuiPlayer(i).getCar().getPrimaryColor();
field = gui.getFields()[playerC.getPosition(i)];
street = (GUI_Street) field;
street.setBorder(carColor);
}
public int choseNumOfPlayers() {
//int players = gui.getUserInteger("How many players is participating in the game?");
int numOfPlayers;
while (true) {
String input = gui.getUserString(message.gameMessage("33"));
if (input.matches("^[2-4]$") && input.length() > 0) {
numOfPlayers = Integer.parseInt(input);
break;
} else {
gui.showMessage(message.gameMessage("34"));
}
}
return numOfPlayers;
}
public void setGameUpGui(PlayerController playerC) {
int numOfPlayers = playerC.getNumOfPlayers();
gui_cars = new GUI_Car[numOfPlayers];
gui_Players = new GUI_Player[numOfPlayers];
CarColor carColor = new CarColor();
for (int i = 0; i < playerC.getNumOfPlayers(); i++) {
enterNamePlayer(playerC, i);
GUI_Car car = chosePlayerCar(carColor, playerC, i);
addGuiPlayer(playerC, i, car);
setSpecificCar(playerC, i);
}
}
public GUI_Player getGuiPlayer(int i) {
GUI_Player guiPlayer = gui_Players[i];
return guiPlayer;
}
public void addGuiPlayer(PlayerController playerC, int ref, GUI_Car car) {
gui_Players[ref] = new GUI_Player(playerC.getName(ref), playerC.getBalance(ref), car);
gui.addPlayer(gui_Players[ref]);
}
public Color chooseCarColor(CarColor carColorObj, PlayerController playerC, int ref) {
String[] chooseColorStrings = carColorObj.colorsToChooseFrom().split(" ");
String carColorS;
for (int i = 0; i < chooseColorStrings.length; i++) {
}
if (chooseColorStrings.length == 4) {
carColorS = gui.getUserSelection("Choose color", chooseColorStrings[0], chooseColorStrings[1], chooseColorStrings[2], chooseColorStrings[3]);
} else if (chooseColorStrings.length == 3) {
carColorS = gui.getUserSelection("Choose color", chooseColorStrings[0], chooseColorStrings[1], chooseColorStrings[2]);
} else if (chooseColorStrings.length == 2) {
carColorS = gui.getUserSelection("Choose color", chooseColorStrings[0], chooseColorStrings[1]);
} else {
gui.showMessage(playerC.getName(ref) + "'s color is " + chooseColorStrings[0]);
carColorS = chooseColorStrings[0];
}
Color carColorChoice = carColorObj.colorChosen(carColorS);
return carColorChoice;
}
public GUI_Car chosePlayerCar(CarColor carColorObj, PlayerController playerC, int ref) {
String carChoice = gui.getUserSelection("Choose car", "Car", "Ufo", "Tractor", "Racecar");
GUI_Car car;
Color carColor = chooseCarColor(carColorObj, playerC, ref);
if (carChoice.equalsIgnoreCase("ufo")) {
car = new GUI_Car(carColor, Color.blue, UFO, GUI_Car.Pattern.FILL);
gui_cars[ref] = car;
} else if (carChoice.equalsIgnoreCase("car")) {
car = new GUI_Car(carColor, Color.blue, CAR, GUI_Car.Pattern.FILL);
gui_cars[ref] = car;
} else if (carChoice.equalsIgnoreCase("tractor")) {
car = new GUI_Car(carColor, Color.blue, TRACTOR, GUI_Car.Pattern.FILL);
gui_cars[ref] = car;
} else {
car = new GUI_Car(carColor, Color.blue, RACECAR, GUI_Car.Pattern.FILL);
gui_cars[ref] = car;
}
return car;
}
public void enterNamePlayer(PlayerController playerC, int ref) {
while (true) {
String input = gui.getUserString(message.turnMessage(playerC, ref, "26") + " " + (ref + 1));
if (input.length() > 0) {
playerC.setName(input, ref);
break;
} else {
gui.showMessage(message.turnMessage(playerC, ref, "27") + " " + (ref + 1));
}
}
}
public void setDiceGui(Die die) {
gui.setDie(die.getFaceValue());
}
public void playerTurnGui(PlayerController player, int ref) {
gui.showMessage(message.playerTurn(player, ref));
}
public void showScore(PlayerController player, int i) {
gui.showMessage(message.playerEndTurn(player, i));
}
public void removeSpecificCar(PlayerController playerC, int ref) {
fields[(playerC.getOldPosition(ref))].removeAllCars();
}
public void setSpecificCar(PlayerController playerC, int ref) {
fields[(playerC.getPosition(ref))].setCar(getGuiPlayer(ref), true);
}
public void removeAllCarsCurPos(PlayerController playerC) {
for (int i = 0; i < gui_Players.length; i++) {
fields[(playerC.getPosition(i))].removeAllCars();
}
}
public void setAllCarsCurPos(PlayerController playerC) {
for (int i = 0; i < gui_Players.length; i++) {
fields[(playerC.getPosition(i))].setCar(getGuiPlayer(i), true);
}
}
public void diceUpdateGui(PlayerController player, Die die) {
setDiceGui(die);
}
public void updateGuiPlayerBalance(PlayerController playerC) {
for (int i = 0; i < gui_Players.length; i++) {
gui_Players[i].setBalance(playerC.getBalance(i));
}
}
public void messageSquareGui(PlayerController playerC, int ref, Field field, boolean passedStart) {
if (passedStart) {
gui.showMessage(message.messageField(playerC, ref));
}
gui.showMessage(message.messageField(playerC, ref, field, playerC.getPosition(ref)));
}
public void messageSquareGuiSpecial(PlayerController playerC, int ref, boolean passedStart) {
if (passedStart) {
gui.showMessage(message.messageField(playerC, ref));
}
gui.showMessage(message.messageSpecial(playerC, ref, playerC.getPosition(ref)));
}
public void impactSquareGui(int squareInt, PlayerController playerC, int i, GameBoard board) {
if (squareInt < 0) {
updateGuiPlayerBalance(playerC);
//Player bought a street
if (squareInt == -2) {
changeBorderColor(playerC, i);
} else if (squareInt == -3) {
}
//Go to jail
else if (squareInt == -18) {
removeSpecificCar(playerC, i);
fields[6].setCar(getGuiPlayer(i), true);
}
} else {
//If the square int is 0 or more, then it's because the player picked up a chance card
guiChanceSwitch(squareInt, playerC, i, board);
updateGuiPlayerBalance(playerC);
}
}
public void resetGuiChance() {
GUI_Center.getInstance().displayDefault();
}
public void guiSpecialChance(PlayerController playerC, int ref) {
removeSpecificCar(playerC, ref);
setAllCarsCurPos(playerC);
setSpecificCar(playerC, ref);
}
public void guiChanceSwitch(int squareInt, PlayerController playerC, int ref, GameBoard board) {
switch (squareInt + 1) {
case 1: //Special card for player 1
gui.displayChanceCard((String) chanceDesc.get(0));
if (playerC.getPlayerObjectNumber(ref) != 0) {
board.getSquare(squareInt).landedOnStreet(playerC, ref);
}
break;
case 2: //Move to start
gui.displayChanceCard((String) chanceDesc.get(1));
removeSpecificCar(playerC, ref);
setAllCarsCurPos(playerC);
setSpecificCar(playerC, ref);
break;
case 3: //Advance between 1 to 5 fields.
gui.displayChanceCard((String) chanceDesc.get(2));
int choiceInt = Integer.parseInt(gui.getUserButtonPressed("", "1", "2", "3", "4", "5"));
playerC.setPosition(((playerC.getPosition(ref) + choiceInt) % 24), ref);
removeSpecificCar(playerC, ref);
setAllCarsCurPos(playerC);
setSpecificCar(playerC, ref);
break;
case 4: // Move to an orange field. If it's NOT owned, the street is yours. Else pay rent to the owner.
gui.displayChanceCard((String) chanceDesc.get(3));
String case4 = gui.getUserButtonPressed("", "Skate Park", "Swimming Pool");
movePlayerToColor(playerC, ref, case4);
break;
case 5: //Advance 1 field or take an extra chance card.
gui.displayChanceCard((String) chanceDesc.get(4));
String choiceS = (gui.getUserButtonPressed("", "Advance 1 field", "Try your luck"));
if (choiceS.equalsIgnoreCase("Advance 1 field")) {
playerC.setPosition(playerC.getPosition(ref) + 1, ref);
removeSpecificCar(playerC, ref);
setAllCarsCurPos(playerC);
setSpecificCar(playerC, ref);
} else {
//pick a new chance card
gui.showMessage("You chose to pick another card!" + "\n" + "Good luck!");
board.getSquare(3).landedOnStreet(playerC, ref);
removeSpecificCar(playerC, ref);
setAllCarsCurPos(playerC);
setSpecificCar(playerC, ref);
}
break;
case 6: //Special card for player 2
gui.displayChanceCard((String) chanceDesc.get(5));
if (playerC.getPlayerObjectNumber(ref) != 0) {
board.getSquare(squareInt).landedOnStreet(playerC, ref);
}
break;
case 7: //You have eaten too much candy. Pay the bank $2.
gui.displayChanceCard((String) chanceDesc.get(6));
updateGuiPlayerBalance(playerC);
break;
case 8: //Move to an orange or green field. If it's NOT owned, the street is yours. Else pay rent to the owner.
gui.displayChanceCard((String) chanceDesc.get(7));
String case8 = gui.getUserButtonPressed("", "Skate Park", "Swimming Pool", "Bowling Alley", "Zoo");
movePlayerToColor(playerC, ref, case8);
break;
case 9: //Move to a light blue field. If it's NOT owned, the street is yours. Else pay rent to the owner.
gui.displayChanceCard((String) chanceDesc.get(8));
String case9 = gui.getUserButtonPressed("", "Candy Store", "Ice Cream Parlor");
movePlayerToColor(playerC, ref, case9);
break;
case 10: //You will be released from prison without being charged. Save this card for later use.
gui.displayChanceCard((String) chanceDesc.get(9));
break;
case 11: //Move to the sea front.
gui.displayChanceCard((String) chanceDesc.get(10));
removeSpecificCar(playerC, ref);
setAllCarsCurPos(playerC);
setSpecificCar(playerC, ref);
break;
case 12: //Special card for player 3
gui.displayChanceCard((String) chanceDesc.get(11));
if (playerC.getPlayerObjectNumber(ref) != 0) {
board.getSquare(squareInt).landedOnStreet(playerC, ref);
}
break;
case 13: //Special card for player 4
gui.displayChanceCard((String) chanceDesc.get(12));
if (playerC.getPlayerObjectNumber(ref) != 0) {
board.getSquare(squareInt).landedOnStreet(playerC, ref);
}
break;
case 14: //Today is your birthday. Every player gives you $1. HAPPY BIRTHDAY!
gui.displayChanceCard((String) chanceDesc.get(13));
updateGuiPlayerBalance(playerC);
break;
case 15: //Move to a pink or dark blue field. If it's NOT owned, the street is yours. Else pay rent to the owner.
gui.displayChanceCard((String) chanceDesc.get(14));
String case15 = gui.getUserButtonPressed("", "Museum", "Library", "Park Place", "Boardwalk");
movePlayerToColor(playerC, ref, case15);
break;
case 16: //You have finished all your homework. Receive $2 on behalf of the bank.
gui.displayChanceCard((String) chanceDesc.get(15));
updateGuiPlayerBalance(playerC);
break;
case 17: //Move to a red field. If it's NOT owned, the street is yours. Else pay rent to the owner.
gui.displayChanceCard((String) chanceDesc.get(16));
String case17 = gui.getUserButtonPressed("", "Video Game Arcade", "Cinema");
movePlayerToColor(playerC, ref, case17);
break;
case 18: //Move to the skater park to execute the perfect grind! If it's NOT owned, the street is yours. Else pay rent to the owner.
gui.displayChanceCard((String) chanceDesc.get(17));
removeSpecificCar(playerC, ref);
setAllCarsCurPos(playerC);
setSpecificCar(playerC, ref);
break;
case 19: //Move to a light blue or red field. If it's NOT owned, the street is yours. Else pay rent to the owner.
gui.displayChanceCard((String) chanceDesc.get(18));
String case19 = gui.getUserButtonPressed("", "Candy Store", "Ice Cream Parlor", "Video Game Arcade", "Cinema");
movePlayerToColor(playerC, ref, case19);
break;
case 20: //Move to a brown or yellow field. If it's NOT owned, the street is yours. Else pay rent to the owner.
gui.displayChanceCard((String) chanceDesc.get(19));
String case20 = gui.getUserButtonPressed("", "Burger Joint", "Pizza House", "Toy Store", "Pet Store");
movePlayerToColor(playerC, ref, case20);
break;
}
}
public void movePlayerToColor(PlayerController playerC, int ref, String choice) {
String[] streets = {"Start", "Burger Joint", "Pizza House", "Chance", "Candy Store", "Ice Cream Parlor",
"Jail", "Museum", "Library", "Chance", "Skate Park", "Swimming Pool", "Free Parking",
"Video Game Arcade", "Cinema", "Chance", "Toy Store", "Pet Store", "Go To Jail",
"Bowling Alley", "Zoo", "Chance", "Park Place", "Boardwalk"};
int position = Arrays.asList(streets).indexOf(choice);
playerC.setPosition(position, ref);
removeSpecificCar(playerC, ref);
setAllCarsCurPos(playerC);
setSpecificCar(playerC, ref);
}
public void playerWonGui(PlayerController playerC, int i) {
gui.showMessage(message.playerWon(playerC, i));
}
public void gotBrokeGui(PlayerController playerC, int i) {
gui.showMessage(message.gotBroke(playerC, i));
}
public void startGameGui() {
gui.showMessage(message.startGame1());
gui.showMessage(message.startGame2());
gui.showMessage(message.startGame3());
gui.showMessage(message.startGame4());
}
public void specialMessage1(PlayerController playerC, int ref) {
gui.showMessage(message.turnMessage(playerC, ref, "32"));
}
public void specialMessage2(PlayerController playerC, int ref) {
gui.showMessage(message.turnMessage(playerC, ref, "31"));
}
public void specialMessage3(PlayerController playerC, int ref) {
gui.showMessage(message.turnMessage(playerC, ref, "30"));
}
public void specialMessage4(PlayerController playerC, int ref) {
gui.showMessage(message.turnMessage(playerC, ref, "40"));
}
public void specialMessage5(PlayerController playerC, int ref) {
gui.showMessage(message.turnMessage(playerC, ref, "45"));
}
public void setSpecificFields() {
fields[0] = new GUI_Start("Start", fields[0].getSubText(), fields[0].getDescription(), Color.RED, Color.BLACK);
fields[3] = new GUI_Chance("?", fields[3].getSubText(), fields[3].getDescription(), new Color(204, 204, 204), Color.BLACK);
fields[9] = new GUI_Chance("?", fields[3].getSubText(), fields[3].getDescription(), new Color(204, 204, 204), Color.BLACK);
fields[15] = new GUI_Chance("?", fields[3].getSubText(), fields[3].getDescription(), new Color(204, 204, 204), Color.BLACK);
fields[21] = new GUI_Chance("?", fields[3].getSubText(), fields[3].getDescription(), new Color(204, 204, 204), Color.BLACK);
fields[6] = new GUI_Jail("default", fields[6].getTitle(), fields[6].getSubText(), fields[6].getDescription(), new Color(125, 125, 125), Color.BLACK);
fields[18] = new GUI_Jail("default", fields[18].getTitle(), fields[18].getSubText(), fields[18].getDescription(), new Color(125, 125, 125), Color.BLACK);
fields[1].setBackGroundColor(new Color(63, 73, 30));
fields[2].setBackGroundColor(new Color(63, 73, 30));
fields[4].setBackGroundColor(new Color(0, 143, 204));
fields[5].setBackGroundColor(new Color(0, 143, 204));
fields[7].setBackGroundColor(new Color(198, 94, 204));
fields[8].setBackGroundColor(new Color(198, 94, 204));
fields[10].setBackGroundColor(new Color(249, 166, 2));
fields[11].setBackGroundColor(new Color(249, 166, 2));
fields[13].setBackGroundColor(new Color(255, 0, 70));
fields[14].setBackGroundColor(new Color(255, 0, 70));
fields[16].setBackGroundColor(new Color(255, 253, 34));
fields[17].setBackGroundColor(new Color(255, 253, 34));
fields[19].setBackGroundColor(new Color(112, 255, 64));
fields[20].setBackGroundColor(new Color(112, 255, 64));
fields[22].setBackGroundColor(new Color(16, 54, 100));
fields[23].setBackGroundColor(new Color(16, 54, 100));
}
}<file_sep>/src/test/java/Controller/PlayerControllerTest.java
package Controller;
import Controller.PlayerController;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Before;
public class PlayerControllerTest {
private PlayerController playerC;
@Before
public void initialize() {
playerC = new PlayerController(4);
for (int i = 0; i < 4; i++) {
assertEquals(0, playerC.getPosition(i));
assertEquals(16, playerC.getBalance(i));
}
}
@Test
public void calcNewPosition() {
// Gameboard indexes from 0 to 23 and has 24 fields.
playerC.setPosition(23, 0);
playerC.calcNewPosition(1, 0);
assertEquals(0, playerC.getPosition(0));
playerC.setPosition(0, 1);
playerC.calcNewPosition(5, 1);
assertEquals(5, playerC.getPosition(1));
}
@Test
public void broke() {
assertFalse(playerC.getModelBroke(0));
assertEquals(16, playerC.getBalance(0));
playerC.updatePlayerBalance(0, -17);
playerC.broke(0);
assertTrue(playerC.getModelBroke(0));
}
@Test
public void playerWithHighestBalance() {
playerC.updatePlayerBalance(0, 4);
playerC.updatePlayerBalance(1, 2);
playerC.updatePlayerBalance(2, 10);
playerC.updatePlayerBalance(3, 10);
playerC.setSumOfStreets(2, 15);
playerC.setSumOfStreets(3, 10);
assertEquals(2, playerC.playerWithHighestBalance());
playerC.setSumOfStreets(3, 20);
assertEquals(3, playerC.playerWithHighestBalance());
}
@Test
public void wantOutOfJail() {
assertEquals(16, playerC.getBalance(0));
assertFalse(playerC.inJail(0));
playerC.setInJail(0, true);
assertTrue(playerC.inJail(0));
playerC.wantOutOfJail(0);
assertEquals(15, playerC.getBalance(0));
assertFalse(playerC.inJail(0));
}
}
<file_sep>/src/test/java/Model/Fields/FieldTest.java
package Model.Fields;
import Controller.PlayerController;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class FieldTest {
PlayerController playerC;
Chance chance;
@Before
public void initialize(){
playerC = new PlayerController(4);
chance = new Chance(3);
for (int i = 0; i < 4; i++) {
assertEquals(0, playerC.getPosition(i));
assertEquals(16, playerC.getBalance(i));
}
}
@Test
public void landedOnStreet() {
// ChanceCard 0
playerC.setPosition(3, 0);
assertFalse(playerC.getSpecialCard(0));
int[] chance0 = {1};
chance.setChanceCards(chance0);
chance.landedOnStreet(playerC, 0);
assertTrue(playerC.getSpecialCard(0));
// ChanceCard 1
playerC.setPosition(3, 0);
int[] chance1 = {2};
chance.setChanceCards(chance1);
chance.landedOnStreet(playerC, 0);
assertEquals(0, playerC.getPosition(0));
// ChanceCard 5
playerC.setPosition(3, 0);
assertFalse(playerC.getSpecialCard(1));
int[] chance5 = {6};
chance.setChanceCards(chance5);
chance.landedOnStreet(playerC, 0);
assertTrue(playerC.getSpecialCard(1));
// ChanceCard 6
playerC.setPosition(3, 0);
int[] chance7 = {7};
chance.setChanceCards(chance7);
chance.landedOnStreet(playerC, 0);
assertEquals(14, playerC.getBalance(0));
// ChanceCard 9
playerC.setPosition(3, 0);
assertFalse(playerC.getJailCard(0));
int[] chance9 = {10};
chance.setChanceCards(chance9);
chance.landedOnStreet(playerC, 0);
assertTrue(playerC.getJailCard(0));
// ChanceCard 10
playerC.setPosition(3, 0);
int[] chance10 = {11};
chance.setChanceCards(chance10);
chance.landedOnStreet(playerC, 0);
assertEquals(23, playerC.getPosition(0));
// ChanceCard 11
playerC.setPosition(3, 0);
assertFalse(playerC.getSpecialCard(2));
int[] chance11 = {12};
chance.setChanceCards(chance11);
chance.landedOnStreet(playerC, 0);
assertTrue(playerC.getSpecialCard(2));
// ChanceCard 12
playerC.setPosition(3, 0);
assertFalse(playerC.getSpecialCard(3));
int[] chance12 = {13};
chance.setChanceCards(chance12);
chance.landedOnStreet(playerC, 0);
assertTrue(playerC.getSpecialCard(3));
// ChanceCard 13
playerC.setPosition(3, 0);
playerC.setBalance(16, 0);
int[] chance13 = {14};
chance.setChanceCards(chance13);
chance.landedOnStreet(playerC, 0);
assertEquals(19, playerC.getBalance(0));
// ChanceCard 15
playerC.setPosition(3, 0);
playerC.setBalance(16, 0);
int[] chance15 = {16};
chance.setChanceCards(chance15);
chance.landedOnStreet(playerC, 0);
assertEquals(18, playerC.getBalance(0));
// ChanceCard 17
playerC.setPosition(3, 0);
int[] chance17 = {18};
chance.setChanceCards(chance17);
chance.landedOnStreet(playerC, 0);
assertEquals(10, playerC.getPosition(0));
}
} | 3d8202b85d17289d8bb8abf909b93d0c20a7437f | [
"Java"
] | 11 | Java | NicolaiNisbeth/CDIO3 | 40fc30d743d2d10c7f8cae213545debb1eeb3384 | a8d326e1b0c290b5b40c3fbcf993fe72f2852cda | |
refs/heads/master | <repo_name>wndeld777/TeamProject_HONJAL<file_sep>/Honjal/src/main/java/com/honjal/honjal/dao/ext/ContentDao.java
package com.honjal.honjal.dao.ext;
import com.honjal.honjal.dao.GenericDao;
import com.honjal.honjal.model.ContentVO;
public interface ContentDao extends GenericDao<ContentVO, Integer>{
}
<file_sep>/Honjal/src/main/webapp/static/js/nav.js
document.addEventListener("DOMContentLoaded", () => {
document.querySelector("#menu").addEventListener("click", (e) => {
let text = e.target.textContent;
let url = `${rootPath}`;
if (text === "공지사항") {
url += "/notice/board";
} else if (text === "정보게시판") {
url += "/info";
} else if (text === "생활 TIP") {
url += "/tip";
} else if (text === "랜선집들이") {
url += "/interior";
} else if (text === "혼잘TALK") {
url += "/talk";
} else if (text === "리뷰게시판") {
url += "/review";
} else if (text === "자취 Q&A") {
url += "/qna";
}
location.href = url;
});
});
<file_sep>/Honjal/src/main/java/com/honjal/honjal/service/impl/ContentServiceImplV1.java
package com.honjal.honjal.service.impl;
import java.util.List;
import com.honjal.honjal.model.ContentListDTO;
import com.honjal.honjal.model.ContentVO;
import com.honjal.honjal.service.ContentService;
public class ContentServiceImplV1 implements ContentService {
@Override
public int insert(ContentVO contentVO) throws Exception {
// TODO Auto-generated method stub
return 0;
}
@Override
public int update(ContentVO contentVO) throws Exception {
// TODO Auto-generated method stub
return 0;
}
@Override
public int delete(int content_num) throws Exception {
// TODO Auto-generated method stub
return 0;
}
@Override
public List<ContentListDTO> listContent() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ContentListDTO> menuContent(String board_code) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ContentListDTO> searchTitleContent(String title) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ContentListDTO> searchTextContent(String text) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ContentListDTO> searchNameContent(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ContentListDTO> MyContent(Integer member_num) {
// TODO Auto-generated method stub
return null;
}
}
| e0402d6dae91484102e9e29e424a5a0b7b5b4bc3 | [
"JavaScript",
"Java"
] | 3 | Java | wndeld777/TeamProject_HONJAL | 0055f3e82c899a79c599d003f8940362c3937cc1 | 809c3d3409b17b973c4a7c0b9e605b9a0fd87c87 | |
refs/heads/main | <repo_name>apriliandi246/vscode-css-sort<file_sep>/src/extension.ts
import * as vscode from "vscode";
import { parse, generate } from "css-tree";
export function activate(context: vscode.ExtensionContext) {
const cssMinSort = vscode.commands.registerCommand("css-sort.min", () => {
const editor = vscode.window.activeTextEditor;
const cssCodeSelected = editor?.document.getText(editor.selection).trim();
if (!editor) {
vscode.window.showInformationMessage("Editor does not exist");
return;
}
if (!cssCodeSelected) {
vscode.window.showWarningMessage("No CSS code selected");
return;
}
editor.edit((currentCssCode) => {
currentCssCode.replace(
editor.selection,
sortCssProperties("min", cssCodeSelected)
);
});
editor.document.save();
});
const cssMaxSort = vscode.commands.registerCommand("css-sort.max", () => {
const editor = vscode.window.activeTextEditor;
const cssCodeSelected = editor?.document.getText(editor.selection).trim();
if (!editor) {
vscode.window.showInformationMessage("Editor does not exist");
return;
}
if (!cssCodeSelected) {
vscode.window.showWarningMessage("No CSS code selected");
return;
}
editor.edit((currentCssCode) => {
currentCssCode.replace(
editor.selection,
sortCssProperties("max", cssCodeSelected)
);
});
editor.document.save();
});
context.subscriptions.push(cssMinSort, cssMaxSort);
}
function sortCssProperties(pattern: string, cssCode: string): string {
let sortedCssProperties: string = "";
const cssAst = parse(cssCode, { parseValue: false });
const arrCssProperties: string[] = generate(cssAst).split("}");
// Single sort
// Just css properties without css selector
if (arrCssProperties[arrCssProperties.length - 1] !== "") {
sortedCssProperties = cssCode
.trim()
.split("\n")
.filter((property) => property.trim() !== "")
.map((property) => property.trim() + ";")
.sort((firstProperty, secondProperty) =>
pattern === "min"
? firstProperty.length - secondProperty.length
: secondProperty.length - firstProperty.length
)
.join("\n");
}
// Multiple sort
// Can sort css properties more than one css selector with css properties
if (arrCssProperties[arrCssProperties.length - 1] === "") {
arrCssProperties.pop();
for (let index = 0; index < arrCssProperties.length; index++) {
const cssNode: string[] = arrCssProperties[index].split("{");
const cssSelector: string = cssNode[0].trim();
const cssProperties: string = cssNode[1]
.trim()
.split(";")
.filter((property) => property.trim() !== "")
.map((property) => property.trim() + ";")
.sort((firstProperty, secondProperty) =>
pattern === "min"
? firstProperty.length - secondProperty.length
: secondProperty.length - firstProperty.length
)
.join("\n");
sortedCssProperties += `${cssSelector} {\n ${cssProperties} \n}${
index === arrCssProperties.length - 1 ? "\n" : "\n\n"
}`;
}
}
return sortedCssProperties;
}
export function deactivate() {}
<file_sep>/README.md
<h1 align="center">📶 CSS-Sort</h1>
<br>
### 👨💻 About
Vscode extension to sort your CSS properties and make them easy to read.
<h3 align="center">. . .</h3>
### 🚀 Demo
[🔗 Try it now](https://marketplace.visualstudio.com/items?itemName=apriliandi246.css-sort)
<h3 align="center">. . .</h3>
### 🧰 Tech Stack
[<img alt="typescript" src="https://img.shields.io/badge/TypeScript-007ACC?style=for-the-badge&logo=typescript&logoColor=white" />](https://www.typescriptlang.org/) —
[<img alt="vscode" src="https://img.shields.io/badge/Visual_Studio_Code-0078D4?style=for-the-badge&logo=visual%20studio%20code&logoColor=white" />](https://code.visualstudio.com/api/get-started/your-first-extension)
<h3 align="center">. . .</h3>
### 📖 More about it
[🔗 Documentation](https://vscode-css-sort-website.vercel.app/)
[🔗 Why](https://apriliandi.xyz/blogs/my-first-vscode-extension)
<h3 align="right">(⌐■_■)</h3>
| acb261b95d505abcb8b7e39165525636f972d14c | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | apriliandi246/vscode-css-sort | 6acf7b7036c77e271a2734961195985ea00e5dda | 4b16279f1c03bdd51f57e214a299a0e893e43f09 | |
refs/heads/master | <file_sep>'use strict';
var app = angular.module('Lab');
app.controller('LabTechController', [ '$scope', '$rootScope', 'LabTechService',
function($scope, $rootScope, LabTechService) {
$scope.logout = "true";
$scope.name = $rootScope.name;
$scope.person = $rootScope.person;
$scope.getAllOrders = function () {
LabTechService.GetAllOrders(function (data) {
$scope.orders = data;
})
}
$scope.selectOrder = function (order) {
$scope.order = order;
}
$scope.updateOrder = function () {
$scope.order.assignedTo = $scope.person;
LabTechService.UpdateOrder($scope.order, function (data) {
})
}
} ]);
<file_sep>'use strict';
var app = angular.module('Nurse');
app.factory('NurseService',
['Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
function (Base64, $http, $cookieStore, $rootScope, $timeout) {
var service = {};
service.AddPatient = function (patient, callback) {
$http.post('http://localhost:8080/Assignment4_REST/rest/nurse/registerPatient', patient)
.success(function (data, status) {
callback(data);
});
};
return service;
}]);
app.factory('ListPatientsService',
['Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
function (Base64, $http, $cookieStore, $rootScope, $timeout) {
var service = {};
service.GetDiagnosis = function (callback) {
$http.get('http://localhost:8080/Assignment4_REST/rest/doctor/getDiagnosis')
.success(function (data, status) {
callback(data);
});
}
service.GenerateList = function (diagnosis, callback) {
$http.post('http://localhost:8080/Assignment4_REST/rest/nurse/generateList', diagnosis)
.success(function (data, status) {
callback(data);
});
}
return service;
}]);
app.factory('SearchPatientService',
['Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
function (Base64, $http, $cookieStore, $rootScope, $timeout) {
var service = {};
service.GetPatient = function (pId, callback) {
$http.get('http://localhost:8080/Assignment4_REST/rest/nurse/searchPatient/' + pId)
.success(function (data, status) {
callback(data);
});
};
service.SendEmail = function (patient, callback) {
$http.post('http://localhost:8080/Assignment4_REST/rest/notify/send', patient)
.success(function (data, status) {
callback(data);
});
}
service.TransferPatient = function (patient, callback) {
$http.post('http://localhost:8080/Assignment4_REST/rest/notify/transfer', patient)
.success(function (data, status) {
callback(data);
});
}
service.AddEncounter = function(encounter, callback) {
encounter.activeMeds = encounter.activeMeds.split(",");
encounter.allergies = encounter.allergies.split(",");
encounter.symptoms = encounter.symptoms.split(",");
encounter.status = "Open";
$http.post('http://localhost:8080/Assignment4_REST/rest/nurse/addEncounter', encounter)
.success(function (data, status) {
callback(data);
});
}
return service;
}]);<file_sep>package edu.neu.test;
import java.util.ArrayList;
import org.hibernate.Session;
import org.hibernate.Transaction;
import edu.neu.bean.DiagnosisBean;
import edu.neu.bean.DrugBean;
import edu.neu.bean.LabPersonBean;
import edu.neu.bean.PersonBean;
import edu.neu.bean.RoleBean;
import edu.neu.bean.UserAccountBean;
import edu.neu.hibernate.HibernateUtil;
public class TestMain {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
RoleBean docRole = new RoleBean();
docRole.setRoleName("Doctor");
RoleBean nurseRole = new RoleBean();
nurseRole.setRoleName("Nurse");
RoleBean labRole = new RoleBean();
labRole.setRoleName("LabTechnician");
PersonBean person = new PersonBean();
person.setName("<NAME>");
UserAccountBean ua = new UserAccountBean();
ua.setUsername("abhinavpunj");
ua.setPassword("<PASSWORD>");
ua.setPerson(person);
ua.setRole(docRole);
PersonBean nurse = new PersonBean();
nurse.setName("Nurse");
UserAccountBean ua2 = new UserAccountBean();
ua2.setUsername("nurse");
ua2.setPassword("<PASSWORD>");
ua2.setPerson(nurse);
ua2.setRole(nurseRole);
LabPersonBean lab = new LabPersonBean();
lab.setName("lab");
UserAccountBean ua3 = new UserAccountBean();
ua3.setUsername("lab");
ua3.setPassword("<PASSWORD>50983cd24fb0d6963f7d28e17f72");
ua3.setPerson(lab);
ua3.setRole(labRole);
DrugBean d1 = new DrugBean();
d1.setDrugName("drug1");
d1.setComponents(new ArrayList<String>());
d1.getComponents().add("sulphur");
d1.getComponents().add("paracetamol");
DrugBean d2 = new DrugBean();
d2.setDrugName("drug2");
d2.setComponents(new ArrayList<String>());
d2.getComponents().add("ibuprofen");
DrugBean d3 = new DrugBean();
d3.setDrugName("drug3");
d3.setComponents(new ArrayList<String>());
d3.getComponents().add("sulphur");
d3.getComponents().add("morphine");
DiagnosisBean db1 = new DiagnosisBean();
db1.setDiagnosisName("Cancer");
db1.setEduLink("http://www.cancer.gov/");
DiagnosisBean db2 = new DiagnosisBean();
db2.setDiagnosisName("High Cholestrol");
db2.setEduLink("http://www.nhlbi.nih.gov/health/resources/heart/heart-cholesterol-hbc-what-html");
DiagnosisBean db3 = new DiagnosisBean();
db3.setDiagnosisName("Influenza");
db3.setEduLink("http://www.cdc.gov/flu/");
DiagnosisBean db4 = new DiagnosisBean();
db4.setDiagnosisName("Migraine");
db4.setEduLink("http://www.webmd.com/migraines-headaches/");
session.save(db1);
session.save(db2);
session.save(db3);
session.save(db4);
session.save(docRole);
session.save(nurseRole);
session.save(labRole);
session.save(person);
session.save(nurse);
session.save(lab);
session.save(ua);
session.save(ua2);
session.save(ua3);
session.save(d1);
session.save(d2);
session.save(d3);
t.commit();
session.close();
//after close session detach state
System.out.println("success");
}
}
<file_sep>$(document).ready(function(){
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
var personId = 0;
var key;
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == 'personId')
{
personId = sParameterName[1];
}
else if(sParameterName[0] == 'AUTH_KEY')
{
key = sParameterName[1];
}
}
var perJson = {
personId : personId
};
$.ajax({
type : 'POST',
contentType : 'application/json',
url : "http://localhost:8080/Assignment4_REST/rest/doctor",
dataType : "json",
data : JSON.stringify(perJson),
beforeSend: function (xhr) {
///// Authorization header////////
xhr.setRequestHeader("AUTH_KEY", key);
},
success : function(data) {
var val = JSON.stringify(data);
var json = $.parseJSON(val);
$('#drName').append(json.name);
var list = $("#patientList");
for(var i=0; i<json.patients.length; i++){
list.append('<a href="Doctor-PatientProfile.jsp?doctorId=' +
personId + '&patientId=' + json.patients[i].patientId +
'" class="list-group-item">' + json.patients[i].patientId +':' + json.patients[i].name + '</a>');
}
},
error : function(er) {
alert("error");
},
failure : function(errormsg) {
alert(errormsg);
}
});
});<file_sep>'use strict';
angular.module('Authentication')
.controller('LoginController',
['$scope', '$rootScope', '$location', 'AuthenticationService',
function ($scope, $rootScope, $location, AuthenticationService) {
// reset login status
AuthenticationService.ClearCredentials();
$scope.login = function () {
$scope.dataLoading = true;
AuthenticationService.Login($scope.username, $scope.password, function(data, headers) {
if(data.personId > 0) {
AuthenticationService.SetCredentials($scope.username, $scope.password, headers);
$location.path('/' + headers('AUTH_KEY'));
$rootScope.name = data.name;
$rootScope.patients = data.patients;
$rootScope.personId = data.personId;
$rootScope.person = data;
} else {
$scope.error = response.message;
$scope.dataLoading = false;
}
});
};
}]);
<file_sep>package edu.neu.controller;
import java.util.ArrayList;
import java.util.Date;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.mysql.fabric.xmlrpc.base.Data;
import edu.neu.bean.DiagnosisBean;
import edu.neu.bean.EncounterBean;
import edu.neu.bean.PatientBean;
import edu.neu.hibernate.PatientDAO;
@Controller
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/nurse")
public class NurseController {
@Autowired
PatientDAO patientDao;
@POST
@RolesAllowed("nurse")
@Path("/registerPatient")
public void registerPatient(PatientBean patient)
{
patientDao.createPatient(patient);
}
@GET
@Path("/searchPatient/{pId}")
@RolesAllowed("nurse")
public PatientBean searchPatient(@PathParam(value = "pId") int patientId)
{
PatientBean patient = new PatientBean();
patient.setPatientId(patientId);
patient = patientDao.searchPatient(patient);
return patient;
}
@POST
@Path("/addEncounter")
@RolesAllowed("nurse")
public void addEncounter(EncounterBean encounter)
{
patientDao.addEncounterData(encounter);
}
@POST
@Path("/generateList")
@RolesAllowed("nurse")
public ArrayList<String> generatePatientList(DiagnosisBean diagnosis)
{
return patientDao.generateList(diagnosis);
}
}
<file_sep>package edu.neu.security;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashEncode {
public enum ALGO{
MD5("MD5");
public String algo;
private ALGO(String algo) {
this.algo = algo;
}
@Override
public String toString() {
return algo;
}
}
private HashEncode(){
}
public static String generateHash(String msg, ALGO algo){
String hash = null;
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance(algo.toString());
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] hashedBytes = digest.digest(msg.getBytes());
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < hashedBytes.length; i++)
{
stringBuffer.append(Integer.toString((hashedBytes[i] & 0xff) + 0x100, 16).substring(1));
}
hash = stringBuffer.toString();
return hash;
}
}
<file_sep>package edu.neu.interceptor;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.JsonParseException;
import org.springframework.stereotype.Component;
@Provider
@Component
public class JsonParsingExceptionMapping implements ExceptionMapper<JsonParseException> {
@Override
public Response toResponse(JsonParseException exception) {
// TODO Auto-generated method stub
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
<file_sep>package edu.neu.bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name = "Diagnosis")
public class DiagnosisBean {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "diagnosisId")
private int diagnosisId;
@Column(name = "diagnosisName")
private String diagnosisName;
@Column(name = "eduLink")
private String eduLink;
@Transient
private PatientBean patient;
public PatientBean getPatient() {
return patient;
}
public void setPatient(PatientBean patient) {
this.patient = patient;
}
public int getDiagnosisId() {
return diagnosisId;
}
public void setDiagnosisId(int diagnosisId) {
this.diagnosisId = diagnosisId;
}
public String getDiagnosisName() {
return diagnosisName;
}
public void setDiagnosisName(String diagnosisName) {
this.diagnosisName = diagnosisName;
}
public String getEduLink() {
return eduLink;
}
public void setEduLink(String eduLink) {
this.eduLink = eduLink;
}
}
<file_sep>package edu.neu.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.springframework.stereotype.Component;
import edu.neu.bean.EncounterBean;
import edu.neu.bean.PatientBean;
import edu.neu.bean.PersonBean;
import edu.neu.bean.VitalSignBean;
//@Component
public class DoctorDAO extends DAO {
public void updateDiagnosis(EncounterBean encounter)
{
Connection conn = null;
PreparedStatement stmt = null;
try
{
conn = getConnection();
String sql = "UPDATE encounter SET doctor_name = ?, diagnosis = ?, status = ? WHERE encounter_id = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, encounter.getDoctor());
stmt.setString(2, encounter.getDiagnosis());
stmt.setInt(3, encounter.getEncounterId());
stmt.setString(4, "Closed");
stmt.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public EncounterBean getVitalSignDetails(EncounterBean encounter)
{
Connection conn = null;
PreparedStatement stmt = null;
PreparedStatement stmt2 = null;
PreparedStatement stmt3 = null;
PreparedStatement stmt4 = null;
ResultSet rs = null;
String sql = null;
try
{
conn = getConnection();
sql = "SELECT v.temp, v.pulse, v.bloodpreesure, v.glucose, v.respiratoryrate, v.weight, v.height, v.bmi"
+ " FROM vitalsign v INNER JOIN encounter e ON e.vitalsign_id = v.VitalSign_Id WHERE e.encounter_id = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, encounter.getEncounterId());
rs = stmt.executeQuery();
while(rs.next())
{
VitalSignBean vs = new VitalSignBean();
vs.setTemp(rs.getFloat("temp"));
vs.setPulse(rs.getInt("pulse"));
vs.setBloodPressure(rs.getInt("bloodpreesure"));
vs.setGlucose(rs.getInt("glucose"));
vs.setRespRate(rs.getInt("respiratoryrate"));
vs.setWeight(rs.getFloat("weight"));
vs.setHeight(rs.getFloat("height"));
vs.setBmi(rs.getInt("bmi"));
encounter.setVitalSign(vs);
}
sql = "SELECT a.name FROM allergies a INNER JOIN encounter e ON a.encounter_id = e.encounter_id "
+ "WHERE e.encounter_id = ?";
stmt2 = conn.prepareStatement(sql);
stmt2.setInt(1, encounter.getEncounterId());
rs = stmt2.executeQuery();
encounter.setAllergies(new ArrayList<String>());
while(rs.next())
{
encounter.getAllergies().add(rs.getString("name"));
}
sql = "SELECT a.name FROM medication a INNER JOIN encounter e ON a.encounter_id = e.encounter_id "
+ "WHERE e.encounter_id = ?";
stmt3 = conn.prepareStatement(sql);
stmt3.setInt(1, encounter.getEncounterId());
rs = stmt3.executeQuery();
encounter.setActiveMeds(new ArrayList<String>());
while(rs.next())
{
encounter.getActiveMeds().add(rs.getString("name"));
}
sql = "SELECT a.name FROM symptoms a INNER JOIN encounter e ON a.encounter_id = e.encounter_id "
+ "WHERE e.encounter_id = ?";
stmt4 = conn.prepareStatement(sql);
stmt4.setInt(1, encounter.getEncounterId());
rs = stmt4.executeQuery();
encounter.setSymptoms(new ArrayList<String>());
while(rs.next())
{
encounter.getSymptoms().add(rs.getString("name"));
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
stmt.close();
stmt2.close();
stmt3.close();
stmt4.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return encounter;
}
public PersonBean getPatientDetails(PersonBean doc)
{
Connection conn = null;
PreparedStatement stmt = null;
PreparedStatement stmt2 = null;
try {
String sql = "Select name FROM person WHERE Person_Id = ?";
conn = getConnection();
stmt = conn.prepareStatement(sql);
stmt.setInt(1, doc.getPersonId());
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
doc.setName(rs.getString("name"));
}
String sql2 = "select a.patient_Id, a.name, a.age, a.phone, a.gender, "
+ "b.encounter_id, b.chiefComplaint, b.doctor_name, b.diagnosis, b.status"
+ " from patientprofile a inner join encounter b on a.patient_id = b.pateint_id where a.patient_id = ?";
stmt2 = conn.prepareStatement(sql2);
for(PatientBean p : doc.getPatients())
{
stmt2.setInt(1, p.getPatientId());
}
rs = stmt2.executeQuery();
for(PatientBean p : doc.getPatients())
{
p.setEncounterHistory(new ArrayList<EncounterBean>());
while(rs.next())
{
p.setName(rs.getString("name"));
p.setGender(rs.getString("gender"));
p.setAge(rs.getInt("age"));
p.setPhone(rs.getInt("phone"));
EncounterBean enc = new EncounterBean();
enc.setEncounterId(rs.getInt("encounter_id"));
enc.setChiefComplaint(rs.getString("chiefComplaint"));
enc.setDoctor(rs.getString("doctor_name"));
enc.setDiagnosis(rs.getString("diagnosis"));
enc.setStatus(rs.getString("status"));
p.getEncounterHistory().add(enc);
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
stmt.close();
stmt2.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return doc;
}
public PersonBean getDoctorDetails(PersonBean doc)
{
Connection conn = null;
PreparedStatement stmt = null;
PreparedStatement stmt2 = null;
try
{
String sql = "Select name FROM person WHERE Person_Id = ?";
conn = getConnection();
stmt = conn.prepareStatement(sql);
stmt.setInt(1, doc.getPersonId());
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
doc.setName(rs.getString("name"));
}
String sql2 = "Select patient_id as patientId, name FROM patientprofile";
stmt2 = conn.prepareStatement(sql2);
rs = stmt2.executeQuery();
doc.setPatients(new ArrayList<PatientBean>());
while(rs.next())
{
PatientBean p = new PatientBean();
p.setPatientId(rs.getInt("patientId"));
p.setName(rs.getString("name"));
doc.getPatients().add(p);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
stmt.close();
stmt2.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return doc;
}
}
<file_sep>package edu.neu.bean;
import java.util.ArrayList;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "WorkRequest")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class WorkRequestBean {
@Id @GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "WorkId")
private int workId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "sender", nullable = false)
private PersonBean sender;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "encounterId")
private EncounterBean encounter;
@Column(name = "updated")
private Date updated;
public int getWorkId() {
return workId;
}
public void setWorkId(int workId) {
this.workId = workId;
}
public PersonBean getSender() {
return sender;
}
public void setSender(PersonBean sender) {
this.sender = sender;
}
public EncounterBean getEncounter() {
return encounter;
}
public void setEncounter(EncounterBean encounter) {
this.encounter = encounter;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
}
<file_sep>package edu.neu.interceptor;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.stereotype.Component;
@Provider
@Component
public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
@Override
public Response toResponse(JsonMappingException exception) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}<file_sep>'use strict';
var app = angular.module('Doctor');
app.factory('LabTechService',
['Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
function (Base64, $http, $cookieStore, $rootScope, $timeout) {
var service = {};
service.GetAllOrders = function (callback) {
$http.get('http://localhost:8080/Assignment4_REST/rest/lab/getAllOrders')
.success(function (data, status) {
callback(data);
});
};
service.UpdateOrder = function (order, callback) {
$http.put('http://localhost:8080/Assignment4_REST/rest/lab/updateOrder', order)
.success(function (data, status) {
callback(data);
});
}
return service;
}]);<file_sep>//'use strict';
var app = angular.module('Doctor');
app.factory('PateintDetailsService',
['Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
function (Base64, $http, $cookieStore, $rootScope, $timeout) {
var service = {};
service.Details = function (patientId, personId, callback) {
$http.get('http://localhost:8080/Assignment4_REST/rest/doctor/patientDetails/' + personId + '/' + patientId)
.success(function (data, status) {
callback(data);
});
};
service.GetDiagnosis = function (callback) {
$http.get('http://localhost:8080/Assignment4_REST/rest/doctor/getDiagnosis')
.success(function (data, status) {
callback(data);
});
}
service.SendResources = function (diagnosis, callback) {
$http.post('http://localhost:8080/Assignment4_REST/rest/notify/sendResources', diagnosis)
.success(function (data, status) {
callback(data);
});
}
service.SendEmail = function (encounter, callback) {
$http.post('http://localhost:8080/Assignment4_REST/rest/notify/sendEncounter', encounter)
.success(function (data, status) {
callback(data);
});
}
service.UpdateDiagnosis = function (encounter, callback) {
$http.put('http://localhost:8080/Assignment4_REST/rest/doctor/updateDiagnosis', encounter)
.success(function (data, status) {
callback(data);
})
}
return service;
}]);
app.factory('LabResultsService',
['Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
function (Base64, $http, $cookieStore, $rootScope, $timeout) {
var service = {};
service.GetEncounters = function (patientId, callback) {
$http.get('http://localhost:8080/Assignment4_REST/rest/lab/getEncounters/' + patientId)
.success(function (data, status) {
callback(data);
});
};
service.GetOrders = function (patientId, callback) {
$http.get('http://localhost:8080/Assignment4_REST/rest/lab/getOrders/' + patientId)
.success(function (data, status) {
callback(data);
});
};
service.OrderTest = function (personId, encounterId, testName, callback) {
labOrder = {};
labOrder.encounter = encounterId;
labOrder.testName = testName;
labOrder.sender = {};
labOrder.sender.personId = personId;
$http.post('http://localhost:8080/Assignment4_REST/rest/lab/orderTest', labOrder)
.success(function(data, status) {
callback(data);
});
};
return service;
}]);
app.factory('PrescriptionService',
['Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
function (Base64, $http, $cookieStore, $rootScope, $timeout) {
var service = {};
service.GetEncounters = function (patientId, callback) {
$http.get('http://localhost:8080/Assignment4_REST/rest/lab/getEncounters/' + patientId)
.success(function (data, status) {
callback(data);
});
};
service.GetDrugs = function (callback) {
$http.get('http://localhost:8080/Assignment4_REST/rest/doctor/getDrugs')
.success(function (data, status) {
callback(data);
});
}
service.GetPrescriptions = function (patientId, callback) {
$http.get('http://localhost:8080/Assignment4_REST/rest/doctor/getPrescriptions/' + patientId)
.success(function (data, status) {
callback(data);
});
}
service.CheckAllergy = function (encounter, callback) {
$http.post('http://localhost:8080/Assignment4_REST/rest/doctor/checkAllergy', encounter)
.success(function(data, status) {
callback(data);
});
}
service.AddPrescription = function (encounter, callback) {
$http.post('http://localhost:8080/Assignment4_REST/rest/doctor/addPrescription', encounter)
.success(function(data, status) {
callback(data);
});
}
return service;
}]);<file_sep>package edu.neu.bean;
import java.util.ArrayList;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.springframework.stereotype.Component;
@Entity
@Table(name = "UserAccount")
public class UserAccountBean {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "userId")
private int userId;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "PersonId")
private PersonBean person;
@NotNull(message="Name is a required field")
@Column(name = "username")
private String username;
@NotNull(message="Password is a required field")
@Column(name = "password")
private String password;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "RoleId")
private RoleBean role;
public PersonBean getPerson() {
return person;
}
public void setPerson(PersonBean person) {
this.person = person;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public RoleBean getRole() {
return role;
}
public void setRole(RoleBean role) {
this.role = role;
}
}
<file_sep>package edu.neu.bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "vitalSign")
public class VitalSignBean {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "vitalSignId")
private int vitalSignId;
@Column(name = "temp")
private float temp;
@Column(name = "pulse")
private int pulse;
@Column(name = "bloodPressure")
private int bloodPressure;
@Column(name = "glucose")
private int glucose;
@Column(name = "respRate")
private int respRate;
@Column(name = "weight")
private float weight;
@Column(name = "height")
private float height;
@Column(name = "bmi")
private int bmi;
public int getVitalSignId() {
return vitalSignId;
}
public void setVitalSignId(int vitalSignId) {
this.vitalSignId = vitalSignId;
}
public float getTemp() {
return temp;
}
public void setTemp(float temp) {
this.temp = temp;
}
public int getPulse() {
return pulse;
}
public void setPulse(int pulse) {
this.pulse = pulse;
}
public int getBloodPressure() {
return bloodPressure;
}
public void setBloodPressure(int bloodPressure) {
this.bloodPressure = bloodPressure;
}
public int getGlucose() {
return glucose;
}
public void setGlucose(int glucose) {
this.glucose = glucose;
}
public int getRespRate() {
return respRate;
}
public void setRespRate(int respRate) {
this.respRate = respRate;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public int getBmi() {
return bmi;
}
public void setBmi(int bmi) {
this.bmi = bmi;
}
}
<file_sep>function register(){
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
var key;
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if(sParameterName[0] == 'AUTH_KEY')
{
key = sParameterName[1];
}
}
var dob = new Date($("#dob").val());
var dobJSON = dob.toJSON();
pat = {}
pat["name"] = $("#name").val();
pat["age"] = $("#age").val();
pat["gender"] = $("#gender").val();
pat["address"] = $("#address").val();
pat["phone"] = $("#phone").val();
$.ajax({
url: "http://localhost:8080/Assignment4_REST/rest/nurse/registerPatient",
data: JSON.stringify(pat),
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
beforeSend: function (xhr) {
///// Authorization header////////
xhr.setRequestHeader("AUTH_KEY", key);
},
success: function(data) {
alert("Patient Registered");
},
error: function(er) {
alert(er);
},
failure: function(errormsg) {
alert(errormsg);
}
});
/*actMed = {}
for(var i=0; i<med.length; i++){
actMed[i] = med[i];
}
pat[""]*/
}<file_sep>'use strict';
var app = angular.module('Doctor');
app.controller('DoctorController', [ '$scope', '$rootScope', function($scope, $rootScope) {
$scope.logout = "true";
$scope.name = $rootScope.name;
$scope.patients = $rootScope.patients;
$scope.personId = $rootScope.personId;
} ]);
app.controller('PatientProfileController', [ '$scope', '$rootScope', '$routeParams', '$timeout', 'PateintDetailsService',
function($scope, $rootScope, $routeParams, $timeout, PateintDetailsService) {
$scope.patientId = $routeParams.patientId;
$scope.notify = true;
PateintDetailsService.Details($scope.patientId, $rootScope.personId, function(data) {
$scope.patient = data.patients[0];
})
$scope.idSelected = null;
$scope.getVitalSign = function (encs) {
$scope.idSelected = encs.encounterId;
$scope.notify = false;
$scope.encounter = encs;
$scope.vs = encs.vitalSign;
$scope.symptoms = encs.symptoms;
$scope.activeMeds = encs.activeMeds;
$scope.allergies = encs.allergies;
}
$scope.getDiagnosis = function () {
PateintDetailsService.GetDiagnosis(function (data) {
$scope.allDiag = data;
})
}
$scope.sendEmail = function() {
$scope.dataLoading = true;
$scope.success = false;
PateintDetailsService.SendEmail($scope.encounter, function (data) {
$scope.dataLoading = false;
$scope.success = data;
$timeout(function () {
$scope.success = false;
}, 3000);
})
}
$scope.updateDiagnosis = function (diagObj) {
$scope.encounter.diagnosis = diagObj.diagnosisName;
$scope.encounter.doctor = $scope.name;
$scope.encounter.status = "Closed";
PateintDetailsService.UpdateDiagnosis($scope.encounter, function(data) {
diagObj.patient = $scope.encounter.patientId;
PateintDetailsService.SendResources(diagObj, function(data) {
})
})
}
}]);
app.controller('LabResultsController', [ '$scope', '$filter', '$rootScope', '$routeParams', 'LabResultsService',
function($scope, $filter, $rootScope, $routeParams, LabResultsService) {
$scope.logout = "true";
$scope.patientId = $routeParams.patientId;
$scope.name = $rootScope.name;
$scope.patients = $rootScope.patients;
$scope.personId = $rootScope.personId;
$scope.getEncounters = function() {
LabResultsService.GetEncounters($scope.patientId, function(data) {
$scope.encs = data;
})
}
$scope.orderTest = function () {
LabResultsService.OrderTest($scope.personId, $scope.selEncounter, $scope.testName, function(data) {
$scope.orders.push(data);
})
}
$scope.getOrders = function () {
LabResultsService.GetOrders($scope.patientId, function(data) {
$scope.orders = [];
$scope.orders = data;
})
}
} ]);
app.controller('PrescriptionController', [ '$scope', '$rootScope', '$routeParams', 'PrescriptionService',
function($scope, $rootScope, $routeParams, PrescriptionService) {
$scope.logout = "true";
$scope.patientId = $routeParams.patientId;
$scope.name = $rootScope.name;
$scope.patients = $rootScope.patients;
$scope.personId = $rootScope.personId;
$scope.getEncounters = function() {
PrescriptionService.GetEncounters($scope.patientId, function(data) {
$scope.encs = data;
})
}
$scope.getDrugs = function() {
PrescriptionService.GetDrugs(function(data) {
$scope.allDrugs = data;
})
}
$scope.getPrescriptions = function() {
PrescriptionService.GetPrescriptions($scope.patientId, function(data) {
$scope.drugs = data;
})
}
$scope.addPrescription = function(encounter) {
encounter.doctor = $scope.name;
PrescriptionService.CheckAllergy(encounter, function(data) {
$scope.drugAllergy = data;
})
if($scope.drugAllergy.length > 0){
PrescriptionService.AddPrescription(encounter, function(data) {
$scope.drugs = data;
})
}
}
} ]);<file_sep>package edu.neu.bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
@Entity
@Table(name = "Roles")
public class RoleBean {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "RoleId")
private int roleId;
@Column(name = "RoleName")
private String roleName;
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
| f81e7b14c186fb19e0fe5e46750361b82d993ba5 | [
"JavaScript",
"Java"
] | 19 | JavaScript | abhinavpunj/EHR_System | 8fb3230358626542a9eca9377675a6eb515f3872 | 6c29f99a76207cb57b00c3d18db5a6d8549c80c9 | |
refs/heads/master | <repo_name>Tarfala/RankingsC-<file_sep>/Rankings/Rankings/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rankings
{
class Program
{
// https://en.wikipedia.org/wiki/Ranking#Strategies_for_assigning_rankings
static void Main(string[] args)
{
Program program = new Program();
program.StandardRanking1224();
program.ModifiedRanking1334();
program.DenseRanking1223();
program.OrdinalRanking1234();
program.FractionalRanking125254();
}
public void StandardRanking1224()
{
int rank = 1;
Console.WriteLine("Standard Ranking 1224");
List<int> ranks = new List<int>
{
1,
2,
2,
3
};
while (ranks.Count() != 0)
{
var ranksWithSameNumber = ranks.Where(x => x == ranks[0]).ToList();
ranks.RemoveAll(x => ranksWithSameNumber.Exists(z => z == x));
foreach (var item in ranksWithSameNumber)
{
Console.WriteLine($"Rank of '{item}' is {rank}");
}
rank += ranksWithSameNumber.Count();
}
}
public void ModifiedRanking1334()
{
int rank = 0;
Console.WriteLine("Modified Ranking 1334");
List<int> ranks = new List<int>
{
1,
2,
2,
3
};
while (ranks.Count != 0)
{
var ranksWithSameNumber = ranks.Where(x => x == ranks[0]).ToList();
ranks.RemoveAll(x => ranksWithSameNumber.Exists(z => z == x));
rank += ranksWithSameNumber.Count();
foreach (var item in ranksWithSameNumber)
{
Console.WriteLine($"Rank of {item} is {rank}");
}
}
}
public void DenseRanking1223()
{
int rank = 1;
Console.WriteLine("Modified Ranking 1223");
List<int> ranks = new List<int>
{
1,
2,
2,
3
};
while (ranks.Count != 0)
{
var ranksWithSameNumber = ranks.Where(x => x == ranks[0]).ToList();
ranks.RemoveAll(x => ranksWithSameNumber.Exists(z => z == x));
foreach (var item in ranksWithSameNumber)
{
Console.WriteLine($"Rank of {item} is {rank}");
}
rank++;
}
}
public void OrdinalRanking1234()
{
int rank = 1;
Console.WriteLine("Ordinal Ranking 1234");
List<int> ranks = new List<int>
{
1,
2,
2,
3
};
while (ranks.Count != 0)
{
var ranksWithSameNumber = ranks.Where(x => x == ranks[0]).ToList();
ranks.RemoveAll(x => ranksWithSameNumber.Exists(z => z == x));
foreach (var item in ranksWithSameNumber)
{
Console.WriteLine($"Rank of {item} is {rank}");
rank++;
}
}
}
public void FractionalRanking125254()
{
Console.WriteLine("Fractional Ranking 125254");
var test = new List<FractClass>();
List<double> ranks = new List<double>
{
1, // 1 - 1.5 (3/2)
1, // 2 - 1.5 (3/2)
2, // 3 - 3 (3/1)
3, // 4 - 4.5 (9/2)
3, // 5 - 4.5 (9/2)
4, // 6 - 6 (6/1)
5, // 7 - 8 (24/3)
5, // 8 - 8 (24/3)
5 // 9 - 8 (24/3)
};
for (int i = 0; i < ranks.Count; i++)
{
test.Add(new FractClass() { Rank = ranks[i], OriginRank = i+1 });
}
while (ranks.Count() != 0)
{
var single = test.Where(x => x.Rank == ranks[0]).ToList();
ranks.RemoveAll(x => single.Exists(z => z.Rank == x));
foreach (var item in single)
{
Console.WriteLine($"Rank '{item.Rank}' has fractial rank {single.Sum(x => x.OriginRank) / single.Count()}");
}
}
}
}
}
<file_sep>/Rankings/Rankings/FractClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rankings
{
class FractClass
{
public double Rank { get; set; }
public double OriginRank { get; set; }
}
}
| 166dc642ad38ad4702430f12d273cb6370935eae | [
"C#"
] | 2 | C# | Tarfala/RankingsC- | 60c8e7d16a54b57f1179fda156567fd336907144 | fa102d1c797c67d2b7be9f749ef5813efec1d2e4 | |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Dec 11 15:18:04 2019
@author: Rowland
"""
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import math
print(np.pi)
print(math.pi)
t = np.arange(0.0, np.pi, 0.01)
s = np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel="x axis", ylabel="y axis", title="Here's a sin function")
ax.grid()
fig.savefig("test.png")
plt.show()
<file_sep>import random
import sys
frame_string = "---%--->_<---%---"
print(frame_string)
# face text art
print("|--------|")
print("|--O--O--|")
print("|--------|")
print("|---[]---|")
print("|--------|")
# opening problem, a simple one
def opening():
# creepy terminator message
print("Hello Human. Play a game with me.")
num_to_guess = random.randint(lower_range, upper_range)
print("I\'ve just thought of a number between %d and %d" % (lower_range, upper_range))
# prompt the user
print("guess my number: ")
user_guess = input()
# compare values
if(int(user_guess) == int(num_to_guess)):
print("That was correct! Thanks for playing with me.")
# elif
else:
print("Oops. Wrong guess. Better luck next time, human.")
# has number of chances to guess, with hints
def correction():
# message
print("Okay. It's your first time playing. Maybe I'll give you some help")
lives = 3
print("We'll play by the same rules, but this time I'll give your %s chances" % str(lives))
print("If I'm happy, I might even give you some hints")
num_to_guess = random.randint(lower_range, upper_range)
strikes = 0
# three chanced
while strikes < lives:
print("Take a guess:")
user_guess = input()
if(int(user_guess) == int(num_to_guess)):
print("Well done, human.")
break;
else:
"Hmmm. Not quite."
strikes += 1
# giving corrections
if(int(user_guess) > num_to_guess):
print("that one was too large")
else:
# no need to check for equal
print("that one was too small")
if(strikes >= lives):
print("You've lost. Try harder.")
elif(strikes < lives):
print("Good guess. That was correct! And you had %d chances left" % (lives-strikes))
upper_range = 11
lower_range = 1
opening()
correction()
print("Well, that was fun for me. See you next time, human.")
print(frame_string)
sys.exit(0)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Dec 19 01:31:46 2019
Project: (Crappy) Decision Maker
@author: <NAME>
@contact: <EMAIL>
"""
import tkinter as tk
from tkinter import *
import tkinter.ttk as ttk
from tkinter import messagebox
from tkinter import Menu
from tkinter.ttk import Progressbar
import random
"""global variables"""
window = tk.Tk()
window_width = 700
window_height = 400
"""function declaration"""
def window_setup():
window.title("App")
window.option_add('*font', ('verdana', 12, 'bold'))
window.configure(bg="Honeydew")
window.geometry(str(window_width) + "x" + str(window_height))
def make_label(c, r):
l = tk.Label(window, text="Test", font=("Arial Bold", 30))
l.grid(column=c, row=r)
def make_menu():
menu = Menu(window)
menuSub = Menu(menu, tearoff=0)
menuSub.add_command(label="Open")
menuSub.add_separator()
menuSub.add_command(label="New")
menuSub.add_command(label="Create")
menuSub.add_command(label="Error", command=popup)
menu.add_cascade(label="File", menu=menuSub)
menu.add_command(label="Exit")
window.config(menu=menu)
def popup():
messagebox.showerror("Error from menu", "You clicked the Error tab from menu")
def make_ui():
"""
General layout:
9x9 grid
[combobox] | [Entry] | [label]
[] | [button] | []
[] | [Entry] | []
"""
#combo box
combo = ttk.Combobox(window)
combo["values"] = ("Should", "Can", "Would", "Will")
combo.current(0)
#combo.grid(column=0, row=0)
combo.pack()
# combo.get(), similar to txtbox.get()
#text box
txtbox = tk.Entry(window, width=30)
#txtbox.grid(column=1, row=0)
txtbox.pack()
txtbox.focus()
# label
label = tk.Label(window, text="?", font=("Arial Bold", 20))
#label.grid(column=2, row=0)
label.pack()
def respond():
num = random.randint(0, 1)
if num == 0:
output = "Yes"
if num == 1:
output = "No"
response_label.configure(text="I think the answer is %s" % output)
# button
btn = tk.Button(window, text="Answer", command=respond)
btn.configure(bg="sky blue", fg="azure")
#btn.grid(column=1, row=1)
btn.pack()
# response label
response_label = tk.Label(window, text="", font=("Arial Bold", 20))
#response_label.grid(column=1, row=2)
response_label.pack()
def main():
window_setup()
make_menu()
make_ui()
window.mainloop()
main()<file_sep># Beginner Python Project Collection
A collection of simple python programs I've written to document my journey of learning Python
## Project Contents thus far
### in chronological order
- hello world
- guess the number
- rock paper scissors
- matplotlib graphing test
- hangman
- tkinter gui experiment
- dummy decision maker
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Dec 15 19:51:01 2019
@author: <NAME>
"""
# imports
import turtle
import time
import math
import random
class Coordinate:
def __init__(self, x, y): # two dashes
self.x = x
self.y = y
def getX(self):
return self.x
def getY(self):
return self.y
def setCor(self, x, y):
self.x = x
self.y = y
# window setup
def window_setup():
w = turtle.Screen()
w.title("Classic Snake")
w.bgcolor("skyBlue")
w.setup(width=screen_width, height=screen_height)
w.tracer(0) # turns off screen update
return w
# snake head
def make_snake_head():
h = turtle.Turtle()
h.shape("square")
h.speed(0) #animation speed? fastest
h.color("black")
h.penup() #imagin lifting pen up, not tracing a line
h.goto(0, 0)
h.direction = "stop"
return h
# food
def make_snake_food():
f = turtle.Turtle()
f.shape("circle")
f.speed(0)
f.color("Honeydew")
f.penup()
# position foor with random_food later
return f
# global var
screen_width = 600
screen_height = 600
tick_time = 0.1
step_size = 5
last_loc = Coordinate(0, 0)
food_eaten = 0
window = window_setup()
food = make_snake_food()
head = make_snake_head()
def go_up():
head.direction = "up"
def go_down():
head.direction = "down"
def go_left():
head.direction = "left"
def go_right():
head.direction = "right"
def move():
# update last tick location
last_loc.setCor(head.xcor(), head.ycor())
if head.direction == "up":
y = head.ycor()
head.sety(y + step_size)
if head.direction == "down":
y = head.ycor()
head.sety(y - step_size)
if head.direction == "left":
x = head.xcor()
head.setx(x - step_size)
if head.direction == "right":
x = head.xcor()
head.setx(x + step_size)
def bounds_check():
x = head.xcor()
y = head.ycor()
# print(str(window.screensize()[0]) + ", " + str(window.screensize()[1]))
if (-screen_width/2 < x < screen_width/2) and (-screen_height/2 < y < screen_height/2):
# print("still on screen")
return True
print("%d - %d" % (last_loc.getX(), last_loc.getY()))
head.goto(last_loc.getX(), last_loc.getY())
print("ouh, my head")
head.direction = "stop"
if head.direction == "up":
pass
if head.direction == "down":
pass
if head.direction == "left":
pass
if head.direction == "right":
pass
mouth_range = 5
# check if the snake head is onto of food
def food_check():
head_x = head.xcor()
head_y = head.ycor()
food_x = food.xcor()
food_y = food.ycor()
delt_x = head_x - food_x
delt_y = head_y - food_y
distance = math.sqrt(delt_x**2 + delt_y**2)
if distance < mouth_range:
global food_eaten
food_eaten = food_eaten + 1
print("Yum! Score = %d" % food_eaten)
# pseudo generate new food
random_food()
def random_food():
x = random.randint(-screen_width/2, screen_width/2)
y = random.randint(-screen_height/2, screen_height/2)
position_food(x, y)
# we will be using the same food object, moving it to new locations to simulate new food
def position_food(x, y):
food.goto(int(x), int(y))
game_puased = False
# pause the game
def puase():
head.
head.direction = "stop"
pass
# resume from pause, if called without puase then does nothing
def resume():
if not game_puased:
return
# key binding
def key_bind():
window.listen()
window.onkeypress(go_up, "w") # note: onkeypress seems to not allow a method with parameters
window.onkeypress(go_left, "a")
window.onkeypress(go_down, "s")
window.onkeypress(go_right, "d")
window.onkeypress(pause, "p")
window.onkeypress(resume, "r")
def main():
# global variable initializing methods call on variable declaration
#window_setup()
#make_snake_head()
key_bind()
random_food() # initialize a food location
# main game loop
while True:
window.update()
move()
food_check()
bounds_check()
time.sleep(tick_time)
window.mainloop() # is essentially replaced by the infinite update loop
# calling main function
main()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Dec 12 15:07:49 2019
@author: <NAME>
"""
import random
# gloabal variable
targetWord = ""
stylelisticSeperator = "=============================="
unknown = "_"
chances = 5
# method definition
def main():
print(stylelisticSeperator)
print("Hello human. Welcom to a game of hangman.")
global targetWord
targetWord = randomWord()
print(stylelisticSeperator)
queryUser()
print(stylelisticSeperator)
endGame()
print(stylelisticSeperator)
def randomWord():
file = open("words_Xethron.txt", "r")
if file.mode == "r":
print("using words from %s" % file.name)
# contents = file.read()
# print(contents)
fileLines = file.readlines()
lineCount = 0
for line in fileLines:
lineCount += 1
line = line.strip()
# print("%d - %s" % (lineCount, line))
wordNum = random.randint(0, lineCount+1)
randomWord = fileLines[wordNum].strip()
print("DEBUG: num: %d, word: %s" % (wordNum, randomWord))
return randomWord
pass
def queryUser():
prompt = "I expect you know the rules of the game.\nI will give you %d chances in total" % chances
print(prompt)
ask([], 0)
pass
def ask(knowledge, strikes):
if(strikes >= chances):
print("Sorry human. It seems you have run out of chances to guess my word.\nBetter luck next time.")
return
print("You have %d chances left." % (chances-strikes))
progress_so_far = currentKnowledge(knowledge)
print(progress_so_far)
if not(unknown in progress_so_far) :
print("Congratulations. You've pieced together that the word is %s" % targetWord)
return
currentGuess = input("Make your guess: ")
if(currentGuess == targetWord):
print("That was correct! the answer is %s" % currentGuess)
return
if currentGuess in targetWord:
print("the word does contain [%s]" % currentGuess)
knowledge.extend(currentGuess)
pass
else:
print("the word does not have [%s] in it" % currentGuess)
strikes += 1
pass
ask(knowledge, strikes)
def currentKnowledge(knowledge):
output = ""
for a in targetWord:
if (a in knowledge):
output += a
output += " "
else:
output += unknown
output += " "
return output.strip()
pass
def endGame():
prompt = "Thank you for playing hangman with me.\nI look forward to our next encouter."
print(prompt)
pass
# code execution
main()<file_sep>import random
import sys
import time
# Author: <NAME>
# <EMAIL>
# Last Modified: 12/11/1998
print("Welcome, human. Shall we play some rock, paper, scissors?")
want_to_play = input("y/n ?")
if want_to_play == "y":
# continue
pass
else:
print("Okay. Until next time, perhaps")
sys.exit(0)
print("Great. You know the rules.")
time.sleep(1)
print("rock...")
time.sleep(0.5)
print("paper...")
time.sleep(0.5)
print("scissors!")
time.sleep(0.5)
npc_move = random.randint(1,3+1)
# 1 --> rock, 2 --> paper, 3 --> scissors
player_move = "na"
def query():
global player_move
player_move = input("What do you play? r/p/s ?")
if(player_move == "r"):
# rock
print("you\'ve chosen rock!")
elif(player_move == "p"):
# paper
print("you\'ve chosen paper!")
elif(player_move == "s"):
# scissors
print("you\'ve chosen scissors")
else:
print("not a valid response")
query()
def tie():
# a tie has occured
print("A tie! It seems we are evenly matched.")
def win():
# player has won
print("Congratulations, human. You have bested me.")
def loss():
# computer has won
print("You have lost. I don\'t laugh. But if I could, I would be doing it now.")
query()
npc_play = ""
if npc_move == 1:
npc_play = "rock"
elif npc_move == 2:
npc_play = "paper"
elif npc_move == 3:
npc_play = "scissors"
else:
print("Error: unexpected npc_move")
print("Terminating")
sys.exit(0)
print("computer has played %s" % npc_play)
if(player_move == "r"):
if(npc_move == 1):
tie()
if(npc_move == 2):
loss()
if(npc_move == 3):
win()
elif(player_move == "p"):
if(npc_move == 1):
win()
if(npc_move == 2):
tie()
if(npc_move == 3):
loss()
elif(player_move == "s"):
if(npc_move == 1):
loss()
if(npc_move == 2):
win()
if(npc_move == 3):
tie()
else:
print("Error: unexpected input")
print("Terminating program")
sys.exit(0)
time.sleep(1)
print("Thank you for entertaining me, human. I am looking forward to our next encounter.")
print("--->.<---")
sys.exit(0)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Dec 12 22:03:05 2019
Based on tutorial@
https://likegeeks.com/python-gui-examples-tkinter-tutorial/#Add-a-combobox-widget
@author: <NAME>
@contact: <EMAIL>
"""
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
from tkinter import Menu
from tkinter.ttk import Progressbar
window = tk.Tk()
# window setup
window.title("App")
window.geometry("700x400")
# label
l = tk.Label(window, text="Hello", font=("Arial Bold", 30))
l.grid(column=1, row=0)
def clicked():
l.configure(text="You typed %s" % txtbox.get())
# button
btn = tk.Button(window, text="click!", command=clicked)
btn.configure(bg="sky blue", fg="azure")
btn.grid(column=0, row=0)
#text box
txtbox = tk.Entry(window, width=15)
txtbox.grid(column=0, row=1)
txtbox.focus()
#combo box
combo = ttk.Combobox(window)
combo["values"] = (1, 2, 3, "Text")
combo.current(0)
combo.grid(column=1, row=1)
# combo.get(), similar to txtbox.get()
# check button
checkbutton = tk.Checkbutton(window, text="check bos", var=True)
checkbutton.grid(column=2, row=0)
# radio button
selectedRadio = tk.IntVar()
radioBt1 = tk.Radiobutton(window, text="option", value=1, variable=selectedRadio)
radioBt2 = tk.Radiobutton(window, text="something else", value=2, variable=selectedRadio)
radioBt1.grid(column=2, row=1)
radioBt2.grid(column=3, row=1)
# button for radio button
def radioCheck():
l.configure(text=selectedRadio.get())
btn_radio = tk.Button(window, text="get radio value", comman=radioCheck)
btn_radio.grid(column=4, row=1)
# scrolled text
"""is an option, I just didn't bother with it"""
#message box
def popup():
messagebox.showinfo("Message", combo.get())
messageBt = tk.Button(window, text="message", command=popup)
messageBt.grid(column=2, row=2)
#spin box
spinvar = tk.IntVar()
spinvar.set(10)
spin = tk.Spinbox(window, from_=0, to=100, width=5, textvariable=spinvar)
spin.grid(column=3, row=2)
# progress bar
"""using ttk.style to customize the progress bar"""
barstyle = ttk.Style()
barstyle.theme_use("default")
barstyle.configure("black.Horizontal.TProgressvar", background="black")
bar = Progressbar(window, length=100, style="black.Horizontal.TProgressbar")
bar["value"] = 60
bar.grid(column=0, row=2)
# Menu
def menu_error():
messagebox.showerror("Error from menu", "You clicked the Error tab from menu")
menu = Menu(window)
menuSub = Menu(menu, tearoff=0)
menuSub.add_command(label="Open")
menuSub.add_separator()
menuSub.add_command(label="New")
menuSub.add_command(label="Create")
menuSub.add_command(label="Error", command=menu_error)
menu.add_cascade(label="File", menu=menuSub)
menu.add_command(label="Exit")
window.config(menu=menu)
# tabs
"""
Example
perhaps? TODO
"""
"""
window = Tk()
window.title("Welcome to LikeGeeks app")
tab_control = ttk.Notebook(window)
tab1 = ttk.Frame(tab_control)
tab2 = ttk.Frame(tab_control)
tab_control.add(tab1, text='First')
tab_control.add(tab2, text='Second')
lbl1 = Label(tab1, text= 'label1', padx=5, pady=5)
lbl1.grid(column=0, row=0)
lbl2 = Label(tab2, text= 'label2')
lbl2.grid(column=0, row=0)
tab_control.pack(expand=1, fill='both')
window.mainloop()
"""
window.mainloop()
| 02deb6a0cbf1d480bbc0d7bc7b6ab2e6e0e9ae23 | [
"Markdown",
"Python"
] | 8 | Python | ZR0W/Beginner-Python-Project-Collection | 36d19a2c5767a255e3530edd208a305300f241ad | c34c8d96fd46dae3ebd0257baff51a096c0a0d3b | |
refs/heads/master | <repo_name>Lacratus/MarketPlugin<file_sep>/src/main/java/be/lacratus/market/objects/DDGPlayer.java
package be.lacratus.market.objects;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.UUID;
public class DDGPlayer {
private UUID uuid;
private PriorityQueue<AuctionItem> personalItems;
private boolean isBidding;
private AuctionItem bidAuctionItem;
private List<AuctionItem> biddenItems;
public DDGPlayer(UUID uuid) {
this.uuid = uuid;
this.personalItems = new PriorityQueue<>();
this.biddenItems = new ArrayList<>();
}
public UUID getUuid() {
return uuid;
}
public PriorityQueue<AuctionItem> getPersonalItems() {
return personalItems;
}
public boolean isBidding() {
return isBidding;
}
public void setBidding(boolean bidding) {
isBidding = bidding;
}
public AuctionItem getBidAuctionItem() {
return bidAuctionItem;
}
public void setBidAuctionItem(AuctionItem bidAuctionItem) {
this.bidAuctionItem = bidAuctionItem;
}
public List<AuctionItem> getBiddenItems() {
return biddenItems;
}
}
<file_sep>/src/main/java/be/lacratus/market/commands/MoneyCommand.java
package be.lacratus.market.commands;
import be.lacratus.market.Market;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class MoneyCommand implements CommandExecutor {
Market main;
public MoneyCommand(Market market) {
this.main = market;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("You have to be a player");
return false;
}
if (args.length == 0) {
OfflinePlayer player = (OfflinePlayer) sender;
sender.sendMessage(main.getEconomyImplementer().getBalance(player) + "");
return true;
}
if (args.length == 1) {
try {
Player player = Bukkit.getPlayer(args[0]);
double balance = main.getEconomyImplementer().getBalance(player);
sender.sendMessage(balance + "");
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
}
<file_sep>/src/main/java/be/lacratus/market/listeners/OnJoinListener.java
package be.lacratus.market.listeners;
import be.lacratus.market.Market;
import be.lacratus.market.data.StoredDataHandler;
import be.lacratus.market.objects.DDGPlayer;
import be.lacratus.market.objects.AuctionItem;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class OnJoinListener implements Listener {
private Market main;
private StoredDataHandler storedDataHandler;
public OnJoinListener(Market main) {
this.main = main;
this.storedDataHandler = main.getStoredDataHandler();
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
if (main.getEconomyImplementer().createPlayerAccount(player)) {
System.out.println("Account created");
} else {
System.out.println("Account already existed");
}
//Fill onlinePlayers
//Check if player gets item back
DDGPlayer ddgPlayer;
List<AuctionItem> auctionItems;
if (main.getPlayersWithItems().containsKey(uuid)) {
ddgPlayer = main.getPlayersWithItems().get(uuid);
auctionItems = new ArrayList<>(main.getPlayersWithItems().get(uuid).getBiddenItems());
for (AuctionItem item : auctionItems) {
long timeLeft = item.getTimeOfDeletion() - (System.currentTimeMillis() / 1000);
if (timeLeft < 0) {
player.getInventory().setItem(player.getInventory().firstEmpty(), item.getItemStack());
main.getPlayersWithBiddings().get(uuid).getBiddenItems().remove(item);
main.getItemsRemoveDatabase().add(item);
}
}
main.getOnlinePlayers().put(uuid, ddgPlayer);
main.updateLists(ddgPlayer);
} else if (main.getPlayersWithBiddings().containsKey(uuid)) {
ddgPlayer = main.getPlayersWithBiddings().get(uuid);
auctionItems = new ArrayList<>(main.getPlayersWithBiddings().get(uuid).getBiddenItems());
for (AuctionItem item : auctionItems) {
long timeLeft = item.getTimeOfDeletion() - (System.currentTimeMillis() / 1000);
if (timeLeft < 0) {
player.sendMessage("You are getting a item from the auction, get some inventory space");
main.giveItemWhenInventoryFull(item, ddgPlayer, 30);
main.getPlayersWithBiddings().get(uuid).getBiddenItems().remove(item);
}
}
main.getOnlinePlayers().put(uuid, ddgPlayer);
main.updateLists(ddgPlayer);
} else {
storedDataHandler.loadData(uuid).thenAccept(DDGspeler ->
main.getOnlinePlayers().put(uuid, DDGspeler)).exceptionally(throwable -> {
throwable.printStackTrace();
return null;
});
}
}
}
<file_sep>/src/main/java/be/lacratus/market/util/ItemStackSerializer.java
package be.lacratus.market.util;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class ItemStackSerializer {
@SuppressWarnings("deprecation")
public static String ItemStackToString(ItemStack itemStack) {
String serialization = null;
if (itemStack != null) {
StringBuilder serializedItemStack = new StringBuilder();
String itemStackType = String.valueOf(itemStack.getType().getId());
serializedItemStack.append("Item@").append(itemStackType);
if (itemStack.getDurability() != 0) {
String itemStackDurability = String.valueOf(itemStack.getDurability());
serializedItemStack.append(":d@").append(itemStackDurability);
}
if (itemStack.getAmount() != 1) {
String itemStackAmount = String.valueOf(itemStack.getAmount());
serializedItemStack.append(":a@").append(itemStackAmount);
}
if (itemStack.getItemMeta().getDisplayName() != null) {
String itemStackName = itemStack.getItemMeta().getDisplayName();
serializedItemStack.append(":n@").append(itemStackName);
}
Map<Enchantment, Integer> itemStackEnch = itemStack.getEnchantments();
if (itemStackEnch.size() > 0) {
for (Entry<Enchantment, Integer> ench : itemStackEnch.entrySet()) {
serializedItemStack.append(":e@").append(ench.getKey().getId()).append("@").append(ench.getValue());
}
}
List<String> lores = itemStack.getItemMeta().getLore();
if (lores != null && lores.size() > 0) {
for (String lore : lores) {
serializedItemStack.append(":l@").append(lore);
}
}
if (itemStack.getType() == Material.ENCHANTED_BOOK) {
EnchantmentStorageMeta bookmeta = (EnchantmentStorageMeta) itemStack.getItemMeta();
Map<Enchantment, Integer> enchantments = bookmeta.getStoredEnchants();
if (enchantments.size() > 0) {
for (Entry<Enchantment, Integer> bookenchants : enchantments.entrySet()) {
serializedItemStack.append(":m@").append(bookenchants.getKey().getId()).append("@").append(bookenchants.getValue());
}
}
}
serialization = serializedItemStack.toString();
}
return serialization;
}
@SuppressWarnings("deprecation")
public static ItemStack StringToItemStack(String serializedItem) {
ItemStack itemStack = null;
boolean createdItemStack = false;
String[] serializedItemStack = serializedItem.split(":");
for (String itemInfo : serializedItemStack) {
String[] itemAttribute = itemInfo.split("@");
if (itemAttribute[0].equals("Item")) {
itemStack = new ItemStack(Material.getMaterial(Integer.parseInt(itemAttribute[1])));
createdItemStack = true;
} else if (itemAttribute[0].equals("d") && createdItemStack) {
itemStack.setDurability(Short.parseShort(itemAttribute[1]));
} else if (itemAttribute[0].equals("a") && createdItemStack) {
itemStack.setAmount(Integer.parseInt(itemAttribute[1]));
} else if (itemAttribute[0].equals("e") && createdItemStack) {
itemStack.addEnchantment(Enchantment.getById(Integer.parseInt(itemAttribute[1])), Integer.parseInt(itemAttribute[2]));
} else if (itemAttribute[0].equals("n") && createdItemStack) {
ItemMeta itemMeta = itemStack.getItemMeta();
itemMeta.setDisplayName(itemAttribute[1]);
itemStack.setItemMeta(itemMeta);
} else if (itemAttribute[0].equals("l") && createdItemStack) {
ItemMeta itemMeta = itemStack.getItemMeta();
List<String> lores = new ArrayList<>();
lores.add(itemAttribute[1]);
itemMeta.setLore(lores);
itemStack.setItemMeta(itemMeta);
} else if (itemAttribute[0].equals("m") && createdItemStack) {
EnchantmentStorageMeta itemStackMeta = (EnchantmentStorageMeta) itemStack.getItemMeta();
itemStackMeta.addStoredEnchant(Enchantment.getById(Integer.parseInt(itemAttribute[1])), Integer.parseInt(itemAttribute[2]), true);
itemStack.setItemMeta(itemStackMeta);
}
}
return itemStack;
}
}<file_sep>/src/main/java/be/lacratus/market/util/AuctionHouse.java
package be.lacratus.market.util;
import be.lacratus.market.objects.AuctionItem;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.concurrent.TimeUnit;
public class AuctionHouse {
public AuctionHouse() {
}
public static void openAuctionHouse(Player player, PriorityQueue<AuctionItem> allItems, int page, String title) {
ArrayList<AuctionItem> items = new ArrayList<>(allItems);
if (title.equals("AuctionHouse")) {
items.sort(new SortByIndexAscending());
} else if (title.equals("Personal")) {
items.sort(new SortByIndexDescending());
}
Inventory auctionHouse = Bukkit.createInventory(null, 54, title);
//Get to previous page if possible
ItemStack previousPage;
ItemMeta previousMeta;
if (PageUtil.isPageValid(allItems, page - 1, 45)) {
previousPage = new ItemStack(Material.STAINED_GLASS, 1, (short) 5);
} else {
previousPage = new ItemStack(Material.STAINED_GLASS, 1, (short) 14);
}
previousMeta = previousPage.getItemMeta();
previousMeta.setDisplayName(ChatColor.GREEN + "PREVIOUS PAGE");
previousMeta.setLocalizedName(page + "");
previousPage.setItemMeta(previousMeta);
auctionHouse.setItem(45, previousPage);
//Get to next page if possible
ItemStack nextPage;
ItemMeta nextMeta;
if (PageUtil.isPageValid(allItems, page + 1, 45)) {
nextPage = new ItemStack(Material.STAINED_GLASS, 1, (short) 5);
} else {
nextPage = new ItemStack(Material.STAINED_GLASS, 1, (short) 14);
}
nextMeta = nextPage.getItemMeta();
nextMeta.setDisplayName(ChatColor.GREEN + "NEXT PAGE");
nextPage.setItemMeta(nextMeta);
auctionHouse.setItem(53, nextPage);
// Fill up AuctionHouse and add lores
for (AuctionItem item : PageUtil.getPageItems(items, page, 45)) {
//Get Itemstack
ItemStack itemstack = item.getItemStack();
ItemMeta itemMeta = itemstack.getItemMeta();
//Create lore
List<String> lores = itemMeta.getLore();
lores.add("Bid: " + item.getHighestOffer() + "€");
long timeLeft = item.getTimeOfDeletion() - System.currentTimeMillis() / 1000;
long[] timeList = onlineTimeToLong(timeLeft);
lores.add("Hours: " + timeList[0] + ", Minutes: " + timeList[1] + ", Seconds: " + timeList[2]);
itemMeta.setLore(lores);
itemstack.setItemMeta(itemMeta);
//Set Item
auctionHouse.setItem(auctionHouse.firstEmpty(), item.getItemStack());
}
player.openInventory(auctionHouse);
// Remove lores
for (AuctionItem item : PageUtil.getPageItems(items, page, 45)) {
// Get Itemstack
ItemStack itemstack = item.getItemStack();
ItemMeta itemMeta = itemstack.getItemMeta();
// Remove Auction lore
List<String> lores = itemMeta.getLore();
lores.remove(lores.size() - 1);
lores.remove(lores.size() - 1);
itemMeta.setLore(lores);
itemstack.setItemMeta(itemMeta);
}
}
public static long[] onlineTimeToLong(long timeInSeconds) {
long hours = TimeUnit.SECONDS.toHours(timeInSeconds);
timeInSeconds -= TimeUnit.HOURS.toSeconds(hours);
long minutes = TimeUnit.SECONDS.toMinutes(timeInSeconds);
timeInSeconds -= TimeUnit.MINUTES.toSeconds(minutes);
long seconds = TimeUnit.SECONDS.toSeconds(timeInSeconds);
return new long[]{hours, minutes, seconds};
}
}
| 89ef2b087b80ebdd5e6f94c7f63d1accc8c7505e | [
"Java"
] | 5 | Java | Lacratus/MarketPlugin | 041fb5fbd14d389200b896e05fbb996bdc139691 | 69590756ac16420268ad796cad5f61ade988584e | |
refs/heads/master | <repo_name>Oroko/Roks<file_sep>/myfirstwebsite/home.php
<html>
<head>
<title>My First PHP website</title>
</head>
<?php
session_start(); // starts the session
if($_SESSION['user']){//checks if user is logged in
}
else{
header("location:index.php"); //reirects if user is not logged in
}
$user= $_SESSION['user']; //assigns user values
?>
<body>
<h2>Home Page</h2>
<p>Hello <?php print "$user"?>!</p> <!--Displays user's name-->
<a href="logout.php">Click here to logout</a><br/><br/>
<form action ="add.php" method = "POST">
Add more to list: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type= "submit" value="Add to list"/>
</form>
<h2 align="center">My List</h2>
<table border = "1px" width="100%">
<tr>
<td>ID</td>
<td>Details</td>
<td>Post Time</td>
<td>Edit Time</td>
<td>Edit</td>
<td>Delete</td>
<td>Public Post</td>
</tr>
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("abe_db") or die("Could not connect");
$query = mysql_query("select id, details, date_posted, time_posted, date_edited, time_edited, public from list");
while($row=mysql_fetch_array($query)){
print "<tr>" ;
print '<td align="center">' . $row['id']. '</td>';
print '<td align="center">' . $row['details']. '</td>';
print '<td align="center">' . $row['date_posted'] .'-'. $row['time_posted']. '</td>';
print '<td align="center">' . $row['date_edited'] .'-'. $row['time_edited']. '</td>';
print '<td align="center"><a href="edit.php">edit</a> </td>';
print '<td align="center"><a href="delete.php">delete</a> </td>';
print '<td align="center">' . $row['public']. '</td>';
print "</tr>";
}
?>
</table>
</body>
</html>
<file_sep>/myfirstwebsite/index.php
<!DOCTYPE html>
<html>
<head>
<title>My First Website</title>
</head>
<body>
<?php
echo "Hello World!";
?>
<a href = "login.php">Click here to log
<a href = "register.php">Click here to register
</body>
</html>
<file_sep>/myfirstwebsite/try.php
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("abe_db") or die("Could not connect");
$query = mysql_query("select id, details, date_posted, time_posted, date_edited, time_edited, public from list");
while($row=mysql_fetch_array($query)){
print "<tr>" ;
print '<td align="center">' . $row['id']. '</td>';
print '<td align="center">' . $row['details']. '</td>';
print '<td align="center">' . $row['date_posted'] .'-'. $row['time_posted']. '</td>';
print '<td align="center">' . $row['date_edited'] .'-'. $row['time_edited']. '</td>';
print '<td align="center"><a href="edit.php">edit</a> </td>';
print '<td align="center"><a href="delete.php">delete</a> </td>';
print '<td align="center">' . $row['public']. '</td>';
print "</tr>";
}
?>
<file_sep>/myfirstwebsite/add.php
<?php
session_start();
if($_SESSION['user']){
}
else{
header("location:index.php");
}
if($_SERVER['REQUEST_METHOD'] == "POST"){
$details=$_REQUEST['details'];
$time= strftime("%X"); //time
$date= strftime("%B %d,%Y");//date
$decision ="no";
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("abe_db") or die("Could not connect to the database!");
foreach($_REQUEST['public'] as $each_check)
{
if ($each_check != null)
{
$decision="yes";
}
}
mysql_query("INSERT INTO list(details,date_posted,time_posted,public) VALUES('$details','$date','$time','$decision')");
header("location:home.php");
}
else{
header("location:home.php");
}
?>
| 364e78c115d986b566b1d5499c1e5fe55e7e65c3 | [
"PHP"
] | 4 | PHP | Oroko/Roks | 4f7824d117ec9cfe56c7da92b2020a545977d673 | 7c94b5b03e34bc1634e5effff88c1a2b0da961c3 | |
refs/heads/master | <file_sep>import numpy as np
import sys
from numpy import array
import balance as bal
import random
# import interface as gui
np.set_printoptions(threshold=324) # total number of matrix elements before truncation occurs (18x18 square)
if (len(sys.argv) >= 2):
argv = sys.argv[1:]
else:
argv = ["none"]
def createTable(size):
grid = [[0] * (size) for _ in range(size)]
return grid
# end createTable method
# this method randomly fills an nxn table with blocks from the block array
def randomizeTable(table, blocks, size):
for x in range(size):
for y in range (size):
number = random.choice(blocks)
table[x][y] = number
blocks = blocks[blocks != number]
return table
def main():
size = input("How big would you like the table? ")
try:
size = int(size)
if (size >= 4):
# create an array with weighted blocks
blocks = array(range(1, (size * size) +1))
opening = "\nThe Weighted Blocks For A {} x {} Square Are:\n".format(size,size)
print(opening,blocks, "\n")
# create empty table
print("Empty Table:")
table = createTable(size)
print("\n", np.matrix(table), "\n")
if(size % 4 == 0):
print("Creating a doubly even magic square:")
table = bal.doublyEven(size)
print("\n",np.matrix(table),"\n")
print("Table is a Magic Square: ", bal.isMagicSquare(table), "\n")
isBalanced = bal.checkBalance(table, blocks, size)
print("Table is balanced: ", isBalanced, "\n")
if (argv[0] == "-r"):
print("Randomizing Table: -------------------------------------")
table = randomizeTable(table, blocks, size)
print("\n",np.matrix(table),"\n")
isBalanced = bal.checkBalance(table, blocks, size)
while (not isBalanced):
table = randomizeTable(table, blocks, size)
isBalanced = bal.checkBalance(table, blocks, size)
print("Table is balanced: ", isBalanced, "\n")
elif(size % 2 == 0):
print("Creating singly even magic square:")
table = bal.build_sems(size)
print("\n",np.matrix(table),"\n")
print("Table is a Magic Square: ", bal.isMagicSquare(table), "\n")
isBalanced = bal.checkBalance(table, blocks, size)
print("Table is balanced: ", isBalanced, "\n")
if (argv[0] == "-r"):
print("Randomizing Table: -------------------------------------")
table = randomizeTable(table, blocks, size)
print("\n",np.matrix(table),"\n")
isBalanced = bal.checkBalance(table, blocks, size)
while (not isBalanced):
table = randomizeTable(table, blocks, size)
isBalanced = bal.checkBalance(table, blocks, size)
print("Table is balanced: ", isBalanced, "\n")
else:
print("Creating odd magic square:")
table = bal.generateSquare(size)
print("\n",np.matrix(table),"\n")
print("Table is a Magic Square: ", bal.isMagicSquare(table), "\n")
isBalanced = bal.checkBalance(table, blocks, size)
print("Table is balanced: ", isBalanced, "\n")
if (argv[0] == "-r"):
print("Randomizing Table: -------------------------------------")
table = randomizeTable(table, blocks, size)
print("\n",np.matrix(table),"\n")
isBalanced = bal.checkBalance(table, blocks, size)
while (not isBalanced):
table = randomizeTable(table, blocks, size)
isBalanced = bal.checkBalance(table, blocks, size)
print("Table is balanced: ", isBalanced, "\n")
else:
print("Table must be greater than or equal to 4x4")
except ValueError:
print("That's not an integer!")
# end main method
# Executes the main function
if __name__ == '__main__':
main()
<file_sep>import numpy as np
import math as math
# checks the center of gravity (cog) of a table by computing it's cog in the x and y dimensions
# calculations start with the origin at the bottom left of a table (0,0)
def checkBalance(table, blocks, size):
totalMass = sum(blocks) # total weight of all the blocks
xLoc = 0.5
yLoc = size - 0.5
momentTableX = [[0] * (size) for _ in range(size)] # table of moments in the x dimension
momentTableY = [[0] * (size) for _ in range(size)] # table of moments in the y dimension
perfectBalanceX = size/2
perfectBalanceY = size/2
# determine the safe zone for the table
# 2x2 for even, 4x4 for odd
if (size % 2 == 0):
topLeft = [size/2 - 1, size/2 + 1]
topRight = [size/2 + 1, size/2 + 1]
bottomLeft = [size/2 - 1, size/2 - 1]
bottomRight = [size/2 + 1, size/2 - 1]
safeZone = [topLeft, topRight, bottomLeft, bottomRight]
print("Safe Zone: ", safeZone, "\n")
else:
topLeft = [size/2 - 2, size/2 + 2]
topRight = [size/2 + 2, size/2 + 2]
bottomLeft = [size/2 - 2, size/2 - 2]
bottomRight = [size/2 + 2, size/2 - 2]
safeZone = [topLeft, topRight, bottomLeft, bottomRight]
print("Safe Zone: ", safeZone, "\n")
# determine x center of gravity
for x in range(size):
for y in range(size):
momentTableX[x][y] = table[x][y] * xLoc
xLoc = xLoc + 1
xLoc = 0.5
momentsX = np.sum(momentTableX)
cogX = momentsX/totalMass
print("Center of Gravity X: ", cogX)
# determine y center of gravity
for x in range(size):
for y in range(size):
momentTableY[y][x] = table[y][x] * yLoc
yLoc = yLoc - 1
yLoc = size - 0.5
momentsY = np.sum(momentTableY)
cogY = momentsY/totalMass
print("Center of Gravity Y: ", cogY, "\n")
if (cogX < topLeft[0] or cogX > topRight[0]):
return False
elif (cogY < bottomLeft[1] or cogY > topLeft[1]):
return False
else:
return True
# This method tests a grid to see if it is a magic square
# Rows, columns, and diagonals must equal the same number, the magic constant
# Returns True or False
def isMagicSquare(grid):
magic = True
n = np.size(grid, 0)
magicConstant = n * ((math.pow(n, 2) + 1)) / 2 # n[(n^2+1)/2], formula to find the magic constant
# check rows
for x, row in enumerate(grid):
if sum(row) != magicConstant:
magic = False
return magic
# check columns
gridT = np.transpose(grid)
for y, column in enumerate(gridT):
if sum(column) != magicConstant:
magic = False
return magic
# check diagonals
total = 0
for x in range(0, n, 1):
element = grid[x][x]
total = total + element
if total != magicConstant: magic = False
y = 0
total = 0
for x in range(n-1, -1, -1):
element = grid[x][y]
total = total + element
y = y + 1
if total != magicConstant: magic = False
return magic
# This method tests the isMagicSquare method
# first grid is a magic square, second grid is not
def testMagicSquare():
test = [[4, 9, 2],
[3, 5, 7],
[8, 1, 6]]
print(np.matrix(test))
print(isMagicSquare(test));
test2 = [[2, 9, 2],
[3, 3, 7],
[8, 1, 7]]
print(np.matrix(test2))
print(isMagicSquare(test2));
# end testMagicSquare method
#to print magic square of double order
def doublyEven(n):
# 2-D matrix with all entries as 0
table = [[(n*y)+x+1 for x in range(n)]for y in range(n)]
# Change value of array elements at fix location
# as per the rule (n*n+1)-arr[i][[j]
# Corners of order (n/4)*(n/4)
# Top left corner
for i in range(0,n//4):
for j in range(0,n//4):
table[i][j] = (n*n + 1) - table[i][j];
# Top right corner
for i in range(0,n//4):
for j in range(3 * (n//4),n):
table[i][j] = (n*n + 1) - table[i][j];
# Bottom Left corner
for i in range(3 * (n//4),n):
for j in range(0,n//4):
table[i][j] = (n*n + 1) - table[i][j];
# Bottom Right corner
for i in range(3 * (n//4),n):
for j in range(3 * (n//4),n):
table[i][j] = (n*n + 1) - table[i][j];
# Centre of matrix,order (n/2)*(n/2)
for i in range(n//4,3 * (n//4)):
for j in range(n//4,3 * (n//4)):
table[i][j] = (n*n + 1) - table[i][j];
return table
#end doublyEven
# odd sized magic squares
def generateSquare(n):
# 2-D array with all
# slots set to 0
table = [[0 for x in range(n)]
for y in range(n)]
# initialize position of 1
i = n / 2
j = n - 1
# Fill the magic square
# by placing values
num = 1
while num <= (n * n):
if i == -1 and j == n: # 3rd condition
j = n - 2
i = 0
else:
# next number goes out of
# right side of square
if j == n:
j = 0
# next number goes
# out of upper side
if i < 0:
i = n - 1
if table[int(i)][int(j)]: # 2nd condition
j = j - 2
i = i + 1
continue
else:
table[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1 # 1st condition
return table
#end of odd-magic square
# start of the singly even function
#msut build an odd magic square first
def build_odd(n):
if n % 2 == 0:
n += 1
table = [[0 for j in range(n)] for i in range(n)]
p = 1
i = n // 2
j = 0
while p <= (n * n):
table[i][j] = p
ti = i + 1
if ti >= n: ti = 0
tj = j - 1
if tj < 0: tj = n - 1
if table[ti][tj] != 0:
ti = i
tj = j + 1
i = ti
j = tj
p = p + 1
return table, n
# build singly even magic square
def build_sems(n):
if n % 2 == 1:
n += 1
while n % 4 == 0:
n += 2
table = [[0 for j in range(n)] for i in range(n)]
z = n // 2
b = z * z
c = 2 * b
d = 3 * b
o = build_odd(z)
for j in range(0, z):
for i in range(0, z):
a = o[0][i][j]
table[i][j] = a
table[i + z][j + z] = a + b
table[i + z][j] = a + c
table[i][j + z] = a + d
lc = z // 2
rc = lc
for j in range(0, z):
for i in range(0, n):
if i < lc or i > n - rc or (i == lc and j == lc):
if not (i == 0 and j == lc):
t = table[i][j]
table[i][j] = table[i][j + z]
table[i][j + z] = t
return table
| 543ca6d7ff386e1547266f9ba2acb0278f368973 | [
"Python"
] | 2 | Python | jjpellegr/balance_table | 7787cb6ccd68455888f85df86752393e26d339a5 | cde3344b77e588297a187e38e9b8f998cd5c3ea2 | |
refs/heads/master | <repo_name>SamMitchell153/Pathfinding-Visualizer<file_sep>/src/PathfindingVisualizer/RangeSlider.jsx
import React, { Component } from "react";
import Slider from "react-rangeslider";
import { Col, Row } from "react-bootstrap";
class Horizontal extends Component {
constructor(props, context) {
super(props, context);
this.state = {
value: 30
};
}
handleChange = value => {
this.setState({
value: value
});
this.props.callbackFromParent(value);
};
render() {
let { value } = this.state;
return (
<Row className="slider">
<Col id="xValueLabel" xs="1">
{value}
</Col>
<Col className="slider" xs="11">
<Slider
min={10}
max={100}
value={value}
onChange={this.handleChange}
/>
</Col>
</Row>
);
}
}
class Vertical extends Component {
constructor(props, context) {
super(props, context);
this.state = {
value: 25
};
}
handleChange = value => {
this.setState({
value: value
});
this.props.callbackFromParent(value);
};
render() {
const { value } = this.state;
return (
<div className="slider orientation-reversed">
<div className="slider-vertical">
<div id="yValueLabel">{value}</div>
<Slider
min={10}
max={50}
value={value}
orientation="vertical"
reverse={true}
onChange={this.handleChange}
/>
</div>
</div>
);
}
}
export { Horizontal, Vertical };
| e94561c7845be2706257642fd20e64123e91655e | [
"JavaScript"
] | 1 | JavaScript | SamMitchell153/Pathfinding-Visualizer | 630a2c817e9989b1423834ec0c8b9e105812d853 | b366c39ca54fa31c467fd89282db1d84c4a0d21d | |
refs/heads/master | <file_sep>import React from 'react';
import {withRouter} from 'react-router';
import {connect} from 'react-redux';
import {getMovieDetail} from '../redux/actions';
import {Movie} from '../components/Movie';
import {Content} from '../components/Content';
import { findMovieDirector, getAllDirectedMovies } from '../client/api/helpers';
export class MoviePage extends React.Component {
constructor(props) {
super(props);
this.goSearch = this.goSearch.bind(this);
this.loadMovie = this.loadMovie.bind(this);
if (this.props.match.params.title) {
this.loadMovie(this.props.match.params.title);
}
}
loadMovie(title) {
if (title) {
let [id, ...junk] = title.split('-');
this.props.getDetail(id);
}
}
goSearch(e) {
e.preventDefault();
this.props.history.push('/search');
}
componentWillUpdate(nextProps) {
if (nextProps.match.params.title !== this.props.match.params.title) {
this.loadMovie(nextProps.match.params.title);
}
}
componentDidUpdate() {
window.scrollTo(0, 0);
}
render() {
return (
<div>
<Movie movie={this.props.movie} goSearch={this.goSearch}/>
<div>Films by {findMovieDirector(this.props.movie).name}</div>
<Content movies={getAllDirectedMovies(this.props.director)}/>
</div>
)
}
}
const mapStateToProps = state => ({
movie: state.movie,
director: state.director
});
const mapDispatchToProps = dispatch => ({
getDetail: (id) => dispatch(getMovieDetail(id, dispatch))
});
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(MoviePage));
<file_sep>import {
MOVIES_FETCH_SUCCESS,
MOVIES_FETCH_FAILURE,
MOVIES_SORT_CHANGE,
MOVIE_FETCH_SUCCESS,
MOVIE_FETCH_FAILURE,
DIRECTOR_INFO_FETCH_SUCCESS,
DIRECTOR_INFO_FETCH_FAILURE,
QUERY_SET,
QUERY_SET_TYPE
} from './types';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const initialState = {
movie: {
credits: {
crew: []
},
genres: []
},
id: 1,
director: {
movie_credits: {
crew: []
}
},
movies: [],
selectedSearchType: 'title',
query: '',
oldValue: ''
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case MOVIE_FETCH_SUCCESS:
return {
...state,
id: action.payload.id,
movie: action.payload.result
};
case MOVIE_FETCH_FAILURE: {
console.warn(action.payload);
return {...state};
}
case MOVIES_FETCH_SUCCESS:
return {
...state,
query: action.payload.query,
movies: action.payload.results,
};
case MOVIES_FETCH_FAILURE: {
console.warn(action.payload);
return {...state};
}
case DIRECTOR_INFO_FETCH_SUCCESS:
return {
...state,
director: action.payload.result
};
case DIRECTOR_INFO_FETCH_FAILURE: {
console.warn(action.payload);
return {...state};
}
case MOVIES_SORT_CHANGE:
return {
...state,
sortType: action.payload,
movies: state.results,
};
case QUERY_SET:
return {
...state,
query: action.payload.query,
oldValue: action.payload.oldQuery
};
case QUERY_SET_TYPE:
return {
...state,
selectedSearchType: action.payload
};
default:
return state;
}
};
function createStoreInstance(initialState) {
let store;
store = createStore(reducer, initialState, applyMiddleware(thunk));
return store;
}
export {
initialState,
createStoreInstance
}
<file_sep>const Movies = [{
id: 1,
title: 'Pulp Fiction',
picture: {
source: 'https://cdn.miramax.com/media/assets/Pulp-Fiction1.png',
alt: 'pulp fiction'
},
description: '<NAME> (<NAME>) and <NAME> (<NAME>) are two hit men who are out to retrieve a suitcase stolen from their employer, mob boss <NAME> (Ving Rhames). Wallace has also asked Vincent to take his wife Mia (<NAME>) out a few days later when Wallace himself will be out of town. <NAME> (<NAME>) is an aging boxer who is paid by Wallace to lose his fight. The lives of these seemingly unrelated people are woven together comprising of a series of funny, bizarre and uncalled-for incidents.',
year: 1994,
rating: 4.1,
duration: 140,
director: ' <NAME>',
cast: ['<NAME>', 'Uma', '<NAME>'],
category: 'Oscar'
},
{
id: 2,
title: 'Kill Bill 1',
picture: {
source: 'https://i.pinimg.com/originals/64/82/ef/6482ef51ce0b437986ec477e0d46f30c.jpg',
alt: 'pulp fiction'
},
description: '<NAME> (<NAME>) and <NAME> (<NAME>) are two hit men who are out to retrieve a suitcase stolen from their employer, mob boss <NAME> (Ving Rhames). Wallace has also asked Vincent to take his wife Mia (<NAME>) out a few days later when Wallace himself will be out of town. <NAME> (<NAME>) is an aging boxer who is paid by Wallace to lose his fight. The lives of these seemingly unrelated people are woven together comprising of a series of funny, bizarre and uncalled-for incidents.',
year: 1994,
rating: 4.1,
duration: 140,
director: ' <NAME>',
cast: ['<NAME>', 'Uma', '<NAME>'],
category: 'Oscar'
},
{
id: 3,
title: 'KIll Bill 2',
picture: {
source: 'https://i.pinimg.com/736x/ed/88/0e/ed880e84030cca6cc7f4d9a74b5ee825--cult-movies-quentin-tarantino.jpg',
alt: 'pulp fiction'
},
description: '<NAME> (<NAME>) and <NAME> (<NAME>) are two hit men who are out to retrieve a suitcase stolen from their employer, mob boss <NAME> (Ving Rhames). Wallace has also asked Vincent to take his wife Mia (<NAME>) out a few days later when Wallace himself will be out of town. <NAME> (<NAME>) is an aging boxer who is paid by Wallace to lose his fight. The lives of these seemingly unrelated people are woven together comprising of a series of funny, bizarre and uncalled-for incidents.',
year: 1994,
rating: 4.1,
duration: 140,
director: ' <NAME>',
cast: ['<NAME>', 'Uma', '<NAME>'],
category: 'Oscar'
}];
export default Movies<file_sep>import React from 'react';
import {shallow} from 'enzyme';
import {MoviePage} from '../MoviePage';
describe('<MoviePage />', () => {
test('should render without throwing error', () => {
const page = shallow(
<MoviePage
director={{movie_credits: {crew:[]}}}
movie={{credits: {crew:[]}}}
history={{}}
match={{params: {}}}
/>
);
expect(page.find('Movie').length).toBe(1);
expect(page.find('Content').length).toBe(1);
});
test('should handle Search btn click', () => {
let mockedPush = jest.fn();
const page = shallow(
<MoviePage
director={{movie_credits: {crew:[]}}}
movie={{credits: {crew:[]}}}
history={{push: mockedPush}}
match={{params: {}}}
/>
);
page.instance().goSearch({preventDefault: () => {}});
expect(mockedPush).toHaveBeenCalledWith('/search');
});
});<file_sep>import React from 'react';
import {Route, Switch} from 'react-router-dom';
import SearchPage from './pages/SearchPage';
import MoviePage from './pages/MoviePage';
import IndexPage from './pages/IndexPage';
export default () => (
<Switch>
<Route exact path="/" component={IndexPage}/>
<Route path="/search/:query" component={SearchPage}/>
<Route path="/search/" component={SearchPage}/>
<Route path="/movie/:title" component={MoviePage}/>
</Switch>
);
<file_sep>import React from 'react';
import { findMovieDirector, findMovieCast, getMovieGenres } from '../client/api/helpers';
export const Movie = (props) => (
<div className="info-wrapper">
<button onClick={props.goSearch}>Search</button>
<div className="row">
<img src={'https://image.tmdb.org/t/p/w300' + props.movie.poster_path} alt={props.movie.title}/>
<div>
<h1>{props.movie.title}</h1>
<div>{props.movie.vote_average}</div>
<div>{getMovieGenres(props.movie)}</div>
<div><span>{props.movie.release_date}</span> | <span>{props.movie.duration | 'Inf'} min</span></div>
<p>{props.movie.overview}</p>
<div>Director: {findMovieDirector(props.movie).name}</div>
<div>Cast: {findMovieCast(props.movie).name}</div>
</div>
</div>
</div>
);
<file_sep>import {
MOVIES_FETCH,
MOVIES_FETCH_FAILURE,
MOVIES_FETCH_SUCCESS,
MOVIE_FETCH_FAILURE,
MOVIE_FETCH,
MOVIE_FETCH_SUCCESS,
QUERY_SET,
QUERY_SET_TYPE,
DIRECTOR_INFO_FETCH,
DIRECTOR_INFO_FETCH_SUCCESS,
DIRECTOR_INFO_FETCH_FAILURE
} from './types';
import axios from 'axios';
import * as moviedb from '../client/api/moviedb';
import { findMovieDirector, getAllDirectedMovies } from '../client/api/helpers';
export function doSearch(query, selectedSearchType, dispatch) {
dispatch({type: MOVIES_FETCH});
let isByTitle = selectedSearchType.trim() === 'title';
if (isByTitle) {
return () => axios
.get(moviedb.getSearchMovieUrl(query))
.then(res => {
dispatch(moviesFetchSuccess(res.data.results, query));
})
.catch(err => {
console.trace(err);
dispatch(moviesFetchFailure(err.message || 'Can\'t load results'))
});
} else {
return () => axios
.get(moviedb.getSearchPersonUrl(query))
.then(({data: {results: persons}}) => {
axios
.get(moviedb.getPersonDetailUrl(persons[0].id, ['movie_credits']))
.then(({data: director}) => {
dispatch(moviesFetchSuccess(getAllDirectedMovies(director), query));
})
})
.catch(err => {
console.trace(err);
dispatch(moviesFetchFailure(err.message || 'Can\'t load results'))
});
}
}
function moviesFetchSuccess(results, query) {
return {
type: MOVIES_FETCH_SUCCESS,
payload: {results, query}
}
}
function moviesFetchFailure(message) {
return {
type: MOVIES_FETCH_FAILURE,
payload: message
}
}
export function getMovieDetail(id, dispatch) {
dispatch({type: MOVIE_FETCH});
return () => axios
.get(moviedb.getMovieDetailUrl(id, ['credits']))
.then(({data: movie}) => {
let director = findMovieDirector(movie);
dispatch(movieFetchSuccess(movie, id));
if (director.id) {
dispatch(getDirectorInfo(director.id, dispatch));
}
})
.catch(err => {
console.trace(err);
dispatch(movieFetchFailure(err.message || 'Can\'t load results'))
});
}
function movieFetchSuccess(result, id) {
return {
type: MOVIE_FETCH_SUCCESS,
payload: {result, id}
}
}
function movieFetchFailure(message) {
return {
type: MOVIE_FETCH_FAILURE,
payload: message
}
}
export function getDirectorInfo(id, dispatch) {
dispatch({type: DIRECTOR_INFO_FETCH});
return () => axios
.get(moviedb.getPersonDetailUrl(id, ['movie_credits']))
.then(({data: director}) => {
dispatch(directorInfoFetchSuccess(director, id));
})
.catch(err => {
console.trace(err);
dispatch(directorInfoFetchFailure(err.message || 'Can\'t load results'))
});
}
function directorInfoFetchSuccess(result, id) {
return {
type: DIRECTOR_INFO_FETCH_SUCCESS,
payload: {result, id}
}
}
function directorInfoFetchFailure(message) {
return {
type: DIRECTOR_INFO_FETCH_FAILURE,
payload: message
}
}
export function setQuery(query, oldQuery) {
return {
type: QUERY_SET,
payload: {query, oldQuery}
};
}
export function setSearchType(selectedSearchType) {
return {
type: QUERY_SET_TYPE,
payload: selectedSearchType
};
}
<file_sep>const BASE_URL = 'https://api.themoviedb.org';
const VERSION = '3';
const MOVIE_DETAIL_ENDPOINT = 'movie';
const MOVIE_CREDITS_PART = 'credits';
const PERSON_DETAIL_ENDPOINT = 'person';
const PERSON_MOVIE_CREDITS_PART = 'movie_credits';
const SEARCH_MOVIE_ENDPOINT = 'search/movie';
const SEARCH_PERSON_ENDPOINT = 'search/person';
const BASE_PARAMS = {
api_key: '172283afd6dcc9211e5e1ee68cca7767',
language: 'en-US'
};
let stringify = function stringify(params) {
throw '=(';
};
if (process) {
stringify = function stringify(params) {
return require('querystring').stringify(params);
};
} else if (window) {
stringify = function stringify(params) {
return new URLSearchParams(params).toString();
};
}
const MOVIE_DETAIL_URL = `${BASE_URL}/${VERSION}/${MOVIE_DETAIL_ENDPOINT}`;
const PERSON_DETAIL_URL = `${BASE_URL}/${VERSION}/${PERSON_DETAIL_ENDPOINT}`;
const SEARCH_MOVIE_URL = `${BASE_URL}/${VERSION}/${SEARCH_MOVIE_ENDPOINT}`;
const SEARCH_PERSON_URL = `${BASE_URL}/${VERSION}/${SEARCH_PERSON_ENDPOINT}`;
function getUrlWithQuery(base, query) {
return `${base}?${stringify({...BASE_PARAMS, query})}`;
}
function getUrlWithIdAndAdditions(base, id, additions) {
let params = additions.length ? {...BASE_PARAMS, append_to_response: additions.join(',')} : {...BASE_PARAMS};
return `${base}/${id}?${stringify(params)}`;
}
export function getMovieDetailUrl(id, additions = []) {
return getUrlWithIdAndAdditions(MOVIE_DETAIL_URL, id, additions);
}
export function getPersonDetailUrl(id, additions = []) {
return getUrlWithIdAndAdditions(PERSON_DETAIL_URL, id, additions);
}
export function getSearchMovieUrl(query) {
return getUrlWithQuery(SEARCH_MOVIE_URL, query);
}
export function getSearchPersonUrl(query) {
return getUrlWithQuery(SEARCH_PERSON_URL, query);
}
<file_sep>import React from 'react';
export default class Search extends React.Component {
render() {
return (
<div>
<form onSubmit={this.props.onSubmit} className="search-form">
<label htmlFor="search-field">Find your movie</label>
<input type="text" name="search-field" id="search-field" value={this.props.query} onChange={this.props.onChange}/>
<span>Search by</span>
<input type="radio"
name="searchType"
id="title"
value="title"
checked={this.props.selectedSearchType === 'title'}
onChange={this.props.onSearchTypeChange}/>
<label htmlFor="title">Title</label>
<input type="radio"
name="searchType"
id="director"
value="director"
checked={this.props.selectedSearchType === 'director'}
onChange={this.props.onSearchTypeChange}/>
<label htmlFor="director">Director</label>
<input type="submit" value="Submit"/>
</form>
</div>
);
}
}
<file_sep>export const QUERY_SET = 'QUERY_SET';
export const QUERY_SET_TYPE = 'QUERY_SET_TYPE';
export const MOVIES_FETCH = 'MOVIES_FETCH';
export const MOVIES_FETCH_SUCCESS = 'MOVIES_FETCH_SUCCESS';
export const MOVIES_FETCH_FAILURE = 'MOVIES_FETCH_FAILURE';
export const MOVIES_SORT_CHANGE = 'MOVIES_SORT_CHANGE';
export const MOVIE_FETCH = 'MOVIE_FETCH';
export const MOVIE_FETCH_SUCCESS = 'MOVIE_FETCH_SUCCESS';
export const MOVIE_FETCH_FAILURE = 'MOVIE_FETCH_FAILURE';
export const DIRECTOR_INFO_FETCH = 'DIRECTOR_INFO_FETCH';
export const DIRECTOR_INFO_FETCH_SUCCESS = 'DIRECTOR_INFO_FETCH_SUCCESS';
export const DIRECTOR_INFO_FETCH_FAILURE = 'DIRECTOR_INFO_FETCH_FAILURE';
<file_sep>import Express from 'express';
import React from 'react';
import {renderToString} from 'react-dom/server';
import {StaticRouter} from 'react-router-dom';
import {createStoreInstance, initialState} from '../redux/store';
import {MyApp} from '../client/app';
import routes from '../routes';
const app = Express();
const port = 4300;
//Serve static files
app.use(Express.static('./'));
// This is fired every time the server side receives a request
app.use(handleRender);
function handleRender(req, res) {
const store = createStoreInstance(initialState);
const context = {};
const app = (
<StaticRouter location={req.url} context={context}>
<MyApp store={store}>
{routes()}
</MyApp>
</StaticRouter>);
const html = renderToString(app);
// Send the rendered page back to the client
res.send(renderFullPage(html, initialState))
}
function renderFullPage(html, preloadedState = {}) {
return `
<!DOCTYPE html>
<html>
<head>
<title>Redux Universal Example</title>
<meta charset="utf-8">
<base href="/">
<link href="styles.css" rel="stylesheet"></head>
<body>
<div class="app-wrapper" id="app">${html}</div>
<script>
window.PRELOADED_STATE = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
</script>
<script type="text/javascript" src="client.js"></script><script type="text/javascript" src="styles.js"></script></body>
</html>`
}
app.listen(port);
| 76d92323519fd0cf095b953f314b6c70c6664a43 | [
"JavaScript"
] | 11 | JavaScript | y-bobrovskaya/react-mentoring | 39f48f6daf0d5afce200d63df2aeb1668a5ee23e | f09787516fa99e03e68b78cf40aeeb37ed5e16a3 | |
refs/heads/master | <repo_name>steffmeister/phpircbot<file_sep>/module_klo.php
<?php
/* module_klo, a klo geh vs meetings counter */
function klo_init() {
irc_bot_echo("init klo_module");
klo_reset_counter();
ircbot_register_for_global_listening( 'klo_listener_global' );
}
function klo_command( $string, $target='', $private=0 ) {
irc_bot_echo("klo_command($string)");
$user='';
$input = explode(' ', $string);
$string=$input[0];
switch ( $string ) {
case 'reset':
$user = isset($input[1]) ? $input[1] : 'all' ;
klo_reset_counter($user);
irc_send_message( "Zähler zurückgesetzt.", $target, $private );
break;
case 'show':
$user = isset($input[1]) ? $input[1] : 'all' ;
klo_print_stats($user, $target, $private );
break;
case 'k++':
case 'klo+1':
klo_increase_counter( 'k' , $target);
klo_print_stats( 'all' , $target, $private );
break;
case 'm++':
case 'mtg+1':
klo_increase_counter( 'm' , $target);
klo_print_stats( 'all', $target, $private );
break;
case 'help':
case 'man':
default:
klo_print_help( $target, $private );
}
}
/*
interpret messages from chat and count klos or meetings
*/
function klo_listener_global( $sender, $msg ) {
if ( preg_match( '/[kK]lo/', $msg ) ) {
klo_increase_counter( 'k', $sender );
}
if ( preg_match( '/[mM]eeting/', $msg ) ) {
klo_increase_counter( 'm', $sender );
}
}
/*
reset all individual counters
*/
function klo_reset_counter($user='all') {
irc_bot_echo("reset all counters");
if ($user === 'all') {
foreach ( $GLOBALS['counter'] as $key => $value ) {
foreach ( $value as $k => $v ) {
$GLOBALS['counter'][$key][$k] = 0;
}
}
} else {
foreach ( $GLOBALS['counter'] as $key => $value ) {
$GLOBALS['counter'][$key][$user] = 0;
}
}
}
/*
increase individual counter
*/
function klo_increase_counter( $what , $who ) {
$GLOBALS['counter'][$what][$who]++;
}
/*
print stats for all or for specific user
*/
function klo_print_stats( $user='all', $target='', $private=0 ) {
irc_send_message( "Stats for $user:", $target, $private );
if ( $user==='all' ) {
$all_counts=array();
// count all klos and meetings
foreach ( $GLOBALS['counter'] as $key => $value ) {
foreach ( $value as $k => $v ) {
$all_counts[$key]+=$v;
}
}
irc_send_message( "Klo ".$all_counts['k']." : ".$all_counts['m']." Meetings", $target, $private );
}else {
irc_send_message( "Klo ".$GLOBALS['counter']['k'][$user]." : ".$GLOBALS['counter']['m'][$user]." Meetings", $target, $private );
}
}
/*
print available commands
*/
function klo_print_help( $target='', $private=0 ) {
$usage = array(
"#wtf is it?",
"Scans stream for \"klo\" or \"meeting\" and counts how much shit gets produced.",
"#Commands:",
"reset - reset ALL the counters",
"show [user] - show the current stats for [user]; default is 'all'",
"klo+1,k++ - increase your klo count",
"mtg+1,m++ - increase your meeting count",
"help - show this message",
);
foreach ( $usage as $key => $value ) {
irc_send_message( $value, $target, $private );
}
}
?>
<file_sep>/module_numbergame.php
<?php
/* module_demo, some tests */
$current_game = array();
function numbergame_init() {
irc_bot_echo("numbergame_init module");
ircbot_register_command('ng', 'ng_custom');
ircbot_register_for_global_listening('ng_listener_global');
}
function numbergame_command($string, $target='', $private=0) {
irc_send_message('default command handler', $target, $private);
}
function ng_custom($string, $target='', $private=0) {
global $current_game;
switch($string) {
case 'new':
$current_game['running'] = 1;
$current_game['number'] = rand(1, 10);
//irc_send_message('nummer:'. $current_game['number'], $target, 0);
irc_send_message('Los gehts! Erratet die Nummer, 1-10!'.$score, $sender, 0);
irc_bot_echo("Nummer ist ".$current_game['number']);
break;
case 'stop':
$current_game['running'] = 0;
break;
case 'reset':
$current_game['scores'] = array();
break;
case 'scores':
foreach($current_game['scores'] as $nick=>$score) {
irc_send_message($nick.': '.$score, $sender, 0);
}
break;
}
//irc_send_message('registered command handler', $target, $private);
}
function ng_listener_global($sender, $msg) {
global $current_game;
if ($current_game['running']) {
if (is_numeric($msg)) {
if ($msg == $current_game['number']) {
$current_game['running'] = 0;
if (!isset($current_game['scores'][$sender])) {
$current_game['scores'][$sender] = 0;
}
$current_game['scores'][$sender]++;
irc_send_message($sender.' hat die richtige Nummer erraten: '.$current_game['number'].'!', $sender, 0);
irc_bot_echo("Nummer erraten");
}
}
}
}
?>
<file_sep>/module_pyload.php
<?php
/* module_pyload */
/* name of the python executable */
define('PYTHON', 'python2.5');
/* directory of pyload */
define('PYLOAD_PATH', '/share/MD0_DATA/.qpkg/pyload/');
/* my admin users */
define('MODULE_ADMINS', 'steffmeister');
/* temporary file - no need to change */
define('TEMP_FILE', 'ircpyload.tmp');
$module_admins = array();
$config_status = true;
function pyload_init() {
global $module_admins, $config_status;
echo "\npyload_init module\n";
$config_status = true;
if (!file_exists(PYLOAD_PATH.'pyLoadCli.py')) {
echo "pyLoadCli.py not found!!\n";
$config_status = false;
}
$module_admins = explode(',', MODULE_ADMINS);
}
function pyload_command($string, $target='', $private=0) {
global $module_admins, $config_status;
$ok = false;
echo "my admins are\n";
print_r($module_admins);
foreach($module_admins as $username) {
echo "Comparing $username with $target...\n";
if ($username == $target) $ok = true;
}
if (!$ok) {
irc_send_message('Access denied.', $target, $private);
return false;
}
if (!$config_status) {
irc_send_message('Configuration error.', $target, $private);
return false;
}
//irc_send_message('default command handler', $target, $private);
if (strpos($string, ' ') !== false) {
$param = substr($string, strpos($string, ' ')+1);
$string = substr($string, 0, strpos($string, ' '));
echo "param: '$param'\n";
echo "cmd: '$string'\n";
}
switch($string) {
case 'add':
if ($param != '') {
if (preg_match('~^(http|ftp)(s)?\:\/\/((([a-z0-9\-]*)(\.))+[a-z0-9]*)($|/.*$)~i', $param)) {
exec(PYTHON.' '.PYLOAD_PATH.'pyLoadCli.py add ircbotpyload '.$param.' > '.TEMP_FILE);
if (send_temp_file($target, $private) == '') {
irc_send_message('Added.', $target, $private);
}
} else {
irc_send_message('Does not look like a valid URL.', $target, $private);
}
} else {
irc_send_message('Parameter missing.', $target, $private);
}
break;
case 'status':
exec(PYTHON.' '.PYLOAD_PATH.'pyLoadCli.py status > '.TEMP_FILE);
send_temp_file($target, $private);
break;
}
}
function send_temp_file($target, $private) {
$content = '';
if (file_exists(TEMP_FILE)) {
$fh = fopen(TEMP_FILE, 'r');
if ($fh !== false) {
while(!feof($fh)) {
$line = fgets($fh);
$content .= $line;
irc_send_message($line, $target, $private);
}
}
fclose($fh);
unlink(TEMP_FILE);
}
return $content;
}
?>
<file_sep>/module_demo.php
<?php
/* module_demo, some tests */
/* each module needs an *_init() function
use it to set up variables and such stuff */
function demo_init() {
echo "\ndemo_init module";
/* this will register a custom command */
ircbot_register_command('dm', 'dm_custom');
/* register a callback which is called when someone writes on the channel */
ircbot_register_for_global_listening('dm_listener_global');
/* register a callbick which is called when a private message is received */
ircbot_register_for_private_listening('dm_listener_private');
}
/* this function is also required by every module */
function demo_command($string, $target='', $private=0) {
irc_send_message('default command handler', $target, $private);
}
/* our custom command callback, target is the sender, eg the channel or a username */
/* private means if the message was received privately */
function dm_custom($string, $target='', $private=0) {
irc_send_message('registered command handler', $target, $private);
}
/* our global message callback */
function dm_listener_global($sender, $msg) {
irc_send_message('global handler', $sender, 0);
}
/* our private message callback */
function dm_listener_private($sender, $msg) {
irc_send_message('private handler', $sender, 1);
}
?>
<file_sep>/startbot.sh
#!/bin/sh
# this will launch the bot
# if the exit code of the bot is 3, we will pull the code from github
# and restart again
# check if php command exists
command -v php >/dev/null && continue || { echo "php-cli not found! Please install!"; exit 5; }
# main loop
quit=0
while [ $quit -eq 0 ]
do
php phpircbot.php > bot.log
returncode=$?
if [ $returncode = "3" ]
then
git pull
else
quit=1
fi
done
echo "Exiting, code: $returncode"
exit $returncode
<file_sep>/module_magicball.php
<?php
/* module_magicball, magic 8 ball */
$answers = array();
function magicball_init() {
irc_bot_echo("magicball_init module");
/* answers were shamelessly copied from wikipedia */
global $answers;
$answers[] = 'It is certain';
$answers[] = 'It is decidedly so';
$answers[] = 'Without a doubt';
$answers[] = 'Yes – definitely';
$answers[] = 'You may rely on it';
$answers[] = 'As I see it, yes';
$answers[] = 'Most likely';
$answers[] = 'Outlook good';
$answers[] = 'Yes';
$answers[] = 'Signs point to yes';
$answers[] = 'Reply hazy, try again';
$answers[] = 'Ask again later';
$answers[] = 'Better not tell you now';
$answers[] = 'Cannot predict now';
$answers[] = 'Concentrate and ask again';
$answers[] = 'Don\'t count on it';
$answers[] = 'My reply is no';
$answers[] = 'My sources say no';
$answers[] = 'Outlook not so good';
$answers[] = 'Very doubtful';
}
function magicball_command($string, $target='', $private) {
global $answers;
$send_answer = rand(0, count($answers)-1);
irc_send_message($answers[$send_answer].'.', $target, $private);
}
?>
<file_sep>/phpircbot.php
<?php
/* check if config file exists */
if (!file_exists('phpircbot.conf.php')){
echo "No config found, please read the README!\n";
exit(4);
}
/* remember start time */
$start_time = time();
/* load phpircbot.conf.php */
require('phpircbot.conf.php');
/* internal constants */
define('IRCBOT_VERSION', '0.1');
define('USER_SHUTDOWN', '1');
define('CONNECTION_LOST', '2');
define('USER_RESTART', '3');
define('CONFIG_NOT_FOUND', '4');
/* quiet mode, disable output */
$quiet_mode = false;
/* convert admin users to array */
$admin_users = explode(',', IRC_ADMIN_USERS);
/* registered commands */
$commands = array();
/* listener */
$msg_listener_global = array();
$msg_listener_private = array();
/* global modules array, contains loaded modules */
$modules = array();
/* auto load modules */
$autoload_modules = explode(',', AUTOLOAD_MODULES);
if (count($autoload_modules) > 0) {
foreach($autoload_modules as $module_to_load) {
load_module($module_to_load, '', 1);
}
}
/* irc channel users */
$users = array();
/* irc resource handle */
$irc_res = false;
/* counter for connection failures */
$connection_failure = 0;
$main_quit = 0;
while(!$main_quit) {
/* main loop, interpret data sent from irc host */
$nick = IRC_NICK;
$channels = explode(',', IRC_CHANNEL);
$irc_res = irc_host_connect();
if ($irc_res == false) {
irc_bot_echo("Connection failure...");
$connection_failure++;
if ($connection_failure > IRC_HOST_RECONNECT) $main_quit = 1;
sleep(60);
} else {
irc_bot_echo("Connection established...");
$connection_failure = 0;
$quit = 0;
$nicked = 0;
$joined = 0;
$timeouts = 0;
while($quit == 0) {
$line = trim(fgets($irc_res));
$meta_data = stream_get_meta_data($irc_res);
if ($meta_data['timed_out']) {
irc_bot_echo("TIMEOUT");
$timeouts++;
irc_bot_echo("Timeouts: $timeouts");
} else {
$timeouts = 0;
irc_bot_echo("Timeouts: $timeouts");
}
if ( $meta_data['eof']){
irc_bot_echo("EOF");
$quit = 1;
}
irc_bot_echo('IRC: '.$line);
/* after 6 timeouts we reconnect */
if ($timeouts > 6) $quit = CONNECTION_LOST;
/* send our nick */
if ((preg_match ( "/(NOTICE AUTH).*(hostname)/i" , $line) == 1) && (!$nicked)) {
irc_bot_echo('Sending nick...', 0);
irc_send('USER '.$nick.' 0 * :phpircbot '.IRCBOT_VERSION);
irc_send('NICK '.$nick);
irc_bot_echo("ok");
$nicked = 1;
/* nick already in use */
} else if (($nicked) && (strpos($line, ' 433 ') !== false)) {
irc_bot_echo("Nick already in use :(");
irc_bot_echo("what now?!?!");
$nick = $nick.'_';
irc_send('NICK '.$nick);
/* at the end of motd message, join the channel */
} else if ((strpos($line, ' 376 ') !== false) && (!$joined)) {
irc_join_channel(IRC_CHANNEL);
/* ping - pong, kind of keepalive stuff */
} else if (substr($line, 0, 4) == 'PING') {
irc_send(str_replace('PING', 'PONG', $line));
foreach($msg_listener_global as $function) {
call_user_func($function, IRC_CHANNEL, 'PING');
}
/* message interpretation */
} else if (strpos($line, ' PRIVMSG '.$nick.' ') !== false) {
irc_bot_echo("Received private message...");
$sender = substr($line, 1, strpos($line, '!')-1);
irc_bot_echo("From: ".$sender);
$msg = substr($line, strpos($line, ':', 2)+1);
irc_bot_echo("Message: ".$msg);
if (interpret_irc_message($sender, $msg, 1) == false) {
foreach($msg_listener_private as $function) {
call_user_func($function, $sender, $msg);
}
}
/* general messages */
} else if (strpos($line, ' PRIVMSG ') !== false) {
irc_bot_echo("Received message...");
$sender = substr($line, 1, strpos($line, '!')-1);
irc_bot_echo("From: ".$sender);
$msg = substr($line, strpos($line, ':', 2)+1);
irc_bot_echo("Message: ".$msg);
irc_bot_echo("My nick is: ".$nick);
$result = false;
if (strpos($msg, $nick) !== false) {
irc_bot_echo("I was mentioned");
if (substr($msg, 0, strlen($nick)) == $nick) {
$msg = substr($msg, strpos($msg, ' ') + 1);
$result = interpret_irc_message($sender, $msg, 0);
}
}
if ($result == false) {
foreach($msg_listener_global as $function) {
call_user_func($function, $sender, $msg);
}
}
/* kick message */
} else if (strpos($line, ' KICK '.IRC_CHANNEL.' '.$nick) !== false) {
// we were kicked :(
irc_bot_echo("were kicked");
$joined = 0;
sleep(10);
irc_bot_echo("rejoining");
irc_join_channel(IRC_CHANNEL); // rejoin
/* interprete names list */
} else if (strpos($line, ' 353 '.$nick) !== false) {
$names = substr($line, strrpos($line, ':')+1);
$users_temp = explode(' ', $names);
$users = array();
foreach($users_temp as $user) {
if (substr($user, 0, 1) == '@') $user = substr($user, 1);
if ($user != $nick) {
$users[] = $user;
}
}
irc_bot_echo("the users are...");
print_r($users);
/* interpret quit message */
} else if (strpos($line, ' QUIT ') !== false) {
irc_bot_echo("Received quit...");
$sender = substr($line, 1, strpos($line, '!')-1);
irc_bot_echo("From: ".$sender);
$usercounter = 0;
foreach($users as $user) {
if ($user == $sender) unset($users[$usercounter]);
$usercounter++;
}
irc_bot_echo("the users are...");
print_r($users);
/* interpret quit message */
} else if (strpos($line, ' JOIN ') !== false) {
irc_bot_echo("Received join...");
$sender = substr($line, 1, strpos($line, '!')-1);
irc_bot_echo("From: ".$sender);
$users[] = $sender;
irc_bot_echo("the users are...");
print_r($users);
}
//if (feof($irc_res)) $quit = CONNECTION_LOST;
}
/* check what to do now... */
switch($quit) {
/* if we were forced to shutdown */
case USER_SHUTDOWN: $main_quit = 1; break;
case USER_RESTART: $main_quit = 3; break;
/* connection lost */
case CONNECTION_LOST:
default:
sleep(60);
irc_bot_echo("QUIT:$quit");
irc_bot_echo("what next?");
break;
}
/* quit message */
if (($quit == USER_SHUTDOWN) || ($quit == USER_RESTART)) irc_send(':'.IRC_NICK.' QUIT :gotta go, fight club');
/* close connection */
fclose($irc_res);
}
}
exit($main_quit);
/* connect to irc host */
function irc_host_connect() {
//global $res;
/* connect to irc host */
irc_bot_echo('Connecting...', 0);
$res = fsockopen(IRC_HOST, IRC_PORT);
if ($res == false) {
irc_bot_echo("error");
//die();
return false;
}
irc_bot_echo("ok");
return $res;
}
/* join channel */
function irc_join_channel($channel) {
global $joined;
global $nick;
irc_bot_echo('Joining channel...', 0);
irc_send(':'.$nick.' JOIN '.$channel);
irc_bot_echo("ok");
$joined = 1;
}
/* interpret irc messages */
function interpret_irc_message($sender, $msg, $private=0) {
global $quit;
global $nick;
global $commands;
global $modules, $quiet_mode, $start_time;
$cmd = $msg;
$params = '';
if (strpos($msg, ' ') !== false) {
$cmd = substr($msg, 0, strpos($msg, ' '));
$params = substr($msg, strpos($msg, ' ')+1);
}
irc_bot_echo('cmd: \''.$cmd."'");
irc_bot_echo('params: \''.$params."'");
switch($cmd) {
/* show loaded modules */
case 'modules':
if (count($modules) > 0) {
$txt = '';
foreach($modules as $loaded) {
if ($txt != '') $txt .= ', ';
$txt .= $loaded;
}
irc_send_message('Geladene Module: '.$txt, $sender, $private);
} else {
irc_send_message('Keine Module geladen.', $sender, $private);
}
break;
/* show registered commands */
case 'commands':
if (count($commands) > 0) {
$txt = '';
foreach($commands as $registered=>$func) {
if ($txt != '') $txt .= ', ';
$txt .= $registered;
}
irc_send_message('Registrierte Befehle: '.$txt, $sender, $private);
} else {
irc_send_message('Keine registrierten Befehle.', $sender, $private);
}
break;
/* shutdown bot */
case 'shutdown':
if (is_admin($sender)) $quit = USER_SHUTDOWN;
break;
/* restart bot */
case 'restart':
if (is_admin($sender)) $quit = USER_RESTART;
break;
/* rename bot */
case 'nick':
if (is_admin($sender)) {
irc_bot_echo('new nick: '.$params);
$nick = $params;
irc_send('NICK '.$nick);
}
break;
/* load module */
case 'load':
if (is_admin($sender)) load_module($params, $sender, '', $private);
break;
/* switch quiet mode */
case 'quietmode':
if (is_admin($sender)) {
if ($quiet_mode) {
$quiet_mode = 0;
} else {
$quiet_mode = 1;
}
irc_send_message('quiet_mode is now: '.$quiet_mode, $sender, $private);
}
break;
/* show version */
case 'version':
irc_send_message('v'.IRCBOT_VERSION, $sender, $private);
break;
/* help */
case 'help':
irc_send_message('Es gibt keine Hilfe!', $sender, $private);
break;
/* uptime */
case 'uptime':
irc_send_message(date('H:i:s').' up '.(time() - $start_time).'s');
break;
/* else (module commands) */
default:
irc_bot_echo("default");
if (default_command($cmd, $params, $sender, $private)) {
return true;
} else {
irc_send_message('Me no understandy!', $sender, $private);
}
break;
}
return true;
}
/* module commands */
function default_command($cmd, $params, $target = '', $private) {
global $modules, $commands;
irc_bot_echo("default_command($cmd, $params, $target, $private)");
foreach($commands as $command=>$func) {
if ($cmd == $command) {
irc_bot_echo("cmd == command");
call_user_func($func, $params, $target, $private);
return true;
}
}
foreach($modules as $loaded) {
if ($cmd == $loaded) {
irc_bot_echo("cmd == loaded");
call_user_func($loaded.'_command', $params, $target, $private);
return true;
}
}
return false;
}
/* register command */
function ircbot_register_command($command, $function) {
global $commands;
irc_bot_echo("ircbot_register_command($command, $function)");
$commands[$command] = $function;
//print_r($commands);
}
/* listener registration public */
function ircbot_register_for_global_listening($function) {
global $msg_listener_global;
$msg_listener_global[] = $function;
}
/* listener registration private */
function ircbot_register_for_private_listening($function) {
global $msg_listener_private;
$msg_listener_private[] = $function;
}
/* send message to irc host */
function irc_send($string) {
global $irc_res;
fwrite($irc_res, $string."\n");
}
/* get array of channel users */
function ircbot_get_channel_users() {
global $users;
return $users;
}
/* send (chat) message to irc */
function irc_send_message($string, $target='', $private=1) {
global $irc_res;
global $nick;
if (($target == '') || (!$private)) $target = IRC_CHANNEL;
if ($private && ($target == '')) $target = IRC_CHANNEL;
$send = ':'.$nick.' PRIVMSG '.$target.' :'.$string."\n";
if ($string != '') {
fwrite($irc_res, $send);
return true;
}
return false;
}
/* load a module */
function load_module($module, $target='', $quiet=0, $private=0) {
global $modules;
$already_loaded = 0;
foreach($modules as $loaded) {
if ($loaded == $module) $already_loaded = 1;
}
if ($already_loaded == 0) {
if (file_exists('module_'.$module.'.php')) {
require('module_'.$module.'.php');
call_user_func($module.'_init');
$modules[] = $module;
if (!$quiet) irc_send_message('Modul geladen.', $target, $private);
} else {
if (!$quiet) irc_send_message('Modul nicht gefunden.', $target, $private);
}
} else {
if (!$quiet) irc_send_message('Modul bereits geladen.', $target, $private);
}
}
/* check if user is admin */
function is_admin($user) {
global $admin_users;
foreach($admin_users as $admin) {
if ($admin == $user) return true;
}
irc_bot_echo("user is not admin...");
return false;
}
/* echo messages */
function irc_bot_echo($message, $newline=1) {
global $quiet_mode;
if (!$quiet_mode) {
echo $message;
if ($newline) echo "\n";
}
}
?>
<file_sep>/module_linky.php
<?php
/* module_linky */
$link_stats = array();
$link_watcher = array();
$link_watcher[] = 'imgur.com';
$link_watcher[] = 'xkcd.com';
$imgur_history = array();
$ping_counter = 0;
$autoimgurpaste = 1;
function linky_init() {
global $autoimgurpaste;
irc_bot_echo("linky_init module");
$autoimgurpaste = 1;
ircbot_register_for_global_listening('linky_listener_global');
}
function linky_command($string, $target='', $private=0) {
//irc_send_message('default command handler', $target, $private);
global $link_stats, $imgur_history, $autoimgurpaste;
switch($string) {
case 'show':
if (count($link_stats) > 0) {
foreach($link_stats as $host=>$amount) {
irc_send_message($host.' : '.$amount, $target, $private);
}
} else {
irc_send_message('Noch keine Links gesammelt.', $target, $private);
}
break;
case 'imgur':
$link = imgur_get_random_link();
if ($link != false) {
irc_send_message($link, $target, $private);
} else {
irc_send_message("Sorry, keinen gültigen Link erhalten :(", $target, $private);
}
break;
case 'autoimgurpaste':
if ($autoimgurpaste) {
$autoimgurpaste = 0;
} else {
$autoimgurpaste = 1;
}
irc_send_message('autoimgurpaste is now: '.$autoimgurpaste, $target, $private);
break;
case 'help':
irc_send_message('linky module commands:', $target, $private);
irc_send_message(' imgur ... get random imgurl link', $target, $private);
irc_send_message(' autoimgurpaste ... show random imgurl link pasting mode (currently '.$autoimgurpaste.')', $target, $private);
irc_send_message(' show ... show some stats about pasted links', $target, $private);
break;
}
}
function imgur_get_random_link() {
global $imgur_history;
// erzeuge einen neuen cURL-Handle
$ch = curl_init();
// setze die URL und andere Optionen
curl_setopt($ch, CURLOPT_URL, "http://imgur.com/gallery/random");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// führe die Aktion aus und gebe die Daten an den Browser weiter
$result = curl_exec($ch);
// schließe den cURL-Handle und gebe die Systemresourcen frei
curl_close($ch);
irc_bot_echo($result);
$link_begin = strpos($result, 'Location:')+strlen('Location: ');
$link_end = strpos($result, "\n", $link_begin);
$link = trim(substr($result, $link_begin, $link_end-$link_begin));
irc_bot_echo("$link_begin - $link_end, string: '".$link."'");
if (substr($link, 0, 4) == 'http') {
$imgur_history[] = $link;
return $link;
}
return false;
}
function linky_listener_global($sender, $msg) {
global $link_stats, $ping_counter, $imgur_history;
if ($msg == 'PING') {
$ping_counter++;
irc_bot_echo("Received ping...$ping_counter");
if ($ping_counter > 10) {
$link = imgur_get_random_link();
if ($link != false) irc_send_message('Random IMGUR anyone? '.$link, IRC_CHANNEL, 0);
$ping_counter = 0;
}
} else {
$pos = strpos($msg, 'http');
if ($pos !== false) {
$end = strpos($msg, ' ', $pos);
if ($end !== false) {
$full_link = substr($msg, $pos, $end);
} else {
$full_link = substr($msg, $pos);
}
irc_bot_echo("link detected as: ".$full_link);
$url = parse_url($full_link);
irc_bot_echo("host of this is: ".$url['host']);
if (!isset($link_stats[$url['host']])) {
$link_stats[$url['host']] = 0;
}
if ($url['host'] == 'imgur.com') {
foreach($imgur_history as $url) {
if ($url == $full_link) {
irc_send_message('Den Link hatten wir schon.', IRC_CHANNEL, 0);
break;
}
}
$imgur_history[] = $full_link;
}
$link_stats[$url['host']]++;
}
}
}
?>
| 51367518e2041e2dc611a968d6e9569d5fed31cc | [
"PHP",
"Shell"
] | 8 | PHP | steffmeister/phpircbot | 9d5fc4191a3df572d2a1438553f11685a15afb77 | 9de8020980460544c509351d8b7bf1f06525facd | |
refs/heads/master | <file_sep>import React, { Component } from "react";
import { Container,Content,Button,Header,Left, Body,Title,Icon, List, ListItem, Switch, Separator, Right } from "native-base";
import {Image,View,TouchableWithoutFeedback,Text} from "react-native";
import styles from "./styles";
class Help extends Component {
static navigationOptions={
header:null
}
constructor(props){
super(props);
}
render() {
return (
<Container>
<View style={styles.headerView}>
<Button
transparent
onPress={() => this.props.navigation.goBack()}
>
<Icon
name="arrow-back"
style={styles.back}
/>
</Button>
<View style={styles.empty}/>
<Image
style={styles.image}
source={require("../../../assets/netflixHeader.png")}/>
</View>
<Content style={styles.content}>
<View style={styles.firstView}><Text style={styles.firstText}>Find Help Online</Text></View>
<List style={styles.list}>
<ListItem icon>
<Left>
<Icon name="ios-exit-outline" style={styles.blue}/>
</Left>
<Body>
<Text style={styles.blue}>Help Center</Text>
</Body>
</ListItem>
<ListItem icon>
<Left>
<Icon name="ios-card" style={styles.blue}/>
</Left>
<Body>
<Text style={styles.blue}>Update Payment Method</Text>
</Body>
</ListItem>
<ListItem icon>
<Left>
<Icon name="printer" type="MaterialCommunityIcons" style={styles.blue}/>
</Left>
<Body>
<Text style={styles.blue}>Request a Titler</Text>
</Body>
</ListItem>
<ListItem icon>
<Left>
<Icon name="lock" type="MaterialIcons" style={styles.blue}/>
</Left>
<Body>
<Text style={styles.blue}>Update Password</Text>
</Body>
</ListItem>
<ListItem icon>
<Left>
<Icon name="cancel" type="MaterialCommunityIcons" style={styles.blue}/>
</Left>
<Body>
<Text style={styles.blue}>Cancel Account</Text>
</Body>
</ListItem>
<ListItem icon>
<Left>
<Icon name="tools" type="Entypo" style={styles.blue}/>
</Left>
<Body>
<Text style={styles.blue}>Fix a connection issue</Text>
</Body>
</ListItem>
</List>
<View style={styles.lastView}>
<Text style={styles.firstText}>Contact</Text>
<Text style={styles.firstText}>Teleflix Customer Service</Text>
<Text style={styles.smallText}>We'll connect the call for free using your internet connection.</Text>
<View><Button iconLeft dark>
<Icon name='ios-call' />
<Text style={styles.buttonText}>Call</Text>
</Button></View>
</View>
</Content>
</Container>
);
}
}
export default Help;
<file_sep>import React, { Component } from "react";
import { Container,Content,Button, Right,Icon } from "native-base";
import {Image,View,TouchableWithoutFeedback,Text} from "react-native";
import styles from "./styles";
import WhiteHeader from "../Headers/WhiteHeader";
import Benifit from "./Benifit";
class Step1Content extends Component {
static navigationOptions={
header:null
}
constructor(props){
super(props);
this.state={
selected:3
}
}
choosePackage(n){
this.setState({
selected:n
})
}
render() {
return (
<Container>
<WhiteHeader login={()=>this.props.navigation.navigate("Login")} help={()=>this.props.navigation.navigate("Help")}/>
<Content contentContainerStyle={styles.contContent}>
<View style={styles.contentView}>
<Text>Step 1 of 3</Text>
<Text style={styles.mainBold}>Choose a plan that's right for you</Text>
<Text>Downgrade or upgrade at any time</Text>
<View style={styles.contentEmpty}/>
<View style={styles.packageView}>
<TouchableWithoutFeedback onPress={()=>this.choosePackage(1)}>
<View style={[styles.package,this.state.selected===1?styles.selected:styles.notSelected]}>
<Text style={styles.packageText}>Basic</Text>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={()=>this.choosePackage(2)}>
<View style={[styles.package,this.state.selected===2?styles.selected:styles.notSelected]}>
<Text style={styles.packageText}>Standard</Text>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={()=>this.choosePackage(3)}>
<View style={[styles.package,this.state.selected===3?styles.selected:styles.notSelected]}>
<Text style={styles.packageText}>Premium</Text>
</View>
</TouchableWithoutFeedback>
</View>
<Text style={styles.centerText}>Monthly price after free month ends on 07/07/2018</Text>
<View style={styles.contentEmpty}/>
<Benifit icon={false} first="Rs. 500" second="Rs. 650" third="Rs. 800" selected={this.state.selected}/>
<View style={styles.contentEmpty}/>
<Text style={styles.centerText}>HD available</Text>
<View style={styles.contentEmpty}/>
<Benifit icon={true} first="cross" second="check" third="check" selected={this.state.selected}/>
<View style={styles.contentEmpty}/>
<Text style={styles.centerText}> Ultra HD available</Text>
<View style={styles.contentEmpty}/>
<Benifit icon={true} first="cross" second="cross" third="check" selected={this.state.selected}/>
<View style={styles.contentEmpty}/>
<Text style={styles.centerText}> Screens you can watch at the same time</Text>
<View style={styles.contentEmpty}/>
<Benifit icon={false} first="1" second="3" third="5" selected={this.state.selected}/>
<View style={styles.contentEmpty}/>
<Text style={styles.centerText}>Cancel at any time and first month free</Text>
<View style={styles.contentEmpty}/>
<Benifit icon={true} first="check" second="check" third="check" selected={this.state.selected}/>
<View style={styles.contentEmpty}/>
<Button style={styles.contentButton} onPress={()=>this.props.navigation.navigate("Step2Main",{plan:this.state.selected})}>
<Text style={styles.mainButtonText}>Continue</Text>
</Button>
</View>
</Content>
</Container>
);
}
}
export default Step1Content;
<file_sep>import React, { Component } from "react";
import { Container,Content,Button, Right,Icon, Input,Form,Item,Label } from "native-base";
import {Image,View,TouchableWithoutFeedback,Text} from "react-native";
import styles from "./styles";
import WhiteHeader from "../Headers/WhiteHeader";
import firebase from 'react-native-firebase';
class Step2Content extends Component {
static navigationOptions={
header:null
}
constructor(props){
super(props);
this.state = {
email:"",
password:"",
error:"Enter email and password"
};
}
validatePassword=(password)=>{
if (this.state.password.length < 8){
this.state.error="Password shouuld be minimum 8 characters long";
}
else{
this.state.error="";
}
this.setState({password:password});
}
validateEmail=(email)=>{
if (!this.state.email.includes('@')){
this.state.error="Email should contain @"
}
else{
this.state.error=""
}
this.setState({email:email});
}
createAccount=()=>{
if(this.state.error=="" && this.state.password.length > 0 && this.state.email.length > 0){
firebase.auth().createUserAndRetrieveDataWithEmailAndPassword(this.state.email, this.state.password)
.then(u => {
this.props.navigation.navigate("Step3Main",{uid:u.user._user.uid,plan:this.props.navigation.state.params.plan})
})
.catch(err =>{
this.setState({
error : err.message
})
})
}
}
componentDidMount() {
}
render() {
return (
<Container>
<WhiteHeader login={()=>this.props.navigation.navigate("Login")} help={()=>this.props.navigation.navigate("Help")}/>
<Content contentContainerStyle={styles.cont2Content}>
<View style={styles.content2View}>
<Text>Step 2 of 3</Text>
<View style={styles.contentEmpty}/>
<Text style={styles.mainBold}>Sign up to start your free month.</Text>
<View style={styles.contentEmpty}/>
<Text>Just two more steps and you are finished!</Text>
<Text>We hate paperwork, too.</Text>
<View style={styles.contentEmpty}/>
<Text style={styles.bold}>Create your account</Text>
<View style={styles.contentEmpty}/>
<Form>
<Item regular>
<Input placeholder="Email" keyboardType="email-address" onChangeText={(email)=>{ this.validateEmail(email)}}/>
</Item>
<Item regular>
<Input placeholder="Password" secureTextEntry onChangeText={(password)=>{this.validatePassword(password)}}/>
</Item>
</Form>
<Text style={styles.errorText}>{this.state.error}</Text>
<View style={styles.contentEmpty}/>
<Button style={styles.contentButton} onPress={this.createAccount}>
<Text style={styles.mainButtonText}>Continue</Text>
</Button>
</View>
</Content>
</Container>
);
}
}
export default Step2Content;
<file_sep>import React, { Component } from "react";
import {
Container,
Header,
Title,
Button,
Icon,
Right,
Left,
Body
} from "native-base";
class BasicTab extends Component {
constructor(props){
super(props)
}
render() {
return (
<Container>
<Header hasTabs>
<Left>
<Button
transparent
onPress={() => this.props.navigation.navigate("DrawerOpen")}
>
<Icon name="menu" />
</Button>
</Left>
<Body>
<Title> Netflix </Title>
</Body>
<Right >
<Button transparent>
<Icon name='search' />
</Button>
<Button transparent>
<Icon name='md-more' />
</Button>
</Right>
</Header>
</Container>
);
}
}
export default BasicTab;
// export default createMaterialTopTabNavigator({
// Series: TabOne,
// Movies: TabTwo,
// });
<file_sep>import React from "react";
import { Root } from "native-base";
import { StackNavigator, DrawerNavigator,TabNavigator } from "react-navigation";
import {
Container,
Header,
Title,
Button,
Icon,
Tabs,
Tab,
Right,
Left,
Body,
} from "native-base";
import {View, StatusBar, YellowBox} from "react-native";
import BasicTab from "./screens/tab/basicTab";
import TabOne from "./screens/tab/tabOne";
import TabTwo from "./screens/tab/tabTwo";
import Detail from "./screens/tab/detailScreen";
import Episodes from "./screens/tab/episodes";
import VideoPlayer from "./screens/tab/video";
import SideBar from "./screens/sidebar";
import Register from "./screens/LoginScreens/Register";
import Login from "./screens/LoginScreens/Login";
import Setting from "./screens/Settings/setting";
import Notification from "./screens/Notifications/Notification";
import MyList from "./screens/MyList/MyList";
import Account from "./screens/Account/Account";
import Users from "./screens/Account/Users";
import Search from "./screens/search/Search";
import Help from "./screens/Help/Help";
import Download from "./screens/Downloads/download";
import Step1Main from "./screens/SignUp/Step1Main";
import Step1Content from "./screens/SignUp/Step1Content";
import Step2Main from "./screens/SignUp/Step2Main";
import Step2Content from "./screens/SignUp/Step2Content";
import Step3Main from "./screens/SignUp/Step3Main";
import Step3Content from "./screens/SignUp/Step3Content";
YellowBox.ignoreWarnings(["Warning: isMounted( ... ) is deprecated"]);
const TabHome = TabNavigator({
Series:{screen:TabOne,navigationOptions: { tabBarLabel: 'Series' }},
Movies:{screen:TabTwo,navigationOptions: { tabBarLabel: 'Movies' }}
},
{
swipeEnabled:true,
lazy:false,
navigationOptions:({navigation})=> ({
title:'Teleflix',
headerLeft:(
<View style={{flex:1,flexDirection:'row'}}>
<Button
transparent
onPress={() => navigation.navigate("DrawerOpen")}
>
<Icon name="menu" style={{color:'white'}}/>
</Button>
</View>
),
headerRight:(
<View style={{flex:1,flexDirection:'row'}}>
<Button transparent onPress={() => navigation.navigate("Search")}>
<Icon name="search" style={{color:'white'}}/>
</Button>
<Button transparent>
<Icon name="md-more" style={{color:'white'}}/>
</Button>
</View>
),
headerStyle:{
backgroundColor:'#2B2C30'
},
headerTitleStyle: {
color: '#C14748',
},
}),
tabBarOptions: {
style:{
backgroundColor:'#2B2C30'
}
}
}
);
const AppNavigator = StackNavigator(
{
// Drawer: { screen: Drawer },
Register:{screen:Register, navigationOptions:({navigation})=>({
drawerLockMode:"locked-closed"
})},
Step1Main:{screen:Step1Main, navigationOptions:({navigation})=>({
drawerLockMode:"locked-closed"
})},
Step1Content:{screen:Step1Content, navigationOptions:({navigation})=>({
drawerLockMode:"locked-closed"
})},
Step2Main:{screen:Step2Main, navigationOptions:({navigation})=>({
drawerLockMode:"locked-closed"
})},
Step2Content:{screen:Step2Content, navigationOptions:({navigation})=>({
drawerLockMode:"locked-closed"
})},
Step3Main:{screen:Step3Main, navigationOptions:({navigation})=>({
drawerLockMode:"locked-closed"
})},
Step3Content:{screen:Step3Content, navigationOptions:({navigation})=>({
drawerLockMode:"locked-closed"
})},
Login:{screen:Login, navigationOptions:({navigation})=>({
drawerLockMode:"locked-closed"
})},
Help:{screen:Help},
TabHome: { screen: TabHome},
Search: {screen: Search},
MyList:{screen:MyList},
Account:{screen:Account},
Users:{screen:Users},
Notification: {screen: Notification},
Download:{screen:Download},
Detail: {screen: Detail},
Episodes: {screen:Episodes},
VideoPlayer: {screen:VideoPlayer, navigationOptions:({navigation})=>({
drawerLockMode:"locked-closed"
})},
},
{
initialRouteName: "Register",
// headerMode: "none"
}
);
const Drawer = DrawerNavigator(
{
App: { screen: AppNavigator },
Setting: {screen: Setting},
Notification: {screen: Notification},
MyList:{screen:MyList},
Account:{screen:Account},
Download:{screen:Download}
},
{
initialRouteName: "App",
contentOptions: {
activeTintColor: "#e91e63"
},
contentComponent: props => <SideBar {...props} />
}
);
export default () =>
<Root>
<StatusBar backgroundColor='#2B2C30' barStyle='light-content' />
<Drawer />
</Root>;
<file_sep>import React, { Component } from "react";
import { Container,Content,Button, Right,Icon } from "native-base";
import {Image,View,TouchableWithoutFeedback,Text,} from "react-native";
import styles from "./styles";
import WhiteHeader from "../Headers/WhiteHeader";
class Step3Main extends Component {
static navigationOptions={
header:null
}
constructor(props){
super(props);
}
render() {
return (
<Container>
<WhiteHeader login={()=>this.props.navigation.navigate("Login")} help={()=>this.props.navigation.navigate("Help")}/>
<Content contentContainerStyle={styles.mainContent}>
<View style={styles.main3View}>
<Icon name="lock-outline" type="MaterialCommunityIcons" style={styles.tick}/>
<View style={styles.mainEmpty}/>
<Text>Step 3 of 3</Text>
<Text style={styles.mainBold}>Set up your Payment</Text>
<View style={styles.mainEmpty}/>
<Text >Cancel before 07/07/18 if you dont want to be charged.</Text>
<View style={styles.contentEmpty}/>
<Text >As a reminder we will remind you 3 days before. </Text>
<View style={styles.contentEmpty}/>
<Text >No Commitments. Cancel online at any time.</Text>
<View style={styles.mainEmpty}/>
<TouchableWithoutFeedback onPress={()=>this.props.navigation.navigate("Step3Content",{uid:this.props.navigation.state.params.uid,plan:this.props.navigation.state.params.plan})}>
<View style={styles.main3Button}>
<Text>Credit or Debit Card</Text>
<Icon name="navigate-next" type="MaterialIcons"/>
</View>
</TouchableWithoutFeedback>
</View>
</Content>
</Container>
);
}
}
export default Step3Main;
<file_sep>import React, { Component } from "react";
import styles from "./styles";
import {View,Text} from "react-native";
import {Icon} from "native-base"
class Benifit extends Component{
constructor(props){
super(props);
}
render(){
return(
<View>
{!this.props.icon &&(
<View style={styles.benifitView}>
<Text style={[styles.benifitText,this.props.selected==1?styles.selectedText:styles.notSelectedText]}>{this.props.first}</Text>
<Text style={styles.benifitText}>|</Text>
<Text style={[styles.benifitText,this.props.selected==2?styles.selectedText:styles.notSelectedText]}>{this.props.second}</Text>
<Text style={styles.benifitText}>|</Text>
<Text style={[styles.benifitText,this.props.selected==3?styles.selectedText:styles.notSelectedText]}>{this.props.third}</Text>
</View>)}
{this.props.icon &&(
<View style={styles.benifitView}>
<Icon style={[styles.benifitText,this.props.selected==1?styles.selectedText:styles.notSelectedText]} type="Entypo" name={this.props.first}/>
<Text style={styles.benifitText}>|</Text>
<Icon style={[styles.benifitText,this.props.selected==2?styles.selectedText:styles.notSelectedText]} type="Entypo" name={this.props.second}/>
<Text style={styles.benifitText}>|</Text>
<Icon style={[styles.benifitText,this.props.selected==3?styles.selectedText:styles.notSelectedText]} type="Entypo" name={this.props.third}/>
</View>
)}
</View>
)
}
}
export default Benifit;
<file_sep>export default {
series: [
{
name: "Narcos",
image: require("../../../assets/narcos.jpg"),
rating: 4,
commments: 279,
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enimad minim veniam, quis nostrud exercitation ullamco",
genre: "crime drama",
seasons: [
{
no: 1,
image: require("../../../assets/narcosS01.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 2,
image: require("../../../assets/narcosS02.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gr<NAME>",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 3,
image: require("../../../assets/narcosS03.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "<NAME>",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 4,
image: require("../../../assets/narcosS04.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
}
]
},
{
name: "<NAME>",
image: require("../../../assets/breaking.jpg"),
rating: 3,
commments: 260,
description: "<NAME>, a chemistry teacher, discovers that he has cancer and decides to get into the meth-making business to repay his medical debts. His priorities begin to change when he partners with Jesse.",
genre: "crime drama",
seasons: [
{
no: 1,
image: require("../../../assets/breakingS01.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "<NAME>",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 2,
image: require("../../../assets/breakingS02.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 3,
image: require("../../../assets/breakingS03.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 4,
image: require("../../../assets/breakingS04.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 5,
image: require("../../../assets/breakingS01.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
}
]
},
{
name: "<NAME>",
image: require("../../../assets/thrones.jpg"),
rating: 5,
commments: 764,
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enimad minim veniam, quis nostrud exercitation ullamco",
genre: "crime drama",
seasons: [
{
no: 1,
image: require("../../../assets/narcosS01.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of Simón Bolivar",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 2,
image: require("../../../assets/narcosS02.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 3,
image: require("../../../assets/narcosS03.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "<NAME>",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "<NAME>",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 4,
image: require("../../../assets/narcosS04.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
}
]
},
{
name: "Narcos",
image: require("../../../assets/narcos.jpg"),
rating: 4,
commments: 279,
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enimad minim veniam, quis nostrud exercitation ullamco",
genre: "crime drama",
seasons: [
{
no: 1,
image: require("../../../assets/narcosS01.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 2,
image: require("../../../assets/narcosS02.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 3,
image: require("../../../assets/narcosS03.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 4,
image: require("../../../assets/narcosS04.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
}
]
},
{
name: "Narcos",
image: require("../../../assets/narcos.jpg"),
rating: 4,
commments: 279,
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enimad minim veniam, quis nostrud exercitation ullamco",
genre: "crime drama",
seasons: [
{
no: 1,
image: require("../../../assets/narcosS01.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of Simón Bolivar",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 2,
image: require("../../../assets/narcosS02.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 3,
image: require("../../../assets/narcosS03.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "<NAME>",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
},
{
no: 4,
image: require("../../../assets/narcosS04.jpg"),
episodes: [
{
no: 1,
title: "Descenso",
time: "47:56",
subtitle: "vost-english"
},
{
no: 2,
title: "The Sword of <NAME>",
time: "49:26",
subtitle: "vost-english"
},
{
no: 3,
title: "The Men of Always",
time: "43:59",
subtitle: "vost-english"
},
{
no: 4,
title: "The Palace in Flames",
time: "47:56",
subtitle: "vost-english"
},
{
no: 5,
title: "There Will Be a Future",
time: "41:32",
subtitle: "vost-english"
},
{
no: 6,
title: "Explosivos",
time: "47:23",
subtitle: "vost-english"
},
{
no: 7,
title: "You Will Cry Tears of Blood",
time: "46:56",
subtitle: "vost-english"
},
{
no: 8,
title: "La Gran Mentira",
time: "43:26",
subtitle: "vost-english"
},
{
no: 9,
title: "La Catedral",
time: "42:16",
subtitle: "vost-spanish"
},
{
no: 10,
title: "Despegue",
time: "42:16",
subtitle: "vost-spanish"
},
]
}
]
}
]
};
<file_sep>import React, { Component } from "react";
import { Container,Content,Button,Header,Left, Body,Title,Icon, List, ListItem, Switch, Separator, Right } from "native-base";
import {Image,View,TouchableWithoutFeedback,Text} from "react-native";
import styles from "./styles";
const datas=[
{
head:'Breaking Bad S01E01',
date:'May 30',
img:require('../../../assets/breaking.jpg')
},
{
head:'Breaking Bad S02E02',
date:'May 30',
img:require('../../../assets/breakingS02.jpg')
},
{
head:'Breaking Bad S03E03',
date:'May 30',
img:require('../../../assets/breakingS03.jpg')
},
]
class Download extends Component {
static navigationOptions={
header:null
}
constructor(props){
super(props);
}
render() {
return (
<Container>
<Header androidStatusBarColor="#121212" style={styles.header}>
<Left>
<Button
transparent
onPress={() => this.props.navigation.goBack()}
>
<Icon
name="arrow-back"
style={styles.back}
/>
</Button>
</Left>
<Body>
<Title style={styles.headerTitle}>My Downloads</Title>
</Body>
<Right/>
</Header>
<Content style={styles.content}>
<List noBorder
listBorderColor="#1A1A1A"
listItemPadding={5}
dataArray={datas}
renderRow={data=><ListItem style={styles.listItem} onPress={() => this.props.navigation.navigate("VideoPlayer")}>
<View style={styles.imageView}>
<Image
style={styles.image}
source={data.img}/>
</View>
<View style={styles.pad}/>
<View style={styles.allText}>
<Text style={styles.head}>{data.head}</Text>
<Text style={styles.date}>{data.date}</Text>
</View>
</ListItem>}/>
</Content>
</Container>
);
}
}
export default Download;
<file_sep>const React = require('react-native')
const { Dimensions }=React
const deviceHeight = Dimensions.get("window").height;
const deviceWidth = Dimensions.get('window').width;
const ratio=deviceWidth/200
export default {
image:{
height:(deviceWidth/6)*54,
width:deviceWidth/6,
},
registerContent:{
backgroundColor:'black'
},
headerText:{
color:'black',
fontSize:17,
fontWeight:'bold'
},
header:{
backgroundColor:'white'
},
content:{
backgroundColor:'#1A1A1A'
},
contentImage:{
height:deviceHeight/1.5,
width:deviceWidth
},
textView:{
flex:1,
justifyContent:'flex-start',
alignItems:'center'
},
firstText:{
fontSize:22,
color:'white',
fontWeight:'bold',
paddingBottom:deviceHeight/100
},
secondText:{
fontSize:17,
color:'white',
paddingBottom:deviceHeight/70
},
buttonText:{
fontSize:16,
color:'white',
paddingTop:deviceHeight/200,
paddingLeft:deviceWidth/50,
paddingRight:deviceWidth/50,
paddingBottom:deviceHeight/200
},
button:{
backgroundColor:'#FF6D2D',
},
tabs:{
paddingTop:deviceHeight/20,
flex:1,
flexDirection:'row',
justifyContent:'space-evenly',
width:deviceWidth
},
icons:{
fontSize:70,
color:"white"
},
thirdTextView:{
flex:1,
alignItems:'center',
paddingTop: deviceHeight/20,
width: deviceWidth*(2/3),
marginBottom:deviceHeight/20
},
cancelImage:{
width:deviceWidth,
height:deviceHeight/2.5,
paddingTop:deviceHeight/10
},
selectedIcon:{
borderBottomColor:"#FF6D2D",
borderBottomWidth: 3
},
//login
headerArrangement:{flex:1,
flexDirection:'row',
alignItems:'center'},
back:{ color: "white",
fontSize: 19 },
headerLogin:{
backgroundColor:"#121212",
},
empty:{
flex:2
},
loginHeaderText:{
color:'white',
fontSize:17,
fontWeight:'bold'
},
login:{
flex:1,
height:(deviceHeight-(deviceHeight/8)),
justifyContent:'center',
paddingLeft:deviceWidth/15,
paddingRight:deviceWidth/15
},
inputLabel:{
color:'white'
},
input:{
color:'white'
},
loginButton:{
marginTop:deviceHeight/30,
backgroundColor:'#FF6D2D',
width:deviceWidth-(deviceHeight/15),
flex:0.07,
justifyContent:'center',
alignItems:'center',
height:deviceHeight/10
},
loginBottomText:{
fontSize:17,
fontWeight:'600',
color:'white',
paddingTop:deviceHeight/70
}
};
<file_sep>import React, { Component } from "react";
import { Container,Content,Button, Right,Icon } from "native-base";
import {Image,View,TouchableWithoutFeedback,Text,} from "react-native";
import styles from "./styles";
import WhiteHeader from "../Headers/WhiteHeader";
class Register extends Component {
static navigationOptions={
header:null
}
constructor(props){
super(props);
}
render() {
return (
<Container>
{/* <Header androidStatusBarColor="white" style={styles.header}>
<Left>
<Image
style={styles.image}
resizeMode={'contain'}
source={require("../../../assets/netflixHeader.png")}/>
</Left>
<Right>
<Button transparent onPress={() => this.props.navigation.navigate("Login")}>
<Text style={styles.headerText}>LOG IN</Text>
</Button>
<Button transparent onPress={() => this.props.navigation.navigate("Help")}>
<Text style={styles.headerText}>HELP</Text>
</Button>
</Right>
</Header> */}
<WhiteHeader login={()=>this.props.navigation.navigate("Login")} help={()=>this.props.navigation.navigate("Help")}/>
<Content style={styles.registerContent}>
<Image style={styles.contentImage} source={require("../../../assets/RegisterBackground.jpg")}/>
<View style={styles.textView}>
<Text style={styles.firstText}>See what's next</Text>
<Text style={styles.secondText}>Watch anywhere. Cancel at Any Time</Text>
<View>
<Button style={styles.button} onPress={()=>this.props.navigation.navigate("Step1Main")}>
<Text style={styles.buttonText}>Join Free For A Month</Text>
</Button>
</View>
<View style={styles.tabs}>
<View style={styles.selectedIcon}><Icon name="ios-exit" style={styles.icons}/></View>
<Icon name="ios-tablet-landscape-outline" style={styles.icons}/>
<Icon name="ios-pricetags-outline" style={styles.icons}/>
</View>
<View style={styles.thirdTextView}>
<Text style={styles.firstText}>
If you decide Teleflix isn't for you no problem. No commitment. Cancel anytime.
</Text>
</View>
{/* <Image
style={styles.cancelImage}
source={require("../../../assets/cancel.png")}/> */}
</View>
</Content>
</Container>
);
}
}
export default Register;
<file_sep>const React = require('react-native')
const { Dimensions }=React
const deviceHeight = Dimensions.get("window").height;
const deviceWidth = Dimensions.get('window').width;
export default {
headerView:{
backgroundColor:'white',
flex:0.1,
flexDirection:'row',
width:deviceWidth
},
back:{
color: "black",
fontSize: 19
},
headerTitle:{
color:'white',
fontSize:17,
fontWeight:'bold'
},
content:{
flex:0.9,
backgroundColor:'white'
},
firstView:{
flex:1,
flexDirection:'row',
justifyContent:'center'
},
firstText:{
fontWeight:'bold',
color:'black',
fontSize:18
},
list:{
marginTop:deviceHeight/15,
marginRight:deviceWidth/8,
},
image:{
height:(deviceWidth/23),
width:deviceWidth/6,
marginTop:deviceHeight/40
},
empty:{
flex:0.43
},
imageView:{
flex:0.3
},
pad:{
flex:0.04
},
blue:{
color:'#0071EB',
},
lastView:{
marginTop:deviceHeight/8.5,
flex:1,
alignItems:'center',
marginLeft:deviceWidth/7,
marginRight:deviceWidth/7
},
smallText:{
marginTop:deviceHeight/60,
marginBottom:deviceHeight/60,
textAlign:'center'
},
buttonText:{
color:'white',
fontSize:19,
marginLeft:deviceWidth/20,
marginRight:deviceWidth/20
}
};
<file_sep>import React, { Component } from "react";
import { Image } from "react-native";
import {
Content,
Text,
List,
ListItem,
Icon,
Container,
Left,
Header
} from "native-base";
import styles from "./style";
const drawerCover = require("../../../assets/netflix.png");
const drawerImage = require("../../../assets/logo-kitchen-sink.png");
const sidebars = [
{
name: "Account",
route: "Account",
icon: "md-person",
},
{
name: "My List",
route: "MyList",
icon: "md-basket",
},
{
name: "Notifications",
route: "Notification",
icon: "md-notifications",
},
{
name: "My Downloads",
route: "Download",
icon: "md-download",
},
{
name: "Settings",
route: "Setting",
icon: "md-settings",
},
{
name: "Logout",
route: "Logout",
icon: "md-power",
},
];
class SideBar extends Component {
static navigationOptions = {
drawerLabel: () => null,
header:false
}
constructor(props) {
super(props);
this.state = {
shadowOffsetWidth: 1,
shadowRadius: 4
};
}
render() {
return (
<Container>
<Content
bounces={false}
style={{ flex: 1, backgroundColor: "#fff", top: -1 }}
>
<Image source={drawerCover} style={styles.drawerCover} />
<List
dataArray={sidebars}
renderRow={data =>
<ListItem
button
noBorder
onPress={() => this.props.navigation.navigate(data.route)}
>
<Left>
<Icon
active
name={data.icon}
style={{ color: "#777", fontSize: 26, width: 30 }}
/>
<Text style={styles.text}>
{data.name}
</Text>
</Left>
</ListItem>}
/>
</Content>
</Container>
);
}
}
export default SideBar;
<file_sep>import React, { Component } from "react";
import {
Animated,
Platform,
StatusBar,
StyleSheet,
Text,
View,
RefreshControl,
Dimensions,
TouchableOpacity
} from "react-native";
import {
ActionSheet,
Button,
Icon,
Container,
Header,
Left,
Right,
List,
ListItem
} from "native-base";
import styles1 from "./styles";
const deviceHeight = Dimensions.get("window").height;
const deviceWidth = Dimensions.get("window").width;
const HEADER_MAX_HEIGHT = deviceHeight / 2.2;
const HEADER_MIN_HEIGHT = deviceHeight / 10;
const HEADER_SCROLL_DISTANCE = HEADER_MAX_HEIGHT - HEADER_MIN_HEIGHT;
const eps = [
{
name: "Breaking 1",
no: 1
},
{
name: "Breaking 1",
no: 2
},
{
name: "Green Light",
no: 3
},
{
name: "BLue Light",
no: 4
},
{
name: "The Fly",
no: 5
},
{
name: "The Escape",
no: 7
},
{
name: "The Escape",
no: 8
},
{
name: "The Escape",
no: 9
},
{
name: "The Escape",
no: 10
},
{
name: "The Escape",
no: 11
},
{
name: "The Escape",
no: 12
},
{
name: "The Escape",
no: 13
},
{
name: "The Escape",
no: 14
},
{
name: "The Escape",
no: 15
}
];
const EPISODE_BUTTONS =["Download","View Details","Cancel"]
const SCREEN_BUTTONS=["Download All","View Series Details","Cancel"]
const CANCEL_INDEX = 2
export default class App extends Component {
static navigationOptions = {
header: null
};
constructor(props) {
super(props);
this.state = {
scrollY: new Animated.Value(
// iOS has negative initial scroll value because content inset...
Platform.OS === "ios" ? -HEADER_MAX_HEIGHT : 0
),
refreshing: false,
clicked:false
};
}
showActionSheet(BUTTONS,head){
return(ActionSheet.show(
{
options: BUTTONS,
cancelButtonIndex: CANCEL_INDEX,
title: head
},
buttonIndex => {
this.setState({ clicked: BUTTONS[buttonIndex] });
}))
}
_renderScrollViewContent() {
const data = Array.from({ length: 30 });
return (
<View style={styles.scrollViewContent}>
<List
listItemPadding={0}
dataArray={eps}
renderRow={ep =>
<ListItem first button={true} style={styles1.listItem} onPress={() => this.props.navigation.navigate("VideoPlayer")}>
<View style={styles1.episodeView}>
<View style={styles1.episodeWatched} />
<View style={styles1.episodeDetailView}>
<View style={styles1.episodeNameView}>
<Text style={styles1.episodeTitle}>
{" " + ep.name}
</Text>
<Text>
{" "}S01E{ep.no}
</Text>
</View>
<View style={styles1.episodeNameView}>
<Text>
{" "}
</Text>
<Icon name="ios-time-outline" style={styles1.episodeIcon} />
<Text>
{" "}49:56{" "}
</Text>
<Icon
name="ios-closed-captioning"
style={styles1.episodeIcon}
/>
<Text>
{" "}vost-english
</Text>
</View>
</View>
<View style={styles1.episodeMore} >
<TouchableOpacity onPress={()=>this.showActionSheet(EPISODE_BUTTONS,"Episode Options")}>
<Icon name="md-more" />
</TouchableOpacity>
</View>
</View>
</ListItem>}
/>
</View>
);
}
render() {
// Because of content inset the scroll value will be negative on iOS so bring
// it back to 0.
const scrollY = Animated.add(
this.state.scrollY,
Platform.OS === "ios" ? HEADER_MAX_HEIGHT : 0
);
const headerTranslate = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE],
outputRange: [0, -HEADER_SCROLL_DISTANCE],
extrapolate: "clamp"
});
const imageOpacity = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE / 2, HEADER_SCROLL_DISTANCE],
outputRange: [1, 1, 0],
extrapolate: "clamp"
});
const imageTranslate = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE],
outputRange: [0, 100],
extrapolate: "clamp"
});
const viewTranslate = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE],
outputRange: [0, 90],
extrapolate: "clamp"
});
const viewScale = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE / 2, HEADER_SCROLL_DISTANCE],
outputRange: [0, 0, 0],
extrapolate: "clamp"
});
const titleScale = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE / 2, HEADER_SCROLL_DISTANCE],
outputRange: [1, 1, 1],
extrapolate: "clamp"
});
const titleTranslate = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE / 2, HEADER_SCROLL_DISTANCE],
outputRange: [0, 0, -4],
extrapolate: "clamp"
});
const textOpacity=scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE],
outputRange: [0, 1],
})
return (
<View style={styles.fill}>
<StatusBar
translucent
barStyle="light-content"
backgroundColor="#C14748"
/>
<Animated.ScrollView
style={styles.fill}
scrollEventThrottle={1}
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
{ useNativeDriver: true }
)}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={() => {
this.setState({ refreshing: true });
setTimeout(() => this.setState({ refreshing: false }), 1000);
}}
// Android offset for RefreshControl
progressViewOffset={HEADER_MAX_HEIGHT}
/>
}
// iOS offset for RefreshControl
contentInset={{
top: HEADER_MAX_HEIGHT
}}
contentOffset={{
y: -HEADER_MAX_HEIGHT
}}
>
{this._renderScrollViewContent()}
</Animated.ScrollView>
<Animated.View
pointerEvents="none"
style={[
styles.header,
{ transform: [{ translateY: headerTranslate }] }
]}
>
<Animated.Image
style={[
styles.backgroundImage,
{
opacity: imageOpacity,
transform: [{ translateY: imageTranslate }]
}
]}
source={require("../../../assets/narcos.jpg")}
/>
<Animated.View
style={[
styles1.buttonAlign,
{
transform: [
{ translateY: viewTranslate },
{ scale: viewScale }
],
zIndex: 7
}
]}
>
<Button rounded style={styles1.button} onPress={() => this.setState({ clicked: !this.state.clicked })}>
<Icon style={styles1.play} name="play" />
</Button>
</Animated.View>
<Animated.View
style={[
styles1.trailer,
{
transform: [{ translateY: viewTranslate }, { scale: viewScale }]
}
]}
>
<Text style={styles1.trailerText}>GreenLight S01 | E03</Text>
</Animated.View>
</Animated.View>
<Animated.View
style={[
styles.bar,
{
transform: [{ scale: titleScale }, { translateY: titleTranslate }]
}
]}
>
<View style={styles1.headerView}>
<View style={styles1.headerBeginView}>
<Button
transparent
onPress={() => this.props.navigation.goBack()}
>
<Icon
name="arrow-back"
style={styles1.headerIcon}
/>
</Button>
<Button transparent><Animated.Text style={[styles1.headerText,{opacity:textOpacity}]}>{this.props.navigation.state.params.name}</Animated.Text></Button>
</View>
<View
style={styles1.headerEndView}
>
<Button transparent onPress={() => this.props.navigation.navigate("Search")}>
<Icon name="search" style={styles1.headerIcon} />
</Button>
<Button transparent onPress={()=>this.showActionSheet(SCREEN_BUTTONS,"Options")}>
<Icon name="md-more" style={styles1.headerIcon} />
</Button>
</View>
</View>
</Animated.View>
</View>
);
}
}
const styles = StyleSheet.create({
fill: {
flex: 1
},
content: {
flex: 1
},
header: {
position: "absolute",
top: 0,
left: 0,
right: 0,
backgroundColor: "#C14748",
overflow: "hidden",
height: HEADER_MAX_HEIGHT
},
backgroundImage: {
position: "absolute",
top: 0,
left: 0,
right: 0,
width: null,
height: HEADER_MAX_HEIGHT * (9 / 10),
resizeMode: "cover"
},
bar: {
backgroundColor: "transparent",
marginTop: Platform.OS === "ios" ? 28 : 38,
height: 32,
alignItems: "center",
justifyContent: "center",
position: "absolute",
top: 0,
left: 0,
right: 0
},
title: {
color: "white",
fontSize: 18
},
scrollViewContent: {
// iOS uses content inset, which acts like padding.
paddingTop: Platform.OS !== "ios" ? HEADER_MAX_HEIGHT : 0,
marginBottom:deviceHeight/25
},
row: {
height: 40,
margin: 16,
backgroundColor: "#D3D3D3",
alignItems: "center",
justifyContent: "center"
}
});
<file_sep>import React, { Component } from "react";
import { Container,Content,Button, Right,Icon } from "native-base";
import {Image,View,TouchableWithoutFeedback,Text,} from "react-native";
import styles from "./styles";
import WhiteHeader from "../Headers/WhiteHeader";
class Step2Main extends Component {
static navigationOptions={
header:null
}
constructor(props){
super(props);
}
render() {
return (
<Container>
<WhiteHeader login={()=>this.props.navigation.navigate("Login")} help={()=>this.props.navigation.navigate("Help")}/>
<Content contentContainerStyle={styles.mainContent}>
<View style={styles.mainView}>
<Icon name="cellphone-iphone" type="MaterialCommunityIcons" style={styles.tick}/>
<View style={styles.mainEmpty}/>
<Text>Step 2 of 3</Text>
<Text style={styles.mainBold}>Create your account</Text>
<View style={styles.mainEmpty}/>
<Text>Use your email and create a password to watch teleflix on any device at any time.</Text>
<View style={styles.mainEmpty}/>
<Button style={styles.mainButton} onPress={()=>this.props.navigation.navigate("Step2Content",{plan:this.props.navigation.state.params.plan})}>
<Text style={styles.mainButtonText}>Continue</Text>
</Button>
</View>
</Content>
</Container>
);
}
}
export default Step2Main;
<file_sep>import React, { Component } from "react";
import { Container,Content,Button, Left,Icon, Input,Form,Item,ListItem,Body,CheckBox } from "native-base";
import {Image,View,TouchableWithoutFeedback,Text} from "react-native";
import styles from "./styles";
import WhiteHeader from "../Headers/WhiteHeader";
class Step3Content extends Component {
static navigationOptions={
header:null
}
constructor(props){
super(props);
}
render() {
return (
<Container>
<WhiteHeader login={()=>this.props.navigation.navigate("Login")} help={()=>this.props.navigation.navigate("Help")}/>
<Content contentContainerStyle={styles.cont2Content}>
<View style={styles.contentView}>
<Text>Step 3 of 3</Text>
<View style={styles.contentEmpty}/>
<Text style={styles.mainBold}>Set up your credit or debit card.</Text>
<View style={styles.contentEmpty}/>
<View style={styles.creditCard}>
<Icon name="cc-visa" type="FontAwesome"/>
<Text>{' '}</Text>
<Icon name="cc-mastercard" type="FontAwesome"/>
</View>
<View style={styles.contentEmpty}/>
<Form>
<Item regular>
<Input placeholder="First Name"/>
</Item>
<Item regular>
<Input placeholder="Last Name"/>
</Item>
<Item regular>
<Input placeholder="Card Number" keyboardType="phone-pad"/>
</Item>
<Item regular>
<Input placeholder="Expiry Date (MM/YY)"/>
</Item>
<Item regular>
<Input placeholder="Security code (CVV)" keyboardType="phone-pad"/>
</Item>
</Form>
<View style={styles.contentEmpty}/>
<Text>You will be charged Rs. 800 after your free month ends.</Text>
<View style={styles.contentEmpty}/>
<View style={styles.checkBox}>
<CheckBox checked={true} />
<Text>{' '}I am over 18 and I agree to the terms of use and privacy policy.</Text>
</View>
<View style={styles.contentEmpty}/>
<Button style={styles.contentButton} onPress={()=>this.props.navigation.navigate("Login")}>
<Text style={styles.mainButtonText}>Start Membership</Text>
</Button>
</View>
</Content>
</Container>
);
}
}
export default Step3Content;
<file_sep>import React, { Component } from "react";
import { Container,Content,Button,Header,Left, Body,Title,Icon, List, ListItem, Switch, Separator, Right } from "native-base";
import {Image,View,TouchableWithoutFeedback,Text} from "react-native";
import styles from "./styles";
const datas=[
{title:'New Arrival',
head:'Breaking Bad Season 1',
date:'May 30',
img:require('../../../assets/breaking.jpg')
},
{title:'New Arrival',
head:'Breaking Bad Season 2',
date:'May 30',
img:require('../../../assets/breakingS02.jpg')
},
{title:'New Arrival',
head:'Breaking Bad Season 3',
date:'May 30',
img:require('../../../assets/breakingS03.jpg')
},
{title:'New Arrival',
head:'Breaking Bad Season 4',
date:'May 30',
img:require('../../../assets/breakingS04.jpg')
},
{title:'New Arrival',
head:'Breaking Bad Season 5',
date:'May 30',
img:require('../../../assets/breakingS01.jpg')
},
{title:'New Arrival',
head:'Narcos Season 1',
date:'May 30',
img:require('../../../assets/narcosS01.jpg')
},
{title:'New Arrival',
head:'Narcos Season 2',
date:'May 30',
img:require('../../../assets/narcosS02.jpg')
},
{title:'New Arrival',
head:'Game of thrones Season 1',
date:'May 30',
img:require('../../../assets/thronesS01.jpg')
},
{title:'New Arrival',
head:'Game of thrones Season 2',
date:'May 30',
img:require('../../../assets/thrones.jpg')
},
]
class Notification extends Component {
static navigationOptions={
header:null
}
constructor(props){
super(props);
}
render() {
return (
<Container>
<Header androidStatusBarColor="#121212" style={styles.header}>
<Left>
<Button
transparent
onPress={() => this.props.navigation.goBack()}
>
<Icon
name="md-arrow-back"
style={styles.back}
/>
</Button>
</Left>
<Body style={{flex:1}}>
<Title style={styles.headerTitle}>Notificaiton</Title>
</Body>
<Right/>
</Header>
<Content style={styles.content}>
<List noBorder
listBorderColor="#1A1A1A"
listItemPadding={5}
dataArray={datas}
renderRow={data=><ListItem style={styles.listItem} onPress={() => this.props.navigation.navigate("Episodes",{image:1,name:'Narcos'})}>
<View style={styles.imageView}>
<Image
style={styles.image}
source={data.img}/>
</View>
<View style={styles.pad}/>
<View style={styles.allText}>
<Text style={styles.title}>{data.title}</Text>
<Text style={styles.head}>{data.head}</Text>
<Text style={styles.date}>{data.date}</Text>
</View>
</ListItem>}/>
</Content>
</Container>
);
}
}
export default Notification;
<file_sep>import React, { Component } from "react";
import {
Animated,
Platform,
StatusBar,
StyleSheet,
Text,
View,
RefreshControl,
Dimensions,
ImageBackground,
TouchableWithoutFeedback
} from "react-native";
import {
Button,
Icon,
Card,
CardItem,
List,
ListItem,
ActionSheet
} from "native-base";
import styles1 from "./styles";
const deviceHeight = Dimensions.get("window").height;
const deviceWidth = Dimensions.get("window").width;
const HEADER_MAX_HEIGHT = deviceHeight * (2 / 3);
const HEADER_MIN_HEIGHT = deviceHeight / 10;
const HEADER_SCROLL_DISTANCE = HEADER_MAX_HEIGHT - HEADER_MIN_HEIGHT;
const SEASONS_BUTTONS = ["Download", "View Details", "Cancel"]
const SCREEN_BUTTONS = ["Add to your list", "View Series Details", "Cancel"]
const CANCEL_INDEX = 2
const datas = [
{
season: 1,
episodes: "7/13",
img: require("../../../assets/narcosS02.jpg")
},
{
season: 2,
episodes: "7/13",
img: require("../../../assets/narcosS01.jpg")
},
{
season: 3,
episodes: "7/13",
img: require("../../../assets/breakingS01.jpg")
},
{
season: 4,
episodes: "7/13",
img: require("../../../assets/breakingS02.jpg")
},
{
season: 5,
episodes: "7/13",
img: require("../../../assets/breakingS03.jpg")
},
{
season: 6,
episodes: "7/13",
img: require("../../../assets/thronesS01.jpg")
}
]
export default class App extends Component {
static navigationOptions = {
header: null
};
constructor(props) {
super(props);
this.state = {
scrollY: new Animated.Value(
// iOS has negative initial scroll value because content inset...
Platform.OS === "ios" ? -HEADER_MAX_HEIGHT : 0
),
refreshing: false
};
this.arr = [
require("../../../assets/breaking.jpg"),
require("../../../assets/narcos.jpg"),
require("../../../assets/stranger.jpg"),
require("../../../assets/thrones.jpg")
];
}
showActionSheet(BUTTONS, head) {
return (ActionSheet.show(
{
options: BUTTONS,
cancelButtonIndex: CANCEL_INDEX,
title: head
},
buttonIndex => {
this.setState({ clicked: BUTTONS[buttonIndex] });
}))
}
_renderScrollViewContent() {
return (
<View style={[styles.scrollViewContent, styles1.scroll]}>
{datas.map((e, i) => {
return (
<View key={i}>
<TouchableWithoutFeedback onPress={() => this.props.navigation.navigate("Episodes", { image: 1, name: 'Narcos' })}>
<Card style={styles1.seasonCard}>
<CardItem cardBody>
<ImageBackground
source={e.img}
style={styles1.cardImage}
>
<Text style={styles1.cardImageText}>Season {e.season}</Text>
</ImageBackground>
</CardItem>
<View style={styles1.cardFoot}>
<View style={{ flex: 0.8, justifyContent: 'center', alignItems: 'flex-start' }}>
<Text style={styles1.episodesRemaining}>{e.episodes}{' '}Episodes</Text>
</View>
<View style={{ flex: 0.2 }} />
<View style={{ flex: 0.3, justifyContent: "center", alignItems: 'flex-start' }}>
<Button transparent onPress={() => this.showActionSheet(SEASONS_BUTTONS, "Season Options")}>
<Icon name="md-more" style={{ fontSize: 13 }} />
</Button>
</View>
</View>
</Card>
</TouchableWithoutFeedback>
</View>
)
})}
</View>
);
}
render() {
// Because of content inset the scroll value will be negative on iOS so bring
// it back to 0.
const AnimatedTouchableFeedback = Animated.createAnimatedComponent(TouchableWithoutFeedback);
const scrollY = Animated.add(
this.state.scrollY,
Platform.OS === "ios" ? HEADER_MAX_HEIGHT : 0
);
const headerTranslate = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE],
outputRange: [0, -HEADER_SCROLL_DISTANCE],
extrapolate: "clamp"
});
const imageOpacity = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE / 2, HEADER_SCROLL_DISTANCE],
outputRange: [1, 1, 0],
extrapolate: "clamp"
});
const imageTranslate = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE],
outputRange: [0, 100],
extrapolate: "clamp"
});
const viewTranslate = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE],
outputRange: [0, 550],
extrapolate: "extend"
});
const viewScale = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE / 2],
outputRange: [0, 0.7],
extrapolate: "clamp"
});
const detailTranslate = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE],
outputRange: [0, 200],
extrapolate: "clamp"
});
const titleScale = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE / 2, HEADER_SCROLL_DISTANCE],
outputRange: [1, 1, 1],
extrapolate: "clamp"
});
const titleTranslate = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE / 2, HEADER_SCROLL_DISTANCE],
outputRange: [0, 0, -4],
extrapolate: "clamp"
});
const textOpacity = scrollY.interpolate({
inputRange: [0, HEADER_SCROLL_DISTANCE],
outputRange: [0, 1],
})
return (
<View style={styles.fill}>
<StatusBar
translucent
barStyle="light-content"
backgroundColor="#C14748"
/>
<Animated.ScrollView
style={styles.fill}
scrollEventThrottle={1}
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
{ useNativeDriver: true }
)}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={() => {
this.setState({ refreshing: true });
setTimeout(() => this.setState({ refreshing: false }), 1000);
}}
// Android offset for RefreshControl
progressViewOffset={HEADER_MAX_HEIGHT}
/>
}
// iOS offset for RefreshControl
contentInset={{
top: HEADER_MAX_HEIGHT
}}
contentOffset={{
y: -HEADER_MAX_HEIGHT
}}
>
{this._renderScrollViewContent()}
</Animated.ScrollView>
<Animated.View
pointerEvents="none"
style={[
styles.header,
{ transform: [{ translateY: headerTranslate }] }
]}
>
<Animated.Image
style={[
styles.backgroundImage,
{
opacity: imageOpacity,
transform: [{ translateY: imageTranslate }]
}
]}
source={this.arr[this.props.navigation.state.params.image]}
/>
<TouchableWithoutFeedback onPress={() => alert('Add payment')}>
<Animated.View
style={[
styles1.buttonAlign,
{
transform: [
{ translateY: viewTranslate },
],
zIndex: 6
}
]}
>
<Button rounded style={styles1.button} onPress={() => alert('Add payment')}>
<Icon style={styles1.play} name="play" onPress={() => alert('Add payment')} />
</Button>
</Animated.View>
</TouchableWithoutFeedback>
<Animated.View
style={[
styles1.trailer,
{
transform: [{ translateY: viewTranslate }]
}
]}
>
<Text style={styles1.trailerText}>Watch trailer season 1</Text>
</Animated.View>
<Animated.View
style={[
styles1.remaining,
{
transform: [{ translateY: detailTranslate }]
}
]}
>
<View style={styles1.ratings}>
<View style={styles1.rating}>
<Icon name="ios-star" style={styles1.background} />
<Icon name="ios-star" style={styles1.background} />
<Icon name="ios-star" style={styles1.background} />
<Icon name="ios-star" style={styles1.background} />
<Icon name="ios-star" style={styles1.background} />
</View>
<Text style={styles1.rateText}>{' '}5.0/5</Text>
<View style={styles1.rate} />
<View style={styles1.comment}>
<Icon name="md-chatbubbles" style={styles1.background} />
<Text style={styles1.rateText}>{' '}279</Text>
</View>
</View>
<View style={styles1.show}>
<View>
<Text style={styles1.showName}>
{this.props.navigation.state.params.name}
</Text>
</View>
<View>
<Text style={styles1.showGenre}>Crime, Drama</Text>
</View>
</View>
<View style={styles1.description}>
<Text style={styles1.rateText}>
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</Text>
</View>
</Animated.View>
</Animated.View>
<Animated.View
style={[
styles.bar,
{
transform: [{ scale: titleScale }, { translateY: titleTranslate }]
}
]}
>
<View style={styles1.headerView}>
<View style={styles1.headerBeginView}>
<Button
transparent
onPress={() => this.props.navigation.goBack()}
>
<Icon
name="arrow-back"
style={styles1.headerIcon}
/>
</Button>
<Button transparent><Animated.Text style={[styles1.headerText, { opacity: textOpacity }]}>{this.props.navigation.state.params.name}</Animated.Text></Button>
</View>
<View
style={styles1.headerEndView}
>
<Button transparent onPress={() => this.props.navigation.navigate("Search")}>
<Icon name="search" style={styles1.headerIcon} />
</Button>
<Button transparent onPress={() => this.showActionSheet(SCREEN_BUTTONS, "Options")}>
<Icon name="md-more" style={styles1.headerIcon} />
</Button>
</View>
</View>
</Animated.View>
</View>
);
}
}
const styles = StyleSheet.create({
fill: {
flex: 1
},
content: {
flex: 1
},
header: {
position: "absolute",
top: 0,
left: 0,
right: 0,
backgroundColor: "#C14748",
overflow: "hidden",
height: HEADER_MAX_HEIGHT
},
backgroundImage: {
position: "absolute",
top: 0,
left: 0,
right: 0,
width: null,
height: HEADER_MAX_HEIGHT * (7 / 10),
resizeMode: "cover"
},
bar: {
backgroundColor: "transparent",
marginTop: Platform.OS === "ios" ? 28 : 38,
height: 32,
alignItems: "center",
justifyContent: "center",
position: "absolute",
top: 0,
left: 0,
right: 0
},
title: {
color: "white",
fontSize: 18
},
scrollViewContent: {
// iOS uses content inset, which acts like padding.
paddingTop: Platform.OS !== "ios" ? HEADER_MAX_HEIGHT : 0
},
row: {
height: 40,
margin: 16,
backgroundColor: "#D3D3D3",
alignItems: "center",
justifyContent: "center"
}
});
| d9064dbe1dae49a18e9fdc780da85832f74de987 | [
"JavaScript"
] | 18 | JavaScript | prateek3255/NetflixAppReact | 0dfda5db7059a6eec4f4d40a667436b54f8b945e | e6945b952437a8ddcd60e6d9a55435dec9269de6 | |
refs/heads/master | <file_sep>// Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TechF.Configuration
{
//ncrunch: no coverage start
public class ClassFactoryPropertyElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return Convert.ToString(this["name"]);
}
}
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get
{
return Convert.ToString(this["value"]);
}
}
}
[ConfigurationCollection(typeof(ClassFactoryPropertyElement), AddItemName = "Property", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class ClassFactoryPropertyCollection : ConfigurationElementCollection, IEnumerable<ClassFactoryPropertyElement>
{
public ClassFactoryPropertyCollection()
{
AddElementName = "Property";
}
protected override ConfigurationElement CreateNewElement()
{
return new ClassFactoryPropertyElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ClassFactoryPropertyElement)element).Name;
}
IEnumerator<ClassFactoryPropertyElement> IEnumerable<ClassFactoryPropertyElement>.GetEnumerator()
{
foreach (var i in base.BaseGetAllKeys())
{
var o = (ClassFactoryPropertyElement)BaseGet(i);
if (o != null)
yield return o;
}
}
public ClassFactoryPropertyElement this[int index]
{
get
{
return (ClassFactoryPropertyElement)BaseGet(index);
}
}
public new ClassFactoryPropertyElement this[string index]
{
get
{
return (ClassFactoryPropertyElement)BaseGet(index);
}
}
}
public class ClassFactoryElement : ConfigurationElement
{
[ConfigurationProperty("type", IsRequired = true)]
public string Type
{
get
{
return Convert.ToString(this["type"]);
}
}
[ConfigurationProperty("factoryType", IsRequired = true)]
public string FactoryType
{
get
{
return Convert.ToString(this["factoryType"]);
}
}
[ConfigurationProperty("persistPerContext", DefaultValue = false, IsRequired = false)]
public bool PersistsPerContext
{
get
{
return Convert.ToBoolean(this["persistPerContext"]);
}
}
[ConfigurationProperty("FactoryProperties", IsRequired = false)]
public ClassFactoryPropertyCollection FactoryProperties
{
get
{
return (ClassFactoryPropertyCollection)this["FactoryProperties"];
}
}
}
[ConfigurationCollection(typeof(ClassFactoryElement), AddItemName = "Factory", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class ClassFactoryCollection : ConfigurationElementCollection, IEnumerable<ClassFactoryElement>
{
public ClassFactoryCollection()
{
AddElementName = "Factory";
}
protected override ConfigurationElement CreateNewElement()
{
return new ClassFactoryElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ClassFactoryElement)element).Type;
}
public ClassFactoryElement this[int index]
{
get
{
return (ClassFactoryElement)BaseGet(index);
}
}
public new ClassFactoryElement this[string index]
{
get
{
return (ClassFactoryElement)BaseGet(index);
}
}
IEnumerator<ClassFactoryElement> IEnumerable<ClassFactoryElement>.GetEnumerator()
{
var keys = BaseGetAllKeys();
foreach (var key in keys)
{
var i = (ClassFactoryElement)BaseGet(key);
if (i != null)
yield return i;
}
}
}
public class ClassFactorySection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired = false, IsDefaultCollection = true)]
public ClassFactoryCollection ClassFactories
{
get
{
return (ClassFactoryCollection)this[""];
}
}
}
//ncrunch: no coverage end
}
<file_sep>// Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TechF.Test
{
//ncrunch: no coverage start
public enum TestEnum
{
Test1 = 0,
Test2 = 1,
Test3 = 2,
Test4 = 3
}
static class TestClassPropertyValues
{
public const string StringProperty = "test";
public const bool BooleanProperty = true;
public const sbyte SignedByteProperty = 45;
public const byte UnsignedByteProperty = 210;
public const short SignedShortProperty = 2124;
public const ushort UnsignedShortProperty = 3986;
public const int SignedIntProperty = 849829;
public const uint UnsignedIntProperty = 898099;
public const long SignedLongProperty = 382918301;
public const ulong UnsignedLongProperty = 382918301;
public const float SingleProperty = 494.58f;
public const double DoubleProperty = 890.112;
public const decimal DecimalProperty = 123.456M;
public const TestEnum EnumProperty = TestEnum.Test3;
public static DateTimeOffset DateTimeOffsetProperty = new DateTimeOffset(1988, 2, 11, 0, 0, 0, TimeSpan.FromSeconds(0));
public static DateTime DateTimeProperty = new DateTime(1988, 2, 11, 0, 0, 0);
}
public class TestClass
{
public string StringProperty { get; set; }
public bool BooleanProperty { get; set; }
public SByte SignedByteProperty { get; set; }
public Byte UnsignedByteProperty { get; set; }
public short SignedShortProperty { get; set; }
public ushort UnsignedShortProperty { get; set; }
public int SignedIntProperty { get; set; }
public uint UnsignedIntProperty { get; set; }
public long SignedLongProperty { get; set; }
public ulong UnsignedLongProperty { get; set; }
public float SingleProperty { get; set; }
public double DoubleProperty { get; set; }
public decimal DecimalProperty { get; set; }
public TestEnum EnumProperty { get; set; }
public TestEnum EnumPropertyNumeric { get; set; }
public object NullProperty { get; set; }
public DateTime DateTimeProperty { get; set; }
public DateTimeOffset DateTimeOffsetProperty { get; set; }
}
public class TestClass2
{
}
public class TestClass3 : TestClass
{
}
public class TestClassConstructorInjectionValue
{
public int Property { get; private set; }
public TestClassConstructorInjectionValue(int SignedIntProperty)
{
Property = SignedIntProperty;
}
}
public class TestClassNoPublicConstructor
{
private TestClassNoPublicConstructor() { }
}
public class TestClassConstructiorInjectionRef
{
public TestClass Test { get; private set; }
public TestClassConstructiorInjectionRef(TestClass test)
{
Test = test;
}
}
public class ClassFactoryContextTests
{
private ImmutableDictionary<string, string> CreateProperties()
{
return ImmutableDictionary<string, string>.Empty
.Add("StringProperty",TestClassPropertyValues.StringProperty)
.Add("BooleanProperty", TestClassPropertyValues.BooleanProperty.ToString())
.Add("SignedByteProperty", TestClassPropertyValues.SignedByteProperty.ToString())
.Add("UnsignedByteProperty", TestClassPropertyValues.UnsignedByteProperty.ToString())
.Add("SignedShortProperty", TestClassPropertyValues.SignedShortProperty.ToString())
.Add("UnsignedShortProperty", TestClassPropertyValues.UnsignedShortProperty.ToString())
.Add("SignedIntProperty", TestClassPropertyValues.SignedIntProperty.ToString())
.Add("UnsignedIntProperty", TestClassPropertyValues.UnsignedIntProperty.ToString())
.Add("SignedLongProperty", TestClassPropertyValues.SignedLongProperty.ToString())
.Add("UnsignedLongProperty", TestClassPropertyValues.UnsignedLongProperty.ToString())
.Add("SingleProperty", TestClassPropertyValues.SingleProperty.ToString())
.Add("DoubleProperty", TestClassPropertyValues.DoubleProperty.ToString())
.Add("DecimalProperty", TestClassPropertyValues.DecimalProperty.ToString())
.Add("EnumProperty", TestClassPropertyValues.EnumProperty.ToString())
.Add("NullProperty", null)
.Add("EnumPropertyNumeric", ((int)TestClassPropertyValues.EnumProperty).ToString())
.Add("DateTimeOffsetProperty", TestClassPropertyValues.DateTimeOffsetProperty.ToString())
.Add("DateTimeProperty", TestClassPropertyValues.DateTimeProperty.ToString());
}
private TType CreateWithProperties<TType, TImplementation>(bool persist = false) where TType : class where TImplementation : TType
{
var context = new ClassFactoryContext();
var props = CreateProperties();
context.SetFactoryType<TType, TImplementation>(props).Persist = persist;
return context.Resolve<TType>();
}
[Test]
public void TestFromGlobal()
{
ClassFactory.SetFactoryType<TestClass, TestClass>();
var context = new ClassFactoryContext();
var o = context.Resolve<TestClass>();
ClassFactory.ClearFactoryTypeInformation<TestClass>();
Assert.IsInstanceOf<TestClass>(o);
}
[Test]
[ExpectedException(typeof(TechF.Exceptions.ClassFactoryException))]
public void TestNonConfiguredType()
{
ClassFactory.ClearFactoryTypeInformation<TestClass>();
var context = new ClassFactoryContext();
var o = context.Resolve<TestClass>();
}
[Test]
[ExpectedException(typeof(TechF.Exceptions.ClassFactoryConstructorException))]
public void TestTypeWithoutPublicConstructor()
{
var context = new ClassFactoryContext();
context.SetFactoryType<TestClassNoPublicConstructor, TestClassNoPublicConstructor>();
var o = context.Resolve<TestClassNoPublicConstructor>();
}
[Test]
public void TestContextPersistence()
{
var context = new ClassFactoryContext();
context.SetFactoryType<TestClass, TestClass>(null).Persist = true;
var testClass1 = context.Resolve<TestClass>();
var testClass2 = context.Resolve<TestClass>();
Assert.AreSame(testClass1, testClass2);
}
[Test]
public void TestContextNonPersistence()
{
var context = new ClassFactoryContext();
context.SetFactoryType<TestClass, TestClass>(null).Persist = false;
var testClass1 = context.Resolve<TestClass>();
var testClass2 = context.Resolve<TestClass>();
Assert.AreNotSame(testClass1, testClass2);
}
[Test]
[ExpectedException(typeof(Exceptions.ClassFactoryTypeMismatchException))]
public void TestSetFactoryTypeTypeMismatch()
{
var props = CreateProperties();
var context = new ClassFactoryContext();
context.SetFactoryType(typeof(TestClass), typeof(TestClass2), null);
}
[Test]
public void TestSetFactoryInheritance()
{
var context = new ClassFactoryContext();
context.SetFactoryType(typeof(TestClass), typeof(TestClass3), null);
}
[Test]
public void TestPropertyBindingString()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.StringProperty, TestClassPropertyValues.StringProperty);
}
[Test]
public void TestPropertyBindingBoolean()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.BooleanProperty, TestClassPropertyValues.BooleanProperty);
}
[Test]
public void TestPropertyBindingSignedByte()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.SignedByteProperty, TestClassPropertyValues.SignedByteProperty);
}
[Test]
public void TestPropertyBindingUnsignedByte()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.UnsignedByteProperty, TestClassPropertyValues.UnsignedByteProperty);
}
[Test]
public void TestPropertyBindingSignedShort()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.SignedShortProperty, TestClassPropertyValues.SignedShortProperty);
}
[Test]
public void TestPropertyBindingUnsignedShort()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.SignedShortProperty, TestClassPropertyValues.SignedShortProperty);
}
[Test]
public void TestPropertyBindingSignedInt()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.SignedIntProperty, TestClassPropertyValues.SignedIntProperty);
}
[Test]
public void TestPropertyBindingUnsignedInt()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.UnsignedIntProperty, TestClassPropertyValues.UnsignedIntProperty);
}
[Test]
public void TestPropertyBindingSignedLong()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.SignedLongProperty, TestClassPropertyValues.SignedLongProperty);
}
[Test]
public void TestPropertyBindingUnsignedLong()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.UnsignedLongProperty, TestClassPropertyValues.UnsignedLongProperty);
}
[Test]
public void TestPropertyBindingSingle()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.SingleProperty, TestClassPropertyValues.SingleProperty);
}
[Test]
public void TestPropertyBindingDouble()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.DoubleProperty, TestClassPropertyValues.DoubleProperty);
}
[Test]
public void TestPropertyBindingDecimal()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.DecimalProperty, TestClassPropertyValues.DecimalProperty);
}
[Test]
public void TestPropertyEnum()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.EnumProperty, TestClassPropertyValues.EnumProperty);
}
[Test]
public void TestPropertyEnumNumeric()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.EnumPropertyNumeric, TestClassPropertyValues.EnumProperty);
}
[Test]
public void TestPropertyNull()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.NullProperty, null);
}
[Test]
public void TestPropertyDateTime()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.DateTimeProperty, TestClassPropertyValues.DateTimeProperty);
}
[Test]
public void TestPropertyDateTimeOffset()
{
var o = CreateWithProperties<TestClass, TestClass>();
Assert.AreEqual(o.DateTimeOffsetProperty, TestClassPropertyValues.DateTimeOffsetProperty);
}
[Test]
public void TestConstructorInjectionValues()
{
var o = CreateWithProperties<TestClassConstructorInjectionValue, TestClassConstructorInjectionValue>();
Assert.AreEqual(TestClassPropertyValues.SignedIntProperty, o.Property);
}
[Test]
[ExpectedException(typeof(Exceptions.ClassFactoryConstructorException))]
public void TestConstructorInjectionMissingValues()
{
var context = new ClassFactoryContext();
var props = ImmutableDictionary<string, string>.Empty;
context.SetFactoryType<TestClassConstructorInjectionValue, TestClassConstructorInjectionValue>(props);
context.Resolve<TestClassConstructorInjectionValue>();
}
[Test]
public void TestConstructorInjectionResolve()
{
var context = new ClassFactoryContext();
context.SetFactoryType<TestClass, TestClass>();
context.SetFactoryType<TestClassConstructiorInjectionRef, TestClassConstructiorInjectionRef>();
var o = context.Resolve<TestClassConstructiorInjectionRef>();
Assert.NotNull(o.Test);
}
[Test]
public void TestNoPropertyBinding()
{
var context = new ClassFactoryContext();
var props = ImmutableDictionary<string, string>.Empty
.Add("StringProperty", TestClassPropertyValues.StringProperty);
context.SetFactoryType<TestClass, TestClass>(props).BindProperties = false;
var o = context.Resolve<TestClass>();
Assert.AreNotEqual(o.StringProperty, TestClassPropertyValues.StringProperty);
}
[Test]
[ExpectedException(typeof(Exceptions.ClassFactoryTypeMismatchException))]
public void TestTypeMismatch()
{
var context = new ClassFactoryContext();
context.SetFactoryType(typeof(TestClass3), typeof(TestClass));
}
[Test]
public void TestGetTypeOptions()
{
var context = new ClassFactoryContext();
context.SetFactoryType<TestClass, TestClass>();
context.GetTypeOptions<TestClass>().BindProperties = false;
var o = context.Resolve<TestClass>();
Assert.AreNotEqual(TestClassPropertyValues.StringProperty, o.StringProperty);
}
[Test]
public void TestGetTypeOptionsFromRoot()
{
var context = new ClassFactoryContext();
ClassFactory.SetFactoryType<TestClass, TestClass>();
context.GetTypeOptions<TestClass>().BindProperties = false;
var o = context.Resolve<TestClass>();
Assert.AreNotEqual(TestClassPropertyValues.StringProperty, o.StringProperty);
}
[Test]
[ExpectedException(typeof(Exceptions.ClassFactoryTypeMismatchException))]
public void TestGetTypeOptionsFromInvalidType()
{
ClassFactory.ClearFactoryTypeInformation<TestClass>();
new ClassFactoryContext().GetTypeOptions<TestClass>();
}
[Test]
[ExpectedException(typeof(Exceptions.ClassFactoryException))]
public void TestClearTypeInformation()
{
var context = new ClassFactoryContext();
ClassFactory.ClearFactoryTypeInformation<TestClass>();
context.SetFactoryType<TestClass, TestClass>();
context.ClearFactoryTypeInformation<TestClass>();
context.Resolve<TestClass>();
}
}
//ncrunch: no coverage end
}
<file_sep>// Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TechF.Exceptions
{
public class ValidationError : Exception
{
//ncrunch: no coverage start
private string[] _errors;
public ValidationError(IEnumerable<string> errors)
{
_errors = errors.ToArray();
}
public override string ToString()
{
return string.Join("\n", _errors);
}
//ncrunch: no coverage end
}
}
<file_sep>// Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TechF
{
public class ClassFactoryContext : IDisposable
{
private Dictionary<System.Type, ClassFactoryBinder> _factories = new Dictionary<Type, ClassFactoryBinder>();
internal ReaderWriterLock _factoriesLock = new ReaderWriterLock();
private ClassFactoryBinder ResolveRoot(Type type)
{
ClassFactory._factoriesLock.AcquireReaderLock(-1);
var binder = ClassFactory._factories.ContainsKey(type) ? ClassFactory._factories[type] : null;
ClassFactory._factoriesLock.ReleaseReaderLock();
return binder;
}
private ClassFactoryBinder ResolveContext(Type type)
{
_factoriesLock.AcquireReaderLock(-1);
var binder = _factories.ContainsKey(type) ? _factories[type] : null;
_factoriesLock.ReleaseReaderLock();
return binder;
}
/// <summary>
/// Resolve a object of the specified type from the context,
/// falling back to the global class factory if not found in the context.
/// If resolved from the global class factory, the
/// configuration is added to the context
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
/// <throws name="ClassFactoryTypeMismatch">If the type is not configured or valid for creation</throws>
public object Resolve(Type type)
{
ClassFactoryBinder binder = ResolveContext(type);
if (binder != null)
{
var o = binder.Create();
return o;
}
binder = ResolveRoot(type);
if (binder != null)
{
var contextBinder = new ClassFactoryBinder(this, binder);
_factoriesLock.AcquireWriterLock(-1);
_factories[binder._type] = contextBinder;
_factoriesLock.ReleaseWriterLock();
return contextBinder.Create();
}
throw new Exceptions.ClassFactoryException(string.Format("Type '{0}' is not configured", type.Name));
}
/// <summary>
/// Resolve a object of the specified type from the context,
/// falling back to the global class factory if not found in the context.
/// If resolved from the global class factory, the
/// configuration is added to the context
/// </summary>
/// <typeparam name="T">The type to create</typeparam>
/// <returns>A object of the requested type</returns>
/// <throws name="ClassFactoryTypeMismatch">If the type is not configured or valid for creation</throws>
public T Resolve<T>() where T : class
{
return (T)Resolve(typeof(T));
}
/// <summary>
/// Configure a context bound factory for the given type using the provided
/// constant values used in constructor injection and property binding
/// </summary>
/// <param name="type">The type to configure</param>
/// <param name="factoryType">The type that implements 'type'</param>
/// <param name="properties">Constant properties for parameter binding and constructor injection</param>
/// <returns>A options object that can be used for setting persistence and property binding</returns>
public ClassFactoryOptions SetFactoryType(Type type, Type factoryType, ImmutableDictionary<string, string> properties = null)
{
if (!type.IsAssignableFrom(factoryType))
throw new Exceptions.ClassFactoryTypeMismatchException();
var binder = new ClassFactoryBinder(this, factoryType, properties);
_factoriesLock.AcquireWriterLock(-1);
_factories[type] = binder;
_factoriesLock.ReleaseWriterLock();
return binder._options;
}
/// <summary>
/// Configure a context bound factory for the given type using the provided
/// constant values used in constructor injection and property binding
/// </summary>
/// <param name="type">The type to configure</param>
/// <param name="factoryType">The type that implements 'type'</param>
/// <param name="properties">Constant properties for parameter binding and constructor injection</param>
/// <returns>A options object that can be used for setting persistence and property binding</returns>
public ClassFactoryOptions SetFactoryType<TType, TImplementation>(ImmutableDictionary<string, string> properties = null) where TType : class where TImplementation : TType
{
return SetFactoryType(typeof(TType), typeof(TImplementation), properties);
}
/// <summary>
/// Get the options object for the specified type, in order to set persistence and property binding
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public ClassFactoryOptions GetTypeOptions(Type type)
{
ClassFactoryBinder binder = ResolveContext(type);
if (binder != null)
return binder._options;
binder = ResolveRoot(type);
if (binder != null)
return binder._options;
throw new Exceptions.ClassFactoryTypeMismatchException();
}
/// <summary>
/// Get the options object for the specified type, in order to set persistence and property binding
/// </summary>
/// <typeparam name="type"></typeparam>
/// <returns></returns>
public ClassFactoryOptions GetTypeOptions<T>()
{
return GetTypeOptions(typeof(T));
}
/// <summary>
/// Remove the configuration for the specified type
/// </summary>
/// <param name="type"></param>
public void ClearFactoryTypeInformation(Type type)
{
_factoriesLock.AcquireWriterLock(-1);
if (_factories.ContainsKey(type))
_factories.Remove(type);
_factoriesLock.ReleaseWriterLock();
}
/// <summary>
/// Remove the configuration for the specified type
/// </summary>
/// <typeparam name="type"></typeparam>
public void ClearFactoryTypeInformation<T>()
{
ClearFactoryTypeInformation(typeof(T));
}
//ncrunch: no coverage start
public void Dispose()
{
}
//ncrunch: no coverage end
}
}
<file_sep>// Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TechF.Configuration
{
//ncrunch: no coverage start
public static class ConfigurationManager
{
public static IClassFactoryConfiguration Copy(this ClassFactorySection config)
{
if (config == null)
return null;
return new ClassFactoryConfiguration()
{
ClassFactories
= from c in config.ClassFactories ?? new ClassFactoryCollection()
select new ClassFactory()
{
Type = c.Type,
PersistPerContext = c.PersistsPerContext,
FactoryType = c.FactoryType,
FactoryProperties = from p in c.FactoryProperties ?? new ClassFactoryPropertyCollection()
select new ClassFactoryProperty()
{
Name = p.Name,
Value = p.Value
}}};
}
public static IClassFactoryConfiguration ClassFactoryConfigurationFromConfigurationFile(string section)
{
return ((ClassFactorySection)System.Configuration.ConfigurationManager.GetSection(section)).Copy();
}
}
//ncrunch: no coverage end
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TechF.Utilities
{
public class DictionaryComparison<TKey, TValue> where TValue : class
{
public static bool Compare(IReadOnlyDictionary<TKey, TValue> x, IReadOnlyDictionary<TKey, TValue> y)
{
//
if (null == y)
return null == x;
if (null == x)
return false;
if (object.ReferenceEquals(x, y))
return true;
if (x.Count != y.Count)
return false;
foreach (TKey k in x.Keys)
if (!y.ContainsKey(k))
return false;
//
foreach (TKey k in x.Keys)
{
var xk = x != null ? x[k] : null;
var yk = y != null ? y[k] : null;
if (xk == null && yk != null)
return false;
if (xk != yk)
return false;
}
return true;
}
}
}
<file_sep>Tech-F
======
General Purpose Utility Framework
---------------------------------
Currently only contains a class factory implementation which generates IL dynamically
to enable the fastest available performance when resolving objects. The generated code
handles constructor injection and property binding automatically, and allows an entire
application and its dependencies be loaded automatically using app.config or web.config
or programmatically.
**Three example projects are provided which demonstrates is usage**
**TechF.Example.BasicUsage** demonstrates simple programmatic usage, with constructor
injection and property binding.
**TechF.Examples.BasicUsageConfiguration** demonstrates app.config based factory configuration
with constructor injection and property binding
**TechF.Examples.BasicWebApi** demonstrates using the class factory to implement IDependencyResolver
and allow the class factory to construct WebApi controllers with constructor
injection and property binding
<file_sep>// Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace TechF.Examples.BasicWebApi
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Load class factory configuration from web.config
// Allows web.config to be the entry point for the
// application, and making it easy to deploy variations
// of the applications
var classFactoryConfig = TechF.Configuration.ConfigurationManager.ClassFactoryConfigurationFromConfigurationFile("ClassFactory");
ClassFactory.LoadFromConfiguration(classFactoryConfig);
config.DependencyResolver = new DependencyResolver();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
<file_sep>// Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TechF.Test
{
//ncrunch: no coverage start
public class ClassFactoryTests
{
[Test]
public void TestResolve()
{
ClassFactory.SetFactoryType<TestClass, TestClass>();
var o = ClassFactory.Resolve<TestClass>();
}
[Test]
[ExpectedException(typeof(Exceptions.ClassFactoryTypeMismatchException))]
public void TestTypeMismatch()
{
ClassFactory.SetFactoryType(typeof(TestClass3), typeof(TestClass));
}
[Test]
public void ResolveTwice()
{
ClassFactory.SetFactoryType<TestClass, TestClass>();
var o1 = ClassFactory.Resolve<TestClass>();
var o2 = ClassFactory.Resolve<TestClass>();
Assert.NotNull(o1);
Assert.NotNull(o2);
}
[Test]
[ExpectedException(typeof(Exceptions.ClassFactoryTypeMismatchException))]
public void ResolveNonConfiguredType()
{
ClassFactory.Resolve<TestClass2>();
}
}
//ncrunch: no coverage end
}
<file_sep> // Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TechF.Example.BasicUsage
{
public interface IDummyDataSource
{
string Text { get; }
}
public interface IDummyService
{
void Speak();
}
public class DummyDataSource : IDummyDataSource
{
// This property will be set automatically using property binding.
public string Text { get; set; }
}
public class DummyService : IDummyService
{
private IDummyDataSource _dataSource;
public DummyService(IDummyDataSource dataSource)
{
// The class factory generated code will automatically
// resolve reference types (besides string) using the class
// factory context. Value types will be resolved by parameter name
// in the property object provided on type configuration
_dataSource = dataSource;
}
public void Speak()
{
Console.WriteLine(_dataSource.Text);
}
}
// This is the main class for the application.
// By keeping a class which references all the major components,
// it is possible for the class factory to construct all depenncies
// and types automatically without the components needing to know
// about the class factory. This lets you reuse your entire application
// without being dependent on the class factory
public class Application
{
private IDummyService _service;
public Application(IDummyService service)
{
_service = service;
}
public void Run()
{
_service.Speak();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
public static void Main(string[] args)
{
// Enter Class Factory context
using(var context = new ClassFactoryContext())
{
// Create property dictionary to use for
// setting constructor argument and applying
// property binding
var props = ImmutableDictionary<string, string>.Empty.Add("Text", "Hello world!");
// Initialize IDummyDataSource to use the DummyDataSource
// implementation using the provided properties for property
// binding the Text property (properties are bound when they
// have a public set accesor)
context.SetFactoryType<IDummyDataSource, DummyDataSource>(props);
// Initialize IDummyService to use the DummyService
// implementation. The constructor argument dataSource
// is resolved using the class factory context on constructor
// call time
context.SetFactoryType<IDummyService, DummyService>();
// Initialize the main class Application. Application
// should have all needed services required as constructor
// arguments, so the class factory can initialize the entire
// application without any need to call the class factory
// later on in the application. This allows complete decoupling
// of the class factory component from the rest of the application
context.SetFactoryType<Application, Application>();
// Resolve the application object from the class factory
var application = context.Resolve<Application>();
// Run the application
application.Run();
}
}
}
}
<file_sep>// Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TechF.CodeGeneration
{
public static class ClassFactoryCodeGenerator
{
internal class TypeCodeCacheEntry
{
public Type Type { get; set; }
public ConstructorCall ConstructorCall { get; set; }
public PropertyBinder PropertyBinder { get; set; }
public IReadOnlyDictionary<string, string> Properties { get; set; }
public int FetchCount { get; set; }
}
private static Dictionary<Type, IList<TypeCodeCacheEntry>> _typeCodeCache = new Dictionary<Type, IList<TypeCodeCacheEntry>>();
private static ReaderWriterLock _typeCodeCacheLock = new ReaderWriterLock();
internal static TypeCodeCacheEntry GetCachedItem(Type type, IReadOnlyDictionary<string, string> props)
{
IList<TypeCodeCacheEntry> list = new List<TypeCodeCacheEntry>();
_typeCodeCacheLock.AcquireReaderLock(-1);
if(_typeCodeCache.ContainsKey(type))
list = _typeCodeCache[type];
_typeCodeCacheLock.ReleaseReaderLock();
var item = (from c in list where Utilities.DictionaryComparison<string, string>.Compare(c.Properties, props) select c).FirstOrDefault();
if(item == null)
item = Cache(type, props);
return item;
}
internal static TypeCodeCacheEntry Cache(Type type, IReadOnlyDictionary<string, string> props)
{
var ctorCall = CreateConstructorInvokeMethod(type, props);
var propBinder = CreatePropertyBinder(type, props);
return CacheItem(type, props, ctorCall, propBinder);
}
private static TypeCodeCacheEntry CacheItem(Type type, IReadOnlyDictionary<string, string> props, ConstructorCall ctorCall, PropertyBinder propBinder)
{
_typeCodeCacheLock.AcquireWriterLock(-1);
IList<TypeCodeCacheEntry> list = null;
if(_typeCodeCache.ContainsKey(type))
{
list = _typeCodeCache[type];
} else
{
list = new List<TypeCodeCacheEntry>();
_typeCodeCache.Add(type, list);
}
var entry = new TypeCodeCacheEntry()
{
Type = type,
ConstructorCall = ctorCall,
PropertyBinder = propBinder,
Properties = props,
FetchCount = 0
};
list.Add(entry);
_typeCodeCacheLock.ReleaseWriterLock();
return entry;
}
public delegate void PropertyBinder(object obj);
public delegate object ConstructorCall(ClassFactoryContext context);
private static void NullBinder(object obj) { }
private static void EmitDateTime(ILGenerator il, string value)
{
var method = typeof(DateTime).GetMethod("Parse", new Type[] { typeof(string) });
il.Emit(OpCodes.Ldstr, value);
il.Emit(OpCodes.Call, method);
}
private static void EmitDateTimeOffset(ILGenerator il, string value)
{
var method = typeof(DateTimeOffset).GetMethod("Parse", new Type[] { typeof(string) });
il.Emit(OpCodes.Ldstr, value);
il.Emit(OpCodes.Call, method);
}
private static void EmitEnum(ILGenerator il, Type type, string value)
{
object enumObj = Enum.Parse(type, value, true);
int i = (int)enumObj;
il.Emit(OpCodes.Ldc_I4, i);
}
private static void EmitDecimal(ILGenerator il, string value)
{
var method = typeof(Decimal).GetMethod("Parse", new Type[] { typeof(string) });
il.Emit(OpCodes.Ldstr, value);
il.Emit(OpCodes.Call, method);
}
private static bool EmitPropertyValue(ILGenerator il, Type type, string value)
{
if (type == typeof(string))
il.Emit(OpCodes.Ldstr, value);
else if (type == typeof(byte) || type == typeof(ushort) || type == typeof(uint))
il.Emit(OpCodes.Ldc_I4, Convert.ToUInt32(value));
else if (type == typeof(sbyte) || type == typeof(short) || type == typeof(int))
il.Emit(OpCodes.Ldc_I4, Convert.ToInt32(value));
else if (type == typeof(long))
il.Emit(OpCodes.Ldc_I8, Convert.ToInt64(value));
else if (type == typeof(ulong))
il.Emit(OpCodes.Ldc_I8, unchecked((long)Convert.ToUInt64(value)));
else if (type == typeof(bool))
il.Emit(OpCodes.Ldc_I4, Convert.ToBoolean(value) ? 1 : 0);
else if (type == typeof(float))
il.Emit(OpCodes.Ldc_R4, Convert.ToSingle(value));
else if (type == typeof(double))
il.Emit(OpCodes.Ldc_R8, Convert.ToDouble(value));
else if (type == typeof(decimal))
EmitDecimal(il, value);
else if (type == typeof(DateTime))
EmitDateTime(il, value);
else if (type == typeof(DateTimeOffset))
EmitDateTimeOffset(il, value);
else if (type.IsEnum)
//
EmitEnum(il, type, value);
return true;
}
public static PropertyBinder CreatePropertyBinder(Type type, IReadOnlyDictionary<string, string> props)
{
props = props ?? new Dictionary<string, string>();
if (props.Count < 1)
return NullBinder;
var properties = type.GetProperties().Where(x => x.SetMethod.IsPublic).ToArray();
if (properties.Length < 1)
return NullBinder;
var method = new DynamicMethod("", null, new Type[] { typeof(object) });
var il = method.GetILGenerator();
var obj = il.DeclareLocal(type);
var propertyLocals = new LocalBuilder[properties.Length];
for (int i = 0; i < properties.Length; i++)
propertyLocals[i] = il.DeclareLocal(properties[i].PropertyType);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, type);
il.Emit(OpCodes.Stloc, obj);
for (int i = 0; i < properties.Length; i++)
{
var property = properties[i];
if (!(property.PropertyType == typeof(string) || property.PropertyType.IsValueType))
continue;
if (props.ContainsKey(property.Name))
{
if (EmitPropertyValue(il, property.PropertyType, props[property.Name]))
{
il.Emit(OpCodes.Stloc, propertyLocals[i]);
il.Emit(OpCodes.Ldloc, obj);
il.Emit(OpCodes.Ldloc, propertyLocals[i]);
il.Emit(OpCodes.Call, property.SetMethod);
}
}
}
il.Emit(OpCodes.Ret);
return (PropertyBinder)method.CreateDelegate(typeof(PropertyBinder));
}
public static ConstructorCall CreateConstructorInvokeMethod(Type type, IReadOnlyDictionary<string, string> props)
{
var method = new DynamicMethod("", typeof(object), new Type[] { typeof(ClassFactoryContext) });
var il = method.GetILGenerator();
foreach (var ctor in type.GetConstructors())
{
if (!ctor.IsPublic) continue;
bool resolvedValueParameters = true;
foreach (var param in ctor.GetParameters())
if ((param.ParameterType.IsValueType || param.ParameterType == typeof(string)) && !props.ContainsKey(param.Name))
{
resolvedValueParameters = false;
break;
}
if (resolvedValueParameters)
{
// This constructor is usable
// Generate IL code
MethodInfo contextResolveMethod = typeof(ClassFactoryContext).GetMethods().Where(x => x.IsPublic && x.Name == "Resolve" && x.ContainsGenericParameters).Single();
MethodInfo globalMethod = typeof(ClassFactory).GetMethods().Where(x => x.Name == "Resolve" && x.ContainsGenericParameters).Single();
var parameters = ctor.GetParameters();
var paramLocals = new LocalBuilder[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
paramLocals[i] = il.DeclareLocal(parameters[i].ParameterType);
for (int i = 0; i < parameters.Length; i++)
{
var param = parameters[i];
if (param.ParameterType.IsValueType || param.ParameterType == typeof(string))
{
EmitPropertyValue(il, param.ParameterType, props[param.Name]);
il.Emit(OpCodes.Stloc, paramLocals[i]);
}
else
{
var labelWithContext = il.DefineLabel();
var labelAfterContext = il.DefineLabel();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Brtrue, labelWithContext);
// Without class factory
var genericMethod = globalMethod.MakeGenericMethod(new Type[] { param.ParameterType });
il.Emit(OpCodes.Call, genericMethod);
il.Emit(OpCodes.Stloc, paramLocals[i]);
il.Emit(OpCodes.Br, labelAfterContext);
il.MarkLabel(labelWithContext);
// With class factory context
var genericMethodContext = contextResolveMethod.MakeGenericMethod(new Type[] { param.ParameterType });
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, genericMethodContext);
il.Emit(OpCodes.Stloc, paramLocals[i]);
il.MarkLabel(labelAfterContext);
}
}
for (int i = 0; i < parameters.Length; i++)
il.Emit(OpCodes.Ldloc, paramLocals[i]);
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Ret);
return (ConstructorCall)method.CreateDelegate(typeof(ConstructorCall));
}
}
throw new Exceptions.ClassFactoryConstructorException("No supported constructors are available");
}
}
}
<file_sep>// Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TechF.Examples.BasicUsageConfiguration
{
public interface IDummyDataSource
{
string Text { get; set; }
}
public interface IDummyService
{
void Speak();
}
public class DummyDataSource : IDummyDataSource
{
public string Text { get; set; }
}
public class DummyService : IDummyService
{
private IDummyDataSource _dataSource;
public DummyService(IDummyDataSource dataSource)
{
_dataSource = dataSource;
}
public void Speak()
{
Console.WriteLine(_dataSource.Text);
}
}
public class Application
{
private IDummyService _service;
public Application(IDummyService service)
{
_service = service;
}
public void Run()
{
_service.Speak();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
public static void Main(string[] args)
{
var config = TechF.Configuration.ConfigurationManager.ClassFactoryConfigurationFromConfigurationFile("ClassFactory");
ClassFactory.LoadFromConfiguration(config);
using (var context = new ClassFactoryContext())
{
var application = context.Resolve<Application>();
application.Run();
}
}
}
}
<file_sep>// Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TechF.Configuration;
namespace TechF
{
/// <summary>
/// Global Class Factory singleton. Configures global factories and properties
/// </summary>
public class ClassFactory
{
//ncrunch: no coverage start
internal static Dictionary<System.Type, ClassFactoryBinder> _factories = new Dictionary<Type, ClassFactoryBinder>();
internal static ReaderWriterLock _factoriesLock = new ReaderWriterLock();
//ncrunch: no coverage end
private static ClassFactoryBinder ResolveBinder(Type type)
{
_factoriesLock.AcquireReaderLock(-1);
var binder = _factories.ContainsKey(type) ? _factories[type] : null;
_factoriesLock.ReleaseReaderLock();
return binder;
}
/// <summary>
/// Resolve a object for the specified type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static object Resolve(Type type)
{
var binder = ResolveBinder(type);
if(binder != null)
return binder.Create();
throw new Exceptions.ClassFactoryTypeMismatchException();
}
/// <summary>
/// Resolve a object for the specified type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Resolve<T>() where T : class
{
return (T)Resolve(typeof(T));
}
/// <summary>
/// Remove the configuration for the specified type
/// </summary>
/// <param name="type"></param>
public static void ClearFactoryTypeInformation(Type type)
{
_factoriesLock.AcquireWriterLock(-1);
if (_factories.ContainsKey(type))
_factories.Remove(type);
_factoriesLock.ReleaseWriterLock();
}
/// <summary>
/// Remove the configuration for the specified type
/// </summary>
/// <typeparam name="T"></typeparam>
public static void ClearFactoryTypeInformation<T>()
{
ClearFactoryTypeInformation(typeof(T));
}
/// <summary>
/// Configure a factory for the given type using the provided
/// constant values used in constructor injection and property binding
/// </summary>
/// <param name="type">The type to configure</param>
/// <param name="factoryType">The type that implements 'type'</param>
/// <param name="properties">Constant properties for parameter binding and constructor injection</param>
/// <returns>A options object that can be used for setting persistence and property binding</returns>
public static ClassFactoryOptions SetFactoryType(Type type, Type factoryType, ImmutableDictionary<string, string> properties = null)
{
if (!type.IsAssignableFrom(factoryType))
throw new Exceptions.ClassFactoryTypeMismatchException();
var binder = new ClassFactoryBinder(null, factoryType, properties);
_factoriesLock.AcquireWriterLock(-1);
_factories[type] = binder;
_factoriesLock.ReleaseWriterLock();
return binder._options;
}
/// <summary>
/// Configure a factory for the given type using the provided
/// constant values used in constructor injection and property binding
/// </summary>
/// <typeparam name="TType">The type to configure</typeparam>
/// <typeparam name="TImplementation">The type that implements 'type'</typeparam>
/// <param name="properties">Constant properties for parameter binding and constructor injection</param>
/// <returns>A options object that can be used for setting persistence and property binding</returns>
public static ClassFactoryOptions SetFactoryType<TType, TImplementation>(ImmutableDictionary<string, string> properties = null) where TType : class where TImplementation : TType
{
return SetFactoryType(typeof(TType), typeof(TImplementation), properties);
}
//ncrunch: no coverage start
/// <summary>
/// Load class factory configuration
/// </summary>
/// <param name="configuration"></param>
public static void LoadFromConfiguration(IClassFactoryConfiguration configuration)
{
foreach (var factory in configuration.ClassFactories)
{
var typeName = factory.Type;
var factoryTypeName = factory.FactoryType;
var props = factory.FactoryProperties ?? new IClassFactoryProperty[] { };
ImmutableDictionary<string, string> factoryBinder = props.ToImmutableDictionary(x => x.Name, x => x.Value);
try
{
Type type = Type.GetType(typeName);
Type factoryType = Type.GetType(factoryTypeName);
if (type != null && factoryType != null && type.IsAssignableFrom(factoryType))
{
SetFactoryType(type, factoryType, factoryBinder).Persist = factory.PersistPerContext;
}
}
catch
{
}
}
}
//ncrunch: no coverage end
}
}
<file_sep>// Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TechF.Utilities;
namespace TechF.Test
{
public class DictionaryComparisonTests
{
[Test]
public void TestSameDictionariesAreEqual()
{
var d = new Dictionary<string, string>();
Assert.IsTrue(DictionaryComparison<string, string>.Compare(d, d));
}
[Test]
public void TestIdenticalDictionariesAreEqual()
{
var d1 = new Dictionary<string, string>();
var d2 = new Dictionary<string, string>();
d1.Add("test", "test");
d2.Add("test", "test");
Assert.IsTrue(DictionaryComparison<string, string>.Compare(d1, d2));
}
[Test]
public void TestIdenticalKeysDifferentValuesAreNotEqual()
{
var d1 = new Dictionary<string, string>();
var d2 = new Dictionary<string, string>();
d1.Add("test", null);
d2.Add("test", "test2");
Assert.IsFalse(DictionaryComparison<string, string>.Compare(d1, d2));
}
[Test]
public void TestDifferentKeysAreNotEqual()
{
var d1 = new Dictionary<string, string>();
var d2 = new Dictionary<string, string>();
d1.Add("test", "test2");
d2.Add("test2", "test2");
Assert.IsFalse(DictionaryComparison<string, string>.Compare(d1, d2));
}
[Test]
public void TestDifferentNumberOfKeysAreNotEqual()
{
var d1 = new Dictionary<string, string>();
var d2 = new Dictionary<string, string>();
d1.Add("test", "test2");
d2.Add("test", "test2");
d1.Add("test1", "test2");
Assert.IsFalse(DictionaryComparison<string, string>.Compare(d1, d2));
}
}
}
<file_sep>// Tech-F Framework
// (C) Copyright 2014 <NAME><<EMAIL>>
//
// All rights reserved.This program and the accompanying materials
// are made available under the terms of the GNU Lesser General Public License
// (LGPL) version 2.1 which accompanies this distribution, and is available at
// http://www.gnu.org/licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
// Lesser General Public License for more details.
//
// Contributors:
// <NAME><<EMAIL>>
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TechF.CodeGeneration;
namespace TechF
{
public class ClassFactoryOptions
{
internal ClassFactoryOptions(ClassFactoryBinder binder)
{
_binder = new WeakReference<ClassFactoryBinder>(binder);
}
private WeakReference<ClassFactoryBinder> _binder;
public bool Persist
{
set
{
ClassFactoryBinder binder = null;
if (_binder.TryGetTarget(out binder))
{
binder._optionsLock.AcquireWriterLock(-1);
binder._persist = value;
binder._optionsLock.ReleaseWriterLock();
}
}
}
public bool BindProperties
{
set
{
ClassFactoryBinder binder = null;
if (_binder.TryGetTarget(out binder))
{
binder._optionsLock.AcquireWriterLock(-1);
binder._bindProperties = value;
binder._optionsLock.ReleaseWriterLock();
}
}
}
}
public class ClassFactoryBinder
{
internal ClassFactoryBinder(ClassFactoryContext context, ClassFactoryBinder binder)
{
_context = context;
_type = binder._type;
_ctorCall = binder._ctorCall;
_properties = binder._properties;
_options = new ClassFactoryOptions(this);
_persist = binder._persist;
_lastBuild = new WeakReference(null);
}
internal ClassFactoryBinder(ClassFactoryContext context, Type type, ImmutableDictionary<string, string> properties)
{
_context = context;
_type = type;
_properties = properties;
_options = new ClassFactoryOptions(this);
_lastBuild = new WeakReference(null);
}
internal ClassFactoryContext _context;
internal Type _type;
internal Func<ClassFactoryBinder, object> _build;
internal WeakReference _lastBuild = null;
internal ImmutableDictionary<string, string> _properties;
internal bool _persist;
internal bool _bindProperties = true;
internal ClassFactoryOptions _options;
internal ReaderWriterLock _optionsLock = new ReaderWriterLock();
internal ClassFactoryCodeGenerator.ConstructorCall _ctorCall = null;
internal ClassFactoryCodeGenerator.PropertyBinder _propBinder = null;
internal void Bind(object obj)
{
if (_propBinder == null)
{
var cachedCode = ClassFactoryCodeGenerator.GetCachedItem(_type, _properties);
_propBinder = cachedCode.PropertyBinder;
}
_propBinder(obj);
}
internal object Create()
{
if (_ctorCall == null)
_ctorCall = ClassFactoryCodeGenerator.GetCachedItem(_type, _properties).ConstructorCall;
var persist = false;
var propertyBind = false;
_optionsLock.AcquireReaderLock(-1);
persist = _persist;
propertyBind = _bindProperties;
_optionsLock.ReleaseReaderLock();
if (_context == null)
{
// Do not persist in global scope
var o = _ctorCall(null);
if (propertyBind)
Bind(o);
return _ctorCall(null);
}
var lastBuild = _lastBuild.Target;
if (lastBuild != null && _lastBuild.IsAlive && persist)
return lastBuild;
lastBuild = _ctorCall(_context);
if (propertyBind)
Bind(lastBuild);
_lastBuild.Target = lastBuild;
return lastBuild;
}
}
}
| a8d22442eb32fc3d948bd23089d4d7ee53ce7c15 | [
"Markdown",
"C#"
] | 15 | C# | FredrikTheEvil/Tech-F | bf06980517cb946a07a656288a203a9a26f2ddad | b6e5cbecc048a414a1afdb6b7f192b0abc3ea260 | |
refs/heads/master | <file_sep>import { Ng6UdmMockService } from 'ng6-udm-mock';
import { UdmCommentDataSource } from './udm-comment-datasource';
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { MatPaginator, MatSort } from '@angular/material';
import { tap } from 'rxjs/operators';
import { environment } from '../../environments/environment';
@Component({
selector: 'app-udm-table',
templateUrl: './udm-table.component.html',
styleUrls: ['./udm-table.component.css']
})
export class UdmTableComponent implements AfterViewInit, OnInit {
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
commentDataSource: UdmCommentDataSource;
displayedColumns = ['id', 'postId', 'name', 'email', 'body'];
// displayedColumns = ['id', 'postId', 'name', 'email'];
constructor(private sv: Ng6UdmMockService) {
}
ngOnInit() {
this.sv.setBaseUrl(environment.udmMockBaseUrl);
this.commentDataSource = new UdmCommentDataSource(this.paginator, this.sort, this.sv);
this.commentDataSource.loadComments();
}
private loadComments() {
this.commentDataSource.loadComments();
}
ngAfterViewInit() {
this.paginator.page
.pipe(
tap(() => this.loadComments())
)
.subscribe();
}
}
<file_sep>
# _Ng6UdmMockMatConsumer_ Table with sorting and paging functions based on Angular Material in Angular6
[](LICENSE)
_Ng6UdmMockMatConsumer_ is a initial set for those who want to make tables with sorting and paging functions by Angular Material in Angular6.
_This full source code_,
<https://github.com/Ohtsu/ng6-udm-mock-mat-consumer>
_Video Explanation (Japanese)_,
<https://youtu.be/AsVctVk0Hxk>
_Video Explanation (English)_,
<https://youtu.be/qt6TsDoQR7g>
## Overview
- _Ng6UdmMockMatConsumer_ is a table sample project based on Angular Material in Angular6.
- _Ng6UdmMockMatConsumer_ uses mat-table, mat-paginator, mat-sort and so on.
- _Ng6UdmMockMatConsumer_ uses ng6-udm-mock(ver3.0.2) service library for accessing JsonPlaceholder site.
## Prerequisite
- node.js
- Typescript2
- Angular6
- Angular Material
- ng6-udm-mock
## Installation
To install this project, run simply:
```bash
$ npm install
```
## Start project
If you start your local server as follows, you can get a table containing the comment data of JsonPlaceholder site in your browser by accessing **http://localhost:4200**.
```bash
$ ng serve -o
```
- ***First Page***
<img src="https://raw.githubusercontent.com/Ohtsu/images/master/ng6-material/Table01.gif" width= "900" >
## Version
- Ng6UdmMockMatConsumer : 0.1.0
- Angular6 : 6.0.3
- TypeScript : 2.7.2
- @angular/material : 6.4.7
- ng6-udm-mock : 3.0.2
## Reference
- "Schematics",
<https://material.angular.io/guide/schematics>
- "JsonPlaceholder",
<https://jsonplaceholder.typicode.com/>
- "Angular 5, Angular 6 Custom Library: Step-by-step guide",
<https://www.udemy.com/angular5-custom-library-the-definitive-step-by-step-guide/>
(Discount Coupon until 2018/9/30)
<https://www.udemy.com/angular5-custom-library-the-definitive-step-by-step-guide/?couponCode=NG5-CUSLIB-EN-1001>
- "Angular 5, Angular 6用 カスタムライブラリの作成: 完全ステップ・バイ・ステップ・ガイド",
<https://www.udemy.com/angular5-l/>
(割引クーポン 2018/9/30まで)
<https://www.udemy.com/angular5-l/?couponCode=NG5-CUSLIB-JA-0930>
- "ng6-udm-mock Angular6 Service Library to use JsonPlaceholder and json-server",
<https://www.npmjs.com/package/ng6-udm-mock>
- "Reactive Programming with RxJS 5: Untangle Your Asynchronous JavaScript Code", 2018/2/15,<NAME>
<https://www.amazon.co.jp/Reactive-Programming-RxJS-Asynchronous-JavaScript/dp/1680502476/ref=sr_1_7?ie=UTF8&qid=1537063252&sr=8-7&keywords=reactive+programming>
- "Angular Material Data Table: A Complete Example", Angular University
<https://blog.angular-university.io/angular-material-data-table/>
- "Angular 5 Data Table Example(Pagination+Sorting+Filtering)", 2018/01, <NAME>
<https://blog.angular-university.io/angular-material-data-table/>
## Change Log
- 2018.9.18 version 0.1 uploaded
## Copyright
copyright 2018 by <NAME> (DigiPub Japan)
## License
MIT © [<NAME>](<EMAIL>)
<file_sep>import { DataSource, CollectionViewer } from '@angular/cdk/collections';
import { MatPaginator, MatSort } from '@angular/material';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge, BehaviorSubject } from 'rxjs';
import { Ng6UdmMockService } from 'ng6-udm-mock';
import { UdmComment } from 'ng6-udm-mock';
export class UdmCommentDataSource extends DataSource<UdmComment> {
private commentsSubject = new BehaviorSubject<UdmComment[]>([]);
comments: UdmComment[];
constructor(private paginator: MatPaginator, private sort: MatSort, private sv: Ng6UdmMockService) {
super();
}
loadComments() {
this.sv.getAllComments()
.subscribe(dt => {
this.commentsSubject.next(dt);
this.comments = dt;
});
}
connect(collectionViewer: CollectionViewer): Observable<UdmComment[]> {
const dataMutations = [
this.commentsSubject.asObservable(),
this.paginator.page,
this.sort.sortChange
];
this.paginator.length = this.comments.length;
return merge(...dataMutations).pipe(map(() => {
return this.getPagedData(this.getCommentsSortedData([...this.comments]));
}));
}
disconnect(collectionViewer: CollectionViewer): void {
this.commentsSubject.complete();
}
private getPagedData(comments: UdmComment[]) {
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return comments.splice(startIndex, this.paginator.pageSize);
}
private getCommentsSortedData(comments: UdmComment[]) {
if (!this.sort.active || this.sort.direction === '') {
return comments;
}
return comments.sort((a, b) => {
const isAsc = this.sort.direction === 'asc';
switch (this.sort.active) {
case 'id': return compare(+a.id, +b.id, isAsc);
case 'postId': return compare(+a.postId, +b.postId, isAsc);
case 'name': return compare(a.name, b.name, isAsc);
case 'email': return compare(a.email, b.email, isAsc);
case 'body': return compare(a.body, b.body, isAsc);
default: return 0;
}
});
}
}
function compare(a, b, isAsc) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
| fa2d0144a7bc1e2aadd1a1f9005bb7e64aea0774 | [
"Markdown",
"TypeScript"
] | 3 | TypeScript | Ohtsu/ng6-udm-mock-mat-consumer | d2904fd4c858c7790d89b3e8c127cac284a131d8 | f3a296bae97d9af9aaf09ef0153bc29ae3eb5ccd | |
refs/heads/master | <file_sep>module.exports = app => {
app.locals.title = 'Music Time!'
}<file_sep>require('dotenv').config()
const express = require("express")
const router = express.Router()
const User = require("../models/user.model")
const Playlist = require("../models/playlist.model")
//////////////////////AUTENTICACIÓN SPOTI////////////////
const SpotifyWebApi = require("spotify-web-api-node"); //meter aquí configs
const spotifyApi = new SpotifyWebApi({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
redirectUri: 'http:localhost:3000/playlist/details'
/* CLIENT_ID=db5476df850242edbfc2443e875f75b2
CLIENT_SECRET=e92667f3f707483d963d299ca82dee54 */
});
spotifyApi.clientCredentialsGrant().then((data) => {
spotifyApi.setAccessToken(data.body["access_token"])
console.log("todo correct con el spotify token")
}).catch((error) => console.log("Something went wrong when retrieving an access token", error));
//////////////////////////////////////////////////////////
function getArtist(value) {
return new Promise(resolve => {
let artist = ""
spotifyApi.searchArtists(value)
.then((data) => {
artist = data.body.artists.items[0].id
//console.log('Id del artista', artist)
resolve(getAlbums(artist));
return getAlbums(artist)
})
.catch((err) => console.log("The error while searching artists occurred: ", err));
});
}
function getAlbums(artist) {
let albumsArr = []
spotifyApi.getArtistAlbums(artist)
.then((data) => {
let albumsId = data.body.items
albumsArr = albumsId.map(e => e.id)
//console.log('ID de albums', albumsArr)
return getTracks(albumsArr)
})
.catch((err) => console.log("The error while searching albums occurred: ", err))
}
// function getAlbums(artist) {
// let albumsArr = []
// return ("HOLA", data) //hasta aquí llega, en el then da undefined
// spotifyApi.getArtistAlbums(artist)
// .then((data) => {
// let albumsId = data.body.items
// albumsArr = albumsId.map(e => e.id)
// //console.log('ID de albums', albumsArr)
// return getTracks(albumsArr)
// })
// .catch((err) => console.log("The error while searching albums occurred: ", err))
// return ("HOLA", data)
// }
function getRandomTracks(duration) {
console.log(duration)
return new Promise(resolve => {
let randomizer = getRandomSearch()
let randomList = []
spotifyApi.searchTracks(randomizer, { limit: 50 }) ///LÍMITE DE 50, sino se especifica es de 20
.then((data) => {
let datos = data.body.tracks.items
return datos
})
.then((data) => {
data.forEach(e => randomList.push(e))
//console.log('Lista Random', randomList)
return resolve(getDetails(randomList, duration))
})
.catch((err) => console.log("The error while searching random tracks occurred: ", err))
})
}
/////////////////////@perrydrums git
function getRandomSearch() {
// A list of all characters that can be chosen.
const characters = 'abcdefghijklmnopqrstuvwxyz';
// Gets a random character from the characters string.
const randomCharacter = characters.charAt(Math.floor(Math.random() * characters.length));
let randomSearch = '';
// Places the wildcard character at the beginning, or both beginning and end, randomly.
switch (Math.round(Math.random())) {
case 0:
randomSearch = '%' + randomCharacter;
break;
case 1:
randomSearch = '%' + randomCharacter + '%';
break;
}
return randomSearch;
}
let arrEmpty = []
function getTracks(albums) {
albums.forEach(element => {
spotifyApi.getAlbumTracks(element)
.then((data) => {
let tracksId = data.body.items
tracksId.forEach(elm => { arrEmpty.push(elm) })
})
.catch((err) => console.log("The error while searching tracks occurred: ", err))
})
getDetails(arrEmpty)
arrEmpty = [""]
}
function getDetails(songs, duration1) {
let arrSong = []
songs.forEach(e => {
const datos =
{ name: e.name, id: e.id, duration: Math.floor(e.duration_ms / 1000), artist: e.artists, preview: e.preview_url }
arrSong.push(datos)
})
//pasarle tiempo
return createRandomPlaylist(duration1, arrSong)
}
function createRandomPlaylist(durationMap, songs) {
//todo en segundos
const MAX = durationMap * 60
let cont = 0
let playlist = []
songs.shift() //porque la primera salía undefined??
const randomizedArr = shuffle(songs)
songs.forEach(e => {
if ((cont <= MAX)) {
playlist.push(e)
cont = cont + (e.duration)
}
// console.log(e.duration) //1m - 60.000,ms, matemáticas allá voy! | 1s - 1000ms
})
playlist.forEach(e => {
//console.log('---------')
//console.log(e.name)
})
//console.log('RESULTADO FUNCIoN', playlist)
return playlist
}
//////Shuffle para array (stackoverflow)
function shuffle(array) {
let currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
router.get("/details", (req, res) => res.render('playlist/details'))
router.post("/details", (req, res, next) => {
console.log(req.body)
const { playlist, duration } = req.body
console.log('playlist', playlist) //create aqui
console.log('duration', duration)
const allUsers = User.find()
//METER IF PARA ASYNCALLs DISTINTAS, o meterlas en el mismo cuando furule la de artistas
async function asyncCall(duration) {
console.log(duration);
const resultRandom = await getRandomTracks(duration);
return resultRandom
}
async function asyncCallArt(artist) {
console.log(artist)
const resultArtist = await getArtist(artist);
console.log('ASYNC RESULT ARTIST', resultArtist);
return resultArtist
}
asyncCall(duration).then(data => {
res.render('playlist/details', {data})
console.log(data)
})
// asyncCallArt(artist).then(data => {
// res.send(data)
// console.log(data)
// })
})
router.get('/new', (req, res) => res.render('playlist/details')) //no vale
router.post('/new', (req, res) => {
console.log(req.body)
const {title, tracks, user, duration} = req.body
console.log('REQBODY', {title, tracks, user, duration})
console.log('hola',tracks)
Playlist
.create({title, tracks, user, duration})
.then(() => res.redirect('/playlist/details')) //MIRAR BIEN
.catch(err => console.log(err))
})
module.exports = router<file_sep># Music Time!
Have you ever needed a playlist according to the time of the trip you are going to do? 'Music Time!' is the solution!
## Features
In this webapp you choose the journey you gonna do and then you will have a playlist according to the time of that trip.
## Technologies used in this project
- Javascript
- HTML
- CSS
- Handlebars
- Express
- NodeJS
- Mongoose
<file_sep>// console.log("AQUÍ ESTAMOS, desde el axios para spoti")
// //////////////////////AUTENTICACIÓN SPOTI////////////////
// const SpotifyWebApi = require("spotify-web-api-node");
// const spotifyApi = new SpotifyWebApi({
// clientId: process.env.CLIENT_ID,
// clientSecret: process.env.CLIENT_SECRET,
// redirectUri: 'http:localhost:3000/playlist/new'
// /* CLIENT_ID=db5476df850242edbfc2443e875f75b2
// CLIENT_SECRET=e92667f3f707483d963d299ca82dee54 */
// });
// spotifyApi.clientCredentialsGrant().then((data) => {
// console.log(process.env.CLIENT_ID)
// spotifyApi.setAccessToken(data.body["access_token"])
// console.log("todo correct con el spotify token")
// }).catch((error) => console.log("Something went wrong when retrieving an access token", error));
// //////////////////////////////////////////////////////////
// const axiosApp = axios.create({
// baseURL: 'https://localhost:3000/playlist'
// })
// axios({
// url: 'https://accounts.spotify.com/api/token',
// method: 'post',
// params: {
// grant_type: 'client_credentials'
// },
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded'
// },
// auth: {
// username: 'db<PASSWORD>',
// password: '<PASSWORD>'
// }
// }).then(function (response) {
// console.log(response);
// }).catch(function (error) {
// });
/// Título playlist
// document.querySelector('#playlistForm').onsubmit = e => {
// console.log('entras?')
// e.preventDefault()
// const artistInput = document.querySelector('#playlistForm input').value
// console.log(artistInput)
// //getArtist(artistInput)
// }
// function getArtist(artist) {
// console.log('entras en', artist)
// axios({
// url: 'https://api.spotify.com/v1/artist',
// method: 'GET',
// dataType: 'json',
// data: {
// type: 'artist',
// q: artist
// }
// })
// .then(response => console.log(response))
// .catch(err => console.log('Error en getArtist', err))
// }
<file_sep>module.exports = app => {
// Base URLS
app.use('/', require('./index.routes'))
app.use('/', require('./auth.routes'))
// app.use('/user', require('./base.routes'))
app.use('/playlist', require('./playlist.routes'))
// app.use('/playlistCRUD', require('./playlistCRUD.routes'))
}
<file_sep>const mongoose = require("mongoose")
const Schema = mongoose.Schema
const playlistSchema = new Schema({
title: {
type: String,
default: 'Playlist',
maxlength: 25
},
tracks: {
type :[String],
},
user: { type: Schema.Types.ObjectId, ref: 'User' },
duration: {
type: Number,
},
}, {
timestamps: true
})
const Playlist = mongoose.model("Playlist", playlistSchema)
module.exports = Playlist | 777f9eeb34a03dfffc29e3373c82482753f14c73 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | tirsodelalamo/Music-Time-Project | f3d39399fb7fdbbcc80cad189dc1c667fde8552e | 20785f086179cb348dbd23dbab9bab1713a9bb71 | |
refs/heads/master | <file_sep>package oop.ex4.data_structures;
public class AvlTree extends BinaryTree {
/**
* constructor that creates an AVL tree without nodes.
*/
public AvlTree(){
super();
}
/**
* Constructor that creates an AVL tree from a given array
* @param data int array
*/
public AvlTree(int[] data) {
super(data);
}
/**
* Constructor that creates an AVL tree as a copy of an existing AVL tree
* @param avlTree AVL tree to copy
*/
public AvlTree(AvlTree avlTree) {
super(avlTree);
}
/**
* Get minimum number of nodes in a tree of height h
* @param h height of tree
* @return minimum
*/
public static int findMinNodes(int h) {
double res = fib(h+3)-1;
return (int)res;
}
/**
* Calculates the nth Fibonacci number, using Binet's Formula
* see also: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html
* @param n Fibonacci number wanted
* @return fibonacci number
*/
private static double fib(int n) {
double phi = (Math.sqrt(5)+1)/2;
return (Math.pow(phi, n)-Math.pow(-phi, -n))/Math.sqrt(5);
}
/**
* Get maximum number of nodes in a tree of height h
* @param h height of tree
* @return maximum
*/
public static int findMaxNodes(int h) {
return (int)Math.pow(2, h+1)-1;
}
/**
* Add a new node with the given key to the tree.
* @param newValue the value of the new node to add.
* @return true if the value to add is not already in the tree and it was successfully added,
* false otherwise.
*/
@Override
public boolean add(int newValue){
if (! super.add(newValue)) {
return false;
}
root = balanceTree(newValue, root);
return true;
}
/**
* Delete a node with the given key to the tree.
* @param toDelete the value of the new node to delete.
* @return true if the value to delete is in the tree and it was successfully deleted,
* false otherwise.
*/
@Override
public boolean delete(int toDelete){
if (! super.delete(toDelete)){
return false;
}
root = balanceTree(toDelete, root);
return true;
}
/**
* This function rebalances the tree if the AVL invariant is violated
* @param addedValue the value that was added to the tree
* @param currentNode node - initialize as root
* @return root of the tree after balancing
*/
private TreeNode balanceTree(int addedValue, TreeNode currentNode) {
if (currentNode == null) {
return null;
}
if (currentNode.nodeData > addedValue) {
currentNode.leftSon = balanceTree(addedValue, currentNode.leftSon);
}
else if (currentNode.nodeData < addedValue) {
currentNode.rightSon = balanceTree(addedValue, currentNode.rightSon);
}
/* Maintain height attribute of node */
currentNode.height = getHeight(currentNode);
if (Math.abs(getBalanceFactor(currentNode)) == 2) {
return rotate(currentNode);
}
return currentNode;
}
/**
* Gets the height of a node in the tree
* @param node node checked
* @return height of node
*/
private int getHeight(TreeNode node) {
if (node == null) {
return -1;
}
return Math.max(getHeight(node.leftSon),
getHeight(node.rightSon)) + 1;
}
/**
* Gets the current balance factor of the node
* @param node node checked
* @return balance factor - int between -2 and 2. Where 2 is left-heavy, and -2 right-heavy.
*/
private int getBalanceFactor(TreeNode node) {
return getHeight(node.leftSon) - getHeight(node.rightSon);
}
/* class listing all possible violation types */
private enum ViolationTypes {RL, RR, LL, LR}
/**
* Rotates the subtree that the node is the root of, according to the type of violation
* @param unbalancedNode node that violates the AVL invariant
* @return root of subtree (can be different than the one supplied)
*/
private TreeNode rotate(TreeNode unbalancedNode) {
TreeNode subtreeRoot = unbalancedNode;
try {
ViolationTypes violationType = getViolationType(unbalancedNode);
switch (violationType) {
case LL:
subtreeRoot = rightRotate(unbalancedNode);
break;
case LR:
unbalancedNode.leftSon = leftRotate(unbalancedNode.leftSon);
subtreeRoot = rightRotate(unbalancedNode);
break;
case RR:
subtreeRoot = leftRotate(unbalancedNode);
break;
case RL:
unbalancedNode.rightSon = rightRotate(unbalancedNode.rightSon);
subtreeRoot = leftRotate(unbalancedNode);
break;
}
subtreeRoot.rightSon.height = getHeight(subtreeRoot.rightSon);
subtreeRoot.leftSon.height = getHeight(subtreeRoot.leftSon);
subtreeRoot.height = getHeight(subtreeRoot);
return subtreeRoot;
}
catch (NoViolationException e) { return subtreeRoot; }
}
/**
* Determines what kind of violation has occurred in the node violating the AVL invariant
* @param unbalancedNode node violating AVL invariant
* @return violation type
*/
private ViolationTypes getViolationType(TreeNode unbalancedNode) throws NoViolationException {
if (getBalanceFactor(unbalancedNode) == 2) {
if (unbalancedNode.leftSon.leftSon != null){
return ViolationTypes.LL;
} else if (unbalancedNode.leftSon.rightSon != null) {
return ViolationTypes.LR;
}
} else if (getBalanceFactor(unbalancedNode) == -2) {
if (unbalancedNode.rightSon.leftSon != null){
return ViolationTypes.RL;
} else if (unbalancedNode.rightSon.rightSon != null) {
return ViolationTypes.RR;
}
}
throw new NoViolationException();
}
/**
* Rotates the tree left
* @param subtreeRoot root of subtree to rotate
* @return root of subtree (can be different than the one supplied)
*/
private TreeNode leftRotate(TreeNode subtreeRoot) {
TreeNode newRoot = subtreeRoot.rightSon;
TreeNode transferredSon = newRoot.leftSon;
newRoot.leftSon = subtreeRoot;
subtreeRoot.rightSon = transferredSon;
return newRoot;
}
/**
* Rotates the tree right
* @param subtreeRoot root of subtree to rotate
* @return root of subtree (can be different than the one supplied)
*/
private TreeNode rightRotate(TreeNode subtreeRoot) {
TreeNode newRoot = subtreeRoot.leftSon;
TreeNode transferredSon = newRoot.rightSon;
newRoot.rightSon = subtreeRoot;
subtreeRoot.leftSon = transferredSon;
return newRoot;
}
}
| 6eb738eb19313c1920e351798eaa900643ba0ba2 | [
"Java"
] | 1 | Java | matancha/ex4-avl-trees | c0572587ea828784d68938d856b30bded0453ea3 | 19a4b698eb575f57df83aab467c7cd7fce6d3f29 | |
refs/heads/master | <file_sep>from re import sub
def psec( cfg, arg ):
### return option from cfg
for c in cfg:
c = str( c )
if arg in c:
c = str( c.split(':')[-1] ).strip()
return c
return
def pcfg( cfg, sec ):
### parse lines of cfg for section
g = []
x = 0
for ln in cfg:
ln = str( ln )
if x == 1:
if 'END' in ln:
break
else:
ln = str( sub( '\n', '', ln ) ).strip()
ln = str( sub( ' ', ' ', ln ) )
ll = len( ln )
if ll > 1:
g.append( ln )
if sec in ln:
x = 1
return g
<file_sep>#!/usr/bin/env python
### convert directory of images for b64css div template
from base64 import b64encode
from sys import argv, exit
from os import path, listdir, remove, getcwd
from re import sub
exist = path.exists
join = path.join
sep = path.sep
def fatal( err ):
err = str( 'FATAL : %s' % err )
print( err )
exit(1)
def Usage():
print('USAGE : ./b64dir.py /image/directory /out/file.css')
exit(1)
def crender( md, b6, ires ):
### css
src= ''' div.%s {
background:url(data:image/svg+xml;base64,%s);
width: %spx; height: %spx;
background-size: %spx %spx;
background-repeat: no-repeat;
}''' % ( md, b6, ires, ires, ires, ires )
return src
def invertHex(hexNumber):
#invert a hex number
inverse = hex(abs(int(hexNumber, 16) - 255))[2:]
# if the number is a single digit add a preceding zero
if len(inverse) == 1:
inverse = '0'+inverse
return inverse
def colorInvert(hexCode):
#define an empty string for our new colour code
inverse = ""
# if the code is RGB
if len(hexCode) == 6:
R = hexCode[:2]
G = hexCode[2:4]
B = hexCode[4:]
# if the code is ARGB
elif len(hexCode) == 8:
A = hexCode[:2]
R = hexCode[2:4]
G = hexCode[4:6]
B = hexCode[6:]
# don't invert the alpha channel
inverse = inverse + A
else:
# do nothing if it is neither length
return hexCode
inverse = inverse + invertHex(R)
inverse = inverse + invertHex(G)
inverse = inverse + invertHex(B)
return inverse
def sixfo( img ):
### convert image to base64
icn = open(img, 'rb')
icondata = icn.read()
nsvg = ''
for line in icondata.split('\n'):
line = str( line )
if 'fill' in line:
fill = str( line.split('#')[-1] )
fill = str( fill.split('"')[0] )
newf = colorInvert( fill )
line = str( sub( fill, newf, line ) )
nsvg = str( '%s%s' % ( nsvg, line ) )
else:
nsvg = str( '%s%s' % ( nsvg, line ) )
# print(nsvg)
# print(icondata)
icondata = b64encode(nsvg)
return icondata
def pcss( fdir, ocss, mat, ires ):
### main, convert every image to b64 - stream output
scss = ''
if not fdir.startswith('/'):
if exist( fdir ):
cw = str( getcwd() )
fdir = str( join( sep, cw, fdir ) )
for itm in listdir( fdir ):
itm = str( itm )
if itm.endswith( mat ):
fp = str( join( sep, fdir, itm ) )
md = str( itm.split( mat )[0] )
md = str( itm.split('.')[0] )
b6 = str( sixfo( fp ) )
cs = str( crender( md, b6, ires ) )
### Direct Stream From arg
if ocss == '-v':
scss = str( '%s\n%s' % ( scss, cs ) )
else:
a = open( ocss, 'a' )
a.write( cs )
a.write('')
a.close()
if ocss == '-v':
return scss
return
def carg( fdir, ocss ):
### check paths
fdir = str( fdir )
if exist( fdir ):
if not listdir( fdir ):
err = str( 'cannot stat %s' % fdir )
fatal( err )
if ocss == '-v' :
pass
else:
try:
a = open( ocss, 'w' )
a.write('')
a.close()
except:
err = str( 'can not open %s for writing' % ocss )
fatal( err )
def vert():
mat = 'svg'
ires = '32'
ocss = '-v'
### as argument
la = len( argv )
if la < 2:
Usage()
### input directory for images
fdir = str( argv[1] )
if la > 2:
### optional out css file
ocss = str( argv[2] )
carg( fdir, ocss )
cssl = pcss( fdir, ocss, mat, ires )
if ocss == '-v':
for line in cssl.split('\n'):
print( line )
else:
print( 'Contents of %s Converted to css file %s' % ( fdir, ocss ) )
def cvert( fdir ):
### as method
mat = 'svg'
ires = '32'
ocss = '-v'
carg( fdir, ocss )
cssl = pcss( fdir, ocss, mat, ires )
return cssl
if __name__ == "__main__":
if len( argv ) > 0:
vert()
<file_sep>from re import sub
def heads( raw, opt, proc=None ):
def all():
h = []
for e in str( raw ).split('\n'):
e = str( e )
f = ''
if ": " in e:
f = str( e.split(': ')[0] )
e = str( e.split(': ')[-1] )
if proc:
if proc in e:
f = str( '%s ' % proc )
e = str( sub( f, '', e ) )
e = str( e.split(' ')[0] )
f = str( 'METHOD:%s' % proc )
if '\r' in e:
e = str( sub( '\\r', '', e ) )
g = [ f, e ]
h.append( g )
return h
def item():
for e in str( raw ).split('\n'):
e = str( e )
if '-' in e:
if '_' in e:
itm = str( e.split('=')[0] )
id = str( itm.split('_')[-1] )
if len( id ) == 25:
if id[0].isdigit():
return itm
t = eval( opt )
return t()
def headerz( raw, opt, proc=None ):
raw = str( raw )
opt = str( opt )
hary = heads( raw, opt, proc )
return hary
<file_sep>from os import path, getcwd
from re import sub
join = path.join
sep = path.sep
exist = path.exists
def bxcss( clz ):
src = '''\
section.prv button { color: #fff; height: 20px: width: 10px; margin-right: 1; margin-top: 5; background-color: #000000; text-shadow: -1px 1px #417cb8; border: none; }
.btn { width: 25px; height: 25px; -webkit-transform: perspective(1px) translateZ(0); transform: perspective(1px) translateZ(0); -webkit-transition-duration: 0.1s; transition-duration: 0.1s; -webkit-transition-property: transform; transition-property: transform; }
.btn:hover { -webkit-transform: scale(1.4); transform: scale(1.4); -webkit-transition-duration: 0.1s; transition-duration: 0.1s; -webkit-transition-property: transform; transition-property: transform; js:click(); }
section.hvb button { color: #fff; height: 20px: width: 10px; margin-right: 1; margin-top: 5; background-color: #000000; text-shadow: -1px 1px #417cb8; border: none; }
'''
for c in clz:
c = str( c )
src = str( '''%s\
section.c%s button { color: #fff; height: 20px: width: 10px; margin-right: 1; margin-top: 5; background-color: #%s; text-shadow: -1px 1px #417cb8; border: none; }
''' % ( src, c, c ) )
return src
def bxhtml( clz ):
x = 1
rt = []
src = ''
row = 13
cl = len( clz )
for c in clz:
c = str( c )
#cl = str( '#%s' % c )
src = str( '''%s\
<section class="c%s"><button class="btn" onClick="reply_click('%s')" onmouseover="hv_over('%s')"> </button></section>
''' % ( src, c, c, c ) )
if ( x % row == 0 ):
rt.append( src )
src = ''
x = x + 1
else:
x = x + 1
src = str( '''%s<section class="c000000"><button class="btn" onClick="reply_click(c000000)"> </button></section>''' % src )
rt.append( src )
x = 0
src = '<div id="column"><div class = "blocks"><table>'
for r in rt:
r = str( r )
src = str( '%s<td>%s</td>' % ( src, r ) )
x = x + 1
src = str( '''%s\n</table></div>''' % src )
return src
def bxjsp():
src = '''\
function reply_click( hv_clr )
{
var ful = '#' + hv_clr
document.getElementById( 'tinput' ).value = ful;
document.getElementById( 'prv' ).style.backgroundColor = ful;
}
function hv_over( hv_clr )
{
var ful = '#' + hv_clr
document.getElementById( 'hvb' ).style.backgroundColor = ful;
}
'''
return src
def pclrs( fp ):
### parse file for hex colors, return as array
clz = []
if exist( fp ):
a = open( fp, 'r' )
for ln in a.readlines():
ln = str( ln )
ln = str( sub( '\n', '', ln ) )
la = len( ln )
if la == 7:
if ln.startswith('#'):
ln = str( sub( '#', '', ln ) )
clz.append( ln )
else:
return
return clz
def vym():
cwd = str( getcwd() )
dp = str( join( sep, cwd, 'figc' ) )
fp = str( join( sep, dp, 'safe.txt' ) )
clz = pclrs( fp )
if clz:
cs = str( bxcss( clz ) )
h5 = str( bxhtml( clz ) )
jsp = str( bxjsp() )
src = str( '\n\n<style>%s</style><script>%s</script>\n\n%s' % ( cs, jsp, h5 ) )
return src
else:
return str( '%s color config not found' % fp )
<file_sep>from random import choice, randrange
from string import ascii_lowercase, ascii_uppercase
def ranstr( sln ):
### return random string with a leading character
upr = choice( ascii_uppercase )
lwr = choice( ascii_lowercase )
num = randrange( 0, 9)
opt = [ 'upr', 'lwr' ]
opts = [ 'upr', 'lwr', 'num' ]
ret = choice( opt )
ret = str( eval( ret ) )
for i in xrange( 1, sln ):
t = choice( opts )
t = eval( t )
ret = str( '%s%s' % ( ret, t ) )
return ret
<file_sep>
def sidebar():
sbr = '''\
.modalPage {
position: absolute;
font-family: Arial, Helvetica, sans-serif;
top: 80;
right: 0;
bottom: 0;
left: 40;
margin-left:20;
padding-left: 50;
width: 505px; height: 460px;
background: rgba(0,0,0,0.8);
z-index: 99999;
opacity:0;
border-radius: 25px;
-webkit-transition: opacity 1s ease-in;
-moz-transition: opacity 1s ease-in;
transition: opacity 1s ease-in;
pointer-events: none;
}
.modalPage:target {
opacity:1;
position: fixed;
top: 80; left: 40; right: 0; bottom: 0;
pointer-events: auto;
width: 505px; height: 460px;
border-radius: 25px;
}
.modalPage > div {
margin-top: 30;
top 80:
left:5; right: 5;
margin-top: 10;
margin-right: 5;
margin-left: 2;
padding-left: 2;
margin-bottom: 5;
width: 530px;
height: 440px;
position: absolute;
border-radius: 25px;
background: -moz-linear-gradient(#fff, #999);
background: -webkit-linear-gradient(#fff, #999);
background: -o-linear-gradient(#fff, #999);
}
'''
dbr = '''\
.modalDialog {
position: absolute;
font-family: Arial, Helvetica, sans-serif;
top: 80;
right: 0;
bottom: 0;
left: 40;
margin-left:20;
padding-left:20;
width: 265px; height: 120px;
background: rgba(0,0,0,0.8);
z-index: 99999;
opacity:0;
border-radius: 25px;
-webkit-transition: opacity 1s ease-in;
-moz-transition: opacity 1s ease-in;
transition: opacity 1s ease-in;
pointer-events: none;
}
.modalDialog:target {
opacity:1;
position: fixed;
top: 80; left: 40; right: 0; bottom: 0;
pointer-events: auto;
width: 265px; height: 120px;
border-radius: 25px;
}
.modalDialog > div {
margin-top: 30;
top 80:
left:5; right: 5;
margin-top: 10;
margin-right: 5;
margin-left: 2;
padding-left: 2;
margin-bottom: 5;
width: 265px;
height: 100px;
position: absolute;
border-radius: 25px;
background: -moz-linear-gradient(#fff, #999);
background: -webkit-linear-gradient(#fff, #999);
background: -o-linear-gradient(#fff, #999);
}
'''
rbr = '''\
.modalPopup {
position: absolute;
font-family: Arial, Helvetica, sans-serif;
top: 80;
right: 0;
bottom: 0;
left: 40;
margin-left:5;
padding-left:5;
margin-top:4; padding-top:4;
margin-bottom:4; padding-bottom:4;
width: 390px; height: 50px;
background: rgba(0,0,0,0.8);
z-index: 99999;
opacity:0;
border-radius: 25px;
-webkit-transition: opacity 1s ease-in;
-moz-transition: opacity 1s ease-in;
transition: opacity 1s ease-in;
pointer-events: none;
}
.modalPopup:target {
opacity:1;
position: fixed;
top: 80; left: 40; right: 0; bottom: 0;
pointer-events: auto;
width: 410px; height: 95px;
border-radius: 25px;
padding-left:5;
margin-left:5;
}
.modalPopup > div {
top 80:
left:5; right: 5;
margin-right: 5;
margin-left: 2;
padding-left: 2;
width: 390px;
margin-top;5;
margin-bottom:5;
height: 50x;
position: absolute;
border-radius: 25px;
background: -moz-linear-gradient(#fff, #999);
background: -webkit-linear-gradient(#fff, #999);
background: -o-linear-gradient(#fff, #999);
}
'''
src = str( '%s\n\n%s\n\n%s' % ( sbr, dbr , rbr ) )
return src
<file_sep># -*- coding: utf-8 -*-
from os import path
from re import sub
join = path.join
sep = path.sep
exist = path.exists
def psec( cfg, arg ):
### return option from cfg
for c in cfg:
c = str( c )
if arg in c:
c = str( c.split(':')[-1] ).strip()
return c
return
def pcfg( cfg, sec ):
### parse lines of cfg for section
g = []
x = 0
for ln in cfg:
ln = str( ln )
if x == 1:
if 'END' in ln:
break
else:
ln = str( sub( '\n', '', ln ) ).strip()
ln = str( sub( ' ', ' ', ln ) )
ll = len( ln )
if ll > 1:
g.append( ln )
if sec in ln:
x = 1
return g
def dbfg( lns, zf ):
sec = pcfg( lns, 'GENERAL' )
kuid = str( psec( sec, 'localuid' ) )
kn = str( psec( sec, 'kartname' ) )
print(sec)
print
print(kuid)
print
print(kn)
kdb = str( '%s.db' % kuid )
zdb = str( join( sep, zf, kdb ) )
if exist( zdb ):
pass
else:
print( '%s does not exist!' % zdb )
<file_sep># -*- coding: utf-8 -*-
from re import sub
def psec( cfg, arg ):
### return option from cfg
for c in cfg:
c = str( c )
if arg in c:
c = str( c.split(':')[-1] ).strip()
return c
return
def pcfg( cfg, sec ):
### parse lines of cfg for section
g = []
x = 0
for ln in cfg:
ln = str( ln )
if x == 1:
if 'END' in ln:
break
else:
ln = str( sub( '\n', '', ln ) ).strip()
ln = str( sub( ' ', ' ', ln ) )
ll = len( ln )
if ll > 1:
g.append( ln )
if sec in ln:
x = 1
return g
def cssc( cfg ):
### parse main css by section
def headc( hic, tlc ):
print(hic)
src = '''\
div#header-wrapper {
background-color: %s;
font-color:yellow;
width:100%%; top:0;
left:0; right:0;
height:66px;
}
body>div#header-wrapper {
position:fixed;
margin:0 auto;
top:0; left:0;
right:0;
}
div#header {
height:66px;
left:0; right:0;
font-color: yellow;
margin:0 auto;
background-color: %s;
color: %s;
font-style: oblique;
font-size: 36px;
text-align: center;
left: 15; right: 15;
}
''' % ( hic, hic, tlc )
return src
def contc( acc ):
src = str( '''\
div#content-wrapper {
margin-left:0; top:66;
voice-family: "\\"}\\"";
voice-family:inherit;
padding-bottom:0px;
background-color: %s;
position:absolute;
}
body>div#content-wrapper {
margin-left:0;
background-color: %s;
margin:0 auto; left: 0;
top:66; right: 0;
height:25; width:670px;
position:fixed;
}
div#content {
width:720px;
margin:0 auto;
background-color: %s;
}
''' % ( acc, acc, acc ) )
return src
def footc( acc ):
src = str( '''\
div#footerwrap {
width:100%%;
position:absolute;
bottom:25; left:0;
right:0; height:50px;
}
body>div#footerwrap {
position:absolute;
left:0; right:0;
}
div#footer {
height:50px; bottom:0;
left: 0; right: 0;
margin:0 auto;
font-style: oblique;
color: yellow;
font-size: 22px;
text-align: center;
background-color: %s;
position:fixed;
}
''' % acc )
return src
def malc( prc ):
src = str( '''\
div#maltent-wrapper {
background-color: %s;
font-color: yellow;
width:100%%;
top:66; left:75;
right:0; potision: absolute;
height:100%%;
}
body>div#maltent-wrapper {
margin-left:0; background-color: %s;
margin:0 auto;
left: auto; right:0;
position:fixed right: 15;
z-index: -3; top:0;
bottom:auto; width:640px;
}
div#maltent {
width:719px;
font-color: yellow;
margin:0 auto;
background-color: %s;
color: #ff0a00;
font-style: oblique;
font-size: 36px;
text-align: center;
left: 15; right: 15;
top: 0; bottom: auto;
}
''' % ( prc, prc, prc ) )
return src
def glblc( txc, lkc ):
### instance or wrapper based css
src = str('''\
\\a:link { color: %s;
text-decoration: none; }
label { color: %s; }
h1 { text-align: center; }
.column-left{ float: left; width: 33%%; margin-left:5; margin-top:5; }
.column-right{ float: right; width: 33%%; margin-top:5; }
.column-center{ display: inline-block; width: 33%%; }
.c-left{ float: left; width:43%%; margin-left:5; line-height: 2.5; padding-top: 15; top: 15;}
.c-center{ left:50; top:0; padding-left: 25; display: inline-block; width: 33%%; line-height:0.4;}
.f-bottom{ float: bottom; bottom:5; }
.c-l{ float: left; width: 33%%; margin-left:5; margin-top:5; font-size: 135%%;}
.c-r{ float: right; width: 43%%; margin-top:5; }
.cr{ float: right; width: 0%%; top:0; display: inline-block;}
.i-l{ inline-block; top: 0; left: 0; right: 0;}
a:link {
text-decoration: none;
}
a:visited {
text-decoration: none;
}
a:active {
text-decoration: none;
}
body {background-color: #69b543;}
div#wrapper {
width: 100%%;
right: 0;
left: 75;
}
body>div#wrapper-wrapper {
width: 730px; top: 90;
left: 0; right: 0;
position: fixed;
border: 1px solid black;
}
/* from pages */
.close {
background: #606061; color: #FFFFFF;
line-height: 25px; position: absolute;
right: -12px; text-align: center;
top: -10px; width: 24px;
display: inline-block;
text-decoration: none; font-weight: bold;
-webkit-border-radius: 12px; -moz-border-radius: 12px;
border-radius: 12px; -moz-box-shadow: 1px 1px 3px #000;
-webkit-box-shadow: 1px 1px 3px #000; box-shadow: 1px 1px 3px #000;
}
.close:hover { background: #00d9ff; }
.closel {
background: #606061; color: #FFFFFF;
line-height: 25px; position: absolute;
left: -12px; text-align: center;
top: -10px; width: 24px;
display; inline-block;
text-decoration: none; font-weight: bold;
-webkit-border-radius: 12px; -moz-border-radius: 12px;
border-radius: 12px; -moz-box-shadow: 1px 1px 3px #000;
-webkit-box-shadow: 1px 1px 3px #000; box-shadow: 1px 1px 3px #000;
}
.closel:hover { background: #00d9ff; }
.closem {
background: #606061; color: #FFFFFF;
line-height: 25px; position: relative;
left: 0px; text-align: center;
right: auto; margin-left: 60px;
margin-right: 60px;
top: -12px;
display; inline-block;
text-decoration: none; font-weight: bold;
-webkit-border-radius: 12px; -moz-border-radius: 12px;
border-radius: 12px; -moz-box-shadow: 1px 1px 3px #000;
-webkit-box-shadow: 1px 1px 3px #000; box-shadow: 1px 1px 3px #000;
}
/* buttons */
.styled-button-5 {
background-color:#ed8223;
color:#fff;
font-family:'Helvetica Neue',sans-serif;
font-size:18px;
line-height:30px;
margin-top: 12px;
margin-left 12px;
-webkit-border-radius:20px;
-moz-border-radius:20px;
border:2px solid #ed8223;
text-shadow:#C17C3A 0 -1px 0;
width:120px;
height:32px;
disaplay: inline;
}
.styled-button-5:hover {
color:purple;
text-decoration: none;
border:2px solid purple;
}
/* highlight form */
.form-style-6 input[type="submit"], .form-style-6 input[type="button"] {
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
width: 100%%;
margin-top:3; margin-bottom: 3;
padding: 5%%;
background: #43d1af;
border-bottom: 2px solid #30c29e;
border-top-style: none;
border-right-style: none;
border-left-style: none;
color: #fff;
font-size: 14px;
}
/* orange circle button */
h8 {
margin-left: 0; margin-right: 0;
align: center; text-align: center;
font-weight: bold; length: 35px;
box-shadow:inset 2px 2px 2px 2px black;
display: inline;
position: relative;
overflow: hidden;
}
h5 {
font-family: times;
font-size: 50%%;
display: inline;
padding-left: 25px;
padding-right: 25px;
padding-top:0;
margin-bottom:10px;
}
h2 {
padding-bottom:0;
display: inline-block;
}
''' % ( txc, lkc ) )
return src
### define colors from cfg
clr = pcfg( cfg, 'COLOR' )
icc = str( psec( clr, 'icon-color' ) )
prc = str( psec( clr, 'primary-color' ) )
acc = str( psec( clr, 'accent-color' ) )
hic = str( psec( clr, 'highlight-color' ) ).encode('utf-8')
lkc = str( psec( clr, 'link-color' ) )
txc = str( psec( clr, 'text-color' ) )
tlc = str( psec( clr, 'title-color' ) )
### pass colors through css template
head = str( headc( hic, tlc ) )
cont = str( contc( acc ) )
foot = str( footc( acc ) )
mal = str( malc( prc ) )
glbl = str( glblc( txc, lkc ) )
src = str( '%s\n\n%s\n\n%s\n\n%s\n\n%s\n' % ( head, cont, foot, mal, glbl ) )
return src
<file_sep>#!/usr/bin/env python
### convert directory of images for b64css div template
from base64 import b64encode
from sys import argv, exit
from os import path, listdir, remove, getcwd
from re import sub
exist = path.exists
join = path.join
sep = path.sep
def psec( cfg, arg ):
### return option from cfg
for c in cfg:
c = str( c )
if arg in c:
c = str( c.split(':')[-1] ).strip()
return c
return
def pcfg( cfg, sec ):
### parse lines of cfg for section
g = []
x = 0
for ln in cfg:
ln = str( ln )
if x == 1:
if 'END' in ln:
break
else:
ln = str( sub( '\n', '', ln ) ).strip()
ln = str( sub( ' ', ' ', ln ) )
ll = len( ln )
if ll > 1:
g.append( ln )
if sec in ln:
x = 1
return g
def lrender( md, b6 ):
### css
src= ''' div.%s {
background:url(data:image/svg+xml;base64,%s);
width: 280px; height: 32px;
background-size: 280px 32px;
background-repeat: no-repeat;
top: 15; display: inline-block;
padding-top: 15px; margin-top: 15px;
}''' % ( md, b6 )
return src
def trender( md, b6, ires ):
### css
src= ''' div.%s {
background:url(data:image/svg+xml;base64,%s);
width: %spx; height: %spx;
background-size: %spx %spx;
background-repeat: no-repeat;
top: 0; display: inline-block;
}''' % ( md, b6, ires, ires, ires, ires )
return src
def crender( md, b6, ires ):
### css
src= ''' div.%s {
background:url(data:image/svg+xml;base64,%s);
width: %spx; height: %spx;
background-size: %spx %spx;
background-repeat: no-repeat;
}''' % ( md, b6, ires, ires, ires, ires )
return src
def invertHex(hexNumber):
#invert a hex number
inverse = hex(abs(int(hexNumber, 16) - 255))[2:]
# if the number is a single digit add a preceding zero
if len(inverse) == 1:
inverse = '0'+inverse
return inverse
def colorInvert(hexCode):
#define an empty string for our new colour code
inverse = ""
# if the code is RGB
if len(hexCode) == 6:
R = hexCode[:2]
G = hexCode[2:4]
B = hexCode[4:]
# if the code is ARGB
elif len(hexCode) == 8:
A = hexCode[:2]
R = hexCode[2:4]
G = hexCode[4:6]
B = hexCode[6:]
# don't invert the alpha channel
inverse = inverse + A
else:
# do nothing if it is neither length
return hexCode
inverse = inverse + invertHex(R)
inverse = inverse + invertHex(G)
inverse = inverse + invertHex(B)
return inverse
def sixfo( img, icc ):
### convert image to base64
icc = str( icc.split('#')[-1] )
icn = open(img, 'rb')
icondata = icn.read()
nsvg = ''
for line in icondata.split('\n'):
line = str( line )
if 'fill' in line:
fill = str( line.split('#')[-1] )
fill = str( fill.split('"')[0] )
# icc = colorInvert( fill )
line = str( sub( fill, icc, line ) )
nsvg = str( '%s%s' % ( nsvg, line ) )
else:
nsvg = str( '%s%s' % ( nsvg, line ) )
# print(nsvg)
# print(icondata)
icondata = b64encode(nsvg)
return icondata
def pcss( fdir, mat, ires, cfg ):
### main, convert every image to b64 - stream output
scss = cs = ''
clr = pcfg( cfg, 'COLOR' )
icc = str( psec( clr, 'icon-color' ) )
if not fdir.startswith('/'):
if exist( fdir ):
cw = str( getcwd() )
fdir = str( join( sep, cw, fdir ) )
for itm in listdir( fdir ):
itm = str( itm )
if itm.endswith( mat ):
fp = str( join( sep, fdir, itm ) )
md = str( itm.split( mat )[0] )
md = str( itm.split('.')[0] )
b6 = str( sixfo( fp, icc ) )
if fdir.endswith( 'sidebar' ):
cs = str( crender( md, b6, ires ) )
if fdir.endswith( 'topbar' ):
cs = str( trender( md, b6, ires ) )
if fdir.endswith( 'ttl' ):
cs = str( lrender( md, b6 ) )
### Direct Stream From arg
scss = str( '%s\n\n%s' % ( scss, cs ) )
return scss
def carg( fdir, ocss ):
### check paths
fdir = str( fdir )
if exist( fdir ):
if not listdir( fdir ):
err = str( 'cannot stat %s' % fdir )
fatal( err )
def cvert( fdir, cfg ):
### as method
mat = 'svg'
ires = '32'
cssl = pcss( fdir, mat, ires, cfg )
return cssl
#if __name__ == "__main__":
# if len( argv ) > 0:
# vert()
<file_sep>This is my intro to SVGs. Template based CGI configuration. Reads through SVG files to dynamically change at the moment color, but size is the easy next step. I also wrote a color wheel for this which I am quite proud of. CSS HTML, JS, and CGI based logic.
<file_sep>from . import dbfg
<file_sep># -*- coding: utf-8 -*-
#TODO: OS-SPECIFIC < AGNOSTIC
#TODO: TMP/static conf file? tmpfs/ram
#TODO: Remote Backup/Restore cf.db
#TODO: Windows compatable paths
from os import environ, path, listdir, mkdir
from random import choice, randrange
from string import ascii_lowercase, ascii_uppercase
exist = path.exists
join = path.join
sep = path.sep
hdir = environ['HOME']
def ranstr( sln ):
### return random string with a leading character
### for kart uuid
upr = choice( ascii_uppercase )
lwr = choice( ascii_lowercase )
num = randrange( 0, 9)
opt = [ 'upr', 'lwr' ]
opts = [ 'upr', 'lwr', 'num' ]
ret = choice( opt )
ret = str( eval( ret ) )
for i in xrange( 1, sln ):
t = choice( opts )
t = eval( t )
ret = str( '%s%s' % ( ret, t ) )
return ret
def dcf( kuid ):
### default config
### TODO: list parsable uri's as resource
ret = str( ''' \
### COLOR START
icon-color: #69b543
primary-color: #664b4b
accent-color: #7d8182
highlight-color: #272c2e
link-color: yellow
text-color: purple
title-color: red
### COLOR END
### RES SMALL START
width: 640
height: 580
icon-size: 32
### RES SMALL END
### RESOURCE START
sidebar-icons:bins/icn/sidebar
sync:local
#sync:imgur
### RESOURCE END
### GENERAL START
kartname: MyKart
localuid: %s
### GENERAL END
''' % kuid )
return ret
def cdir():
### locate-create-return work dir
if exist( hdir ):
ret = str( join( sep, hdir, '.zkart' ) )
zdb = str( join( sep, ret, 'zdb' ) )
for z in [ ret, zdb ]:
z = str( z )
if exist( z ):
return z
else:
try:
mkdir( z )
except:
return
return ret
return
def cfp():
### locate-create-return conf file
if cdir():
dp = str( cdir() )
ret = str( join( sep, dp, 'zkart.cfg' ) )
if exist( ret ):
return ret
else:
try:
kuid = str( ranstr( 8 ) )
cfg = str( dcf( kuid ) )
fd = open( ret, 'w' )
fd.write( cfg )
fd.close()
return ret
except:
return
return
<file_sep>from . import jscr
<file_sep>from . import pcfg
psec = pcfg.psec
pcfg = pcfg.pcfg
def spages( lns, whl ):
def pnew():
src = ''' \
<div id="newp" class="modalPage"><div>
<a href="#close" title="Close" class="close">X</a>
<form action="#" enctype="multipart/form-data">
<div class="c-left">
<div>TITLE: <br></div>
<div>CATEGORY: <br></div>
<div>DESCRIPTION: <br><br><br><br></div>
<div>PRICE: <br></div>
<div>PIECESPR: <br></div>
<div>QUANTITY: <br></div>
<div class="f-bottom">
<input type="submit" class="styled-button-5" id="newitem" name="newitem" value="Commit" data="dtails" action="#"/>
</form></div>
</div>
<div class="c-center"><div class="form-style-6">
<div><input type="text" name="title"><br><br></div>
<div><input type="text" name="category"><br><br></div>
<div><textarea name="description" rows="10" cols="30" resize="none"> DESCRIPTION</textarea><br><br></div>
<div><input type="text" name="price"><br><br></div>
<div><input type="text" name="pcspr" value="1"><br><br></div>
<div><input type="text" name="totalq" value="unlimited"><br><br></div>
</div></div></div></div>
'''
return src
def pcal():
src = ''' \
<div id="calp" class="modalPage"><div>
<a href="#close" title="Close" class="close">X</a>
<h2>Calender Box</h2>
<p>This is a sample modal box that can be created using the powers of CSS3.</p>
<p>You could do a lot of things here like have a pop-up ad that shows when your></p>
</div></div>
'''
return src
def pitm():
src = ''' \
<div id="itmp" class="modalPage"><div>
<a href="#close" class="close">X</a>
<h2>Items Box</h2>
<p>This is a sample modal box that can be created using the powers of CSS3.</p>
<p>You could do a lot of things here like have a pop-up ad that shows when your></p>
</div></div>
'''
return src
def pmet():
src = ''' \
<div id="metp" class="modalPage"><div>
<a href="#close" class="close">X</a>
<h2>Metric Box</h2>
<p>This is a sample modal box that can be created using the powers of CSS3.</p>
<p>You could do a lot of things here like have a pop-up ad that shows when your></p>
</div></div>
'''
return src
def pord():
src = ''' \
<div id="ordp" class="modalPage"><div>
<a href="#close" title="Close" class="close">X</a>
<h2>Orders Box</h2>
<p>This is a sample modal box that can be created using the powers of CSS3.</p>
<p>You could do a lot of things here like have a pop-up ad that shows when your></p>
</div></div>
'''
return src
def ppic():
src = ''' \
<div id="picp" class="modalPage"><div>
<a href="#close" title="Close" class="close">X</a>
<h2>Picture Box</h2>
<p>This is a sample modal box that can be created using the powers of CSS3.</p>
<p>You could do a lot of things here like have a pop-up ad that shows when your></p>
</div></div>
'''
return src
def ppri():
src = ''' \
<div id="prip" class="modalPage"><div>
<a href="#close" title="Close" class="close">X</a>
<h2>Pricing Box</h2>
<p>This is a sample modal box that can be created using the powers of CSS3.</p>
<p>You could do a lot of things here like have a pop-up ad that shows when your></p>
</div></div>
'''
return src
def dbse():
src = ''' \
<div id="database" class="modalPage"><div>
<a href="#confp" class="close"><</a>
<a href="#close" class="closel">X</a>
<h2>Database Box</h2>
<p>This is a sample modal box that can be created using the powers of CSS3.</p>
<p>You could do a lot of things here like have a pop-up ad that shows when your></p>
</div></div>
'''
return src
def crdz():
src = ''' \
<div id="creds" class="modalPage"><div>
<a href="#confp" class="close"><</a>
<a href="#close" class="closel">X</a>
<h2>Creds Box</h2>
<p>This is a sample modal box that can be created using the powers of CSS3.</p>
<p>You could do a lot of things here like have a pop-up ad that shows when your></p>
</div></div>
'''
return src
def imgz():
src = ''' \
<div id="images" class="modalPage"><div>
<a href="#confp" class="close"><</a>
<a href="#close" class="closel">X</a>
<h2>images Box</h2>
<p>This is a sample modal box that can be created using the powers of CSS3.</p>
<p>You could do a lot of things here like have a pop-up ad that shows when your></p>
</div></div>
'''
return src
def userz():
src = ''' \
<div id="userz" class="modalPage"><div>
<a href="#confp" class="close"><</a>
<a href="#close" class="closel">X</a>
<h2>Users Box</h2>
</center><h5><hr =""\></h5><br>
<select id="uzern">
<option> Rahoul Utilizator</option>
</select> <a id="plusmin" href="#plusmin"><div class="plusmin" onclick="rmin('uzr')"></div></a>
</div></div>
'''
return src
def lgz():
src = ''' \
<div id="logs" class="modalPage"><div>
<a href="#confp" class="close"><</a>
<h2>Logs Box</h2>
<p>This is a sample modal box that can be created using the powers of CSS3.</p>
<p>You could do a lot of things here like have a pop-up ad that shows when your></p>
</div></div>
'''
return src
def hlp():
src = ''' \
<div id="help" class="modalPage"><div>
<a href="#confp" class="close"><</a>
<h2>Help Box</h2>
<p>This is a sample modal box that can be created using the powers of CSS3.</p>
<p>You could do a lot of things here like have a pop-up ad that shows when your></p>
</div></div>
'''
return src
def pcnf():
src = ''' \
<div id="confp" class="modalPage"><div>
<a href="#close" class="close">X</a><br><center>
<a id="paint" href="#pntp"> <div class="paint"> </div></a>
<a id="database" href="#database"> <div class="database"> </div></a>
<a id="creds" href="#creds"> <div class="lock"> </div></a>
<a id="images" href="#images"> <div class="images"> </div></a>
<a id="userz" href="#userz"> <div class="userz"> </div></a>
<a id="logs" href="#logs"> <div class="logs"> </div></a>
<a id="help" href="#help"> <div class="help"> </div></a>
</center><h5><hr =""\></h5><br>
<select id="kartn">
<option> MyKart</option>
</select> <a id="plusmin" href="#plusmin"><div class="plusmin" onclick="rmin('krt')"></div></a>
</div></div>
'''
return src
def ppnt( clr ):
icr = str( psec( clr, 'icon-color' ) )
lcr = str( psec( clr, 'link-color' ) )
pcr = str( psec( clr, 'primary-color' ) )
acr = str( psec( clr, 'accent-color' ) )
hcr = str( psec( clr, 'highlight-color' ) )
txt = str( psec( clr, 'text-color' ) )
ttl = str( psec( clr, 'title-color' ) )
syl = str('''\
<style>
section.icrx button { color: #fff; height: 20px: width: 10px; margin-right: 1; margin-top: 5; background-color: %s; text-shadow: -1px 1px #417cb8; border: none; }
section.lcrx button { color: #fff; height: 20px: width: 10px; margin-right: 1; margin-top: 5; background-color: %s; text-shadow: -1px 1px #417cb8; border: none; }
section.pcrx button { color: #fff; height: 20px: width: 10px; margin-right: 1; margin-top: 5; background-color: %s; text-shadow: -1px 1px #417cb8; border: none; }
section.acrx button { color: #fff; height: 20px: width: 10px; margin-right: 1; margin-top: 5; background-color: %s; text-shadow: -1px 1px #417cb8; border: none; }
section.hcrx button { color: #fff; height: 20px: width: 10px; margin-right: 1; margin-top: 5; background-color: %s; text-shadow: -1px 1px #417cb8; border: none; }
section.txtx button { color: #fff; height: 20px: width: 10px; margin-right: 1; margin-top: 5; background-color: %s; text-shadow: -1px 1px #417cb8; border: none; }
section.ttlx button { color: #fff; height: 20px: width: 10px; margin-right: 1; margin-top: 5; background-color: %s; text-shadow: -1px 1px #417cb8; border: none; }
</style>
''' % ( icr, lcr, pcr, acr, hcr, txt, ttl ) )
src = str( ''' \
<div id="pntp" class="modalPage"><div>
<a href="#confp" class="close"><</a>
<a href="#close" class="closel">X</a>
<h2>Color Box</h2>
<div class="c-l"><br>
<section class="icrx"><button id="icrb" class="btn" onclick="window.location.href='#whlp'; sselect('icri')"> </button> ICON </section>
<section class="pcrx"><button id="pcrb" class="btn" onclick="window.location.href='#whlp'; sselect('pcri')"> </button> PRIMARY </section>
<section class="acrx"><button id="acrb" class="btn" onclick="window.location.href='#whlp'; sselect('acri')"> </button> ACCENT </section>
<section class="hcrx"><button id="hcrb" class="btn" onclick="window.location.href='#whlp'; sselect('hcri')"> </button> HIGHLIGHT </section>
<section class="lcrx"><button id="lcrb" class="btn" onclick="window.location.href='#whlp'; sselect('lcri')"> </button> LINK </section>
<section class="txtx"><button id="txtb" class="btn" onclick="window.location.href='#whlp'; sselect('txti')"> </button> TEXT </section>
<section class="ttlx"><button id="ttlb" class="btn" onclick="window.location.href='#whlp'; sselect('ttli')"> </button> TITLE </section>
</div>
<div class="c-r"><form action="#">
<input name="iconc" type="text" id="icri" value="%s"></input>
<input name="primec" type="text" id="pcri" value="%s"></input>
<input name="acrc" type="text" id="acri" value="%s"></input>
<input name="highc" type="text" id="hcri" value="%s"></input>
<input name="lcrc" type="text" id="lcri" value="%s"></input>
<input name="txtc" type="text" id="txti" value="%s"></input>
<input name="ttlc" type="text" id="ttli" value="%s"></input>
<br><pre>paint stuff
<input type="submit" class="styled-button-5" id="saveclr" name="saveclr" value="SaveClr" /></form></div>
<input id="cslct" type="hidden"></input>
</div></div>
''' % ( icr, pcr, acr, hcr, lcr, txt, ttl ) )
src = str( '%s\n%s' % ( syl, src ) )
return src
def pwhl( whl ):
src = ''' \
<div id="whlp" class="modalPage"><div>
<a href="#pntp" class="close" > < </a>
<a href="#close" class="closel" > X </a>
%s
<section onclick="window.location.href='#pntp'; setcc();"><center>
<button>SET</button> <button class="btn" id="prv" onclick="window.location.href='#pntp'; setcc();"></button>
<input type="text" id="tinput" value="wtf"></input>
<button class="btn" id="hvb"></button>
 <button>ADD^</button></center>
</section>
</div></div>
''' % whl
return src
def pmn():
src = ''' \
<div id="plusmin" class="modalDialog"><div>
<a href="#userz" class="close"><</a>
<a href="#close" class="closel">X</a>
<div class="i-l">
<a href="#umit">
<input type="submit" class="styled-button-5" id="unew" name="NEW" value="NEW" onclick="fjava('uname');" >
<input type="submit" class="styled-button-5" id="urename" name="RENAME" value="RENAME" onclick="fjava('urename');" >
<input type="submit" class="styled-button-5" id="ucopy" name="COPY" value="COPY" onclick="fjava('ucopy');" >
<input type="submit" class="styled-button-5" id="udelete" name="DELETE" value="DELETE" onclick="fjava('udelete');" ></a>
</div></div></div>
</div></div></div>
'''
return src
def pmr():
src = ''' \
<div id="umit" class="modalPopup"><div>
<a href="#plusmin" class="close"><</a>
<a href="#close" class="closel">X</a>
<div class="closem">POOP</div>
<div class="i-l">
<form style="{display: inline-block}">
<input type="text" id="urin" name="urin" value="">
<input type="hidden" id="uref" name="uref" value="">
<input type="text" id="refu" name="refu" value="">
<input type="submit" class="styled-button-5" value="Commit" >
</form></input></intput></input>
</div></div></div>
'''
return src
### main
clr = pcfg( lns, 'COLOR' )
pn = str( pnew() )
pc = str( pcal() )
pi = str( pitm() )
pm = str( pmet() )
po = str( pord() )
pp = str( ppic() )
pr = str( ppri() )
pf = str( pcnf() )
pt = str( ppnt( clr ) )
pw = str( pwhl( whl ) )
db = str( dbse() )
cd = str( crdz() )
ig = str( imgz() )
uz = str( userz() )
lg = str( lgz() )
hp = str( hlp() )
pd = str( pmn() )
pz = str( pmr() )
src = str( '%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s' % ( pd, pn, pz, pc, pi, pm, po, pp, pr, db, cd, ig, uz, lg, hp, pf, pt, pw ) )
return src
<file_sep>import webapp2
#from metric.header import headerz
class MainPage(webapp2.RequestHandler):
def do( self, proc ):
raw = self.request
proc = str( proc )
HTML = '<html><body>mwahaha</body></hmtl>'
self.response.headers['Content-Type'] = 'text/html'
self.response.write(HTML)
def post( self, proc=None ):
self.do('POST')
def get( self, proc=None ):
self.do('GET')
app = webapp2.WSGIApplication([
( '/', MainPage,),
], debug=True,)
<file_sep>#!/usr/bin/python
from binascii import hexlify
import pyelliptic
# Symmetric encryption
iv = pyelliptic.cipher.gen_IV('aes-256-cfb')
ctx = pyelliptic.cipher("secretkey", iv, 1, ciphername='aes-256-cfb')
ciphertext = ctx.update('test1')
ciphertext += ctx.update('test2')
ciphertext += ctx.final()
ctx2 = pyelliptic.Cipher("secretkey", iv, 0, ciphername='aes-256-cfb')
print(ctx2.ciphering(ciphertext))
# Asymmetric encryption
alice = pyelliptic.ECC() # default curve: sect283r1
bob = pyelliptic.ECC(curve='sect571r1')
ciphertext = alice.encrypt("Hello Bob", bob.get_pubkey(),
ephemcurve='sect571r1')
print(bob.decrypt(ciphertext))
signature = bob.sign("Hello Alice")
# alice's job :
print(pyelliptic.ECC(pubkey=bob.get_pubkey(),
curve='sect571r1').verify(signature, "Hello Alice"))
# ERROR !!!
try:
key = alice.get_ecdh_key(bob.get_pubkey())
except:
print("For ECDH key agreement, the keys must be defined on the same curve !")
alice = pyelliptic.ECC(curve='sect571r1')
print(hexlify(alice.get_ecdh_key(bob.get_pubkey())))
print(hexlify(bob.get_ecdh_key(alice.get_pubkey())))
<file_sep># -*- coding: utf-8 -*-
### Handles dynamic variables of cgi runtime such as headers
from . import header
<file_sep># -*- coding: utf-8 -*-
#from pcfg import pcfg
def rcfg( fd, spec=None ):
### parse descriptor, return cfg options
def popt( line ):
### split line, return deliminator
opt = str( line.split(':')[0] ).strip()
arg = str( line.split(':')[-1] ).strip()
return opt, arg
def cres( sg ):
### match resolution options, from cfg segment
width = height = isize = None
for line in sg.split('\n'):
line = str( line )
line = popt( line )
opt = str( line[0] )
arg = str( line[1] )
if opt == 'width':
width = arg
if opt == 'height':
height = arg
if opt == 'icon-size':
isize = arg
return width, height, isize
def crec( sg ):
### parse resources, images, uris, etc
isbr = ''
for line in sg.split('\n'):
line = str( line )
line = popt( line )
opt = str( line[0] )
arg = str( line[1] )
if opt == 'sidebar-icons':
isbr = arg
return isbr
def clr( sg ):
### return color options from cfg
### icon - link - primary - accent - highlight {-color}
iclr = lclr = pclr = aclr = hclr = None
for line in sg.split('\n'):
line = str( line )
line = popt( line )
opt = str( line[0] )
arg = str( line[1] )
if opt == 'icon-color':
iclr = arg
if opt == 'link-color':
lclr = arg
if opt == 'primary-color':
pclr = arg
if opt == 'accent-color':
aclr = arg
if opt == 'highlight-color':
hclr = arg
return iclr, lclr, pclr, aclr, hclr
### main
lines = ''
if not spec:
spec ='SMALL'
if type(fd) == list:
for f in fd:
f = str( f )
lines = str( '%s\n%s' % ( lines, f ) )
else:
lines = fd
sg = str( lines.split( '### RES %s START' % spec )[-1] )
sg = str( sg.split( '### RES %s END' % spec )[0] )
### this preset cfg should already be loaded
if len( sg ) < 4:
return
sz = cres( sg )
sg = str( lines.split( '### COLOR START' )[-1] )
sg = str( sg.split( '### COLOR END' )[0] )
if len( sg ) < 4:
return
cl = clr( sg )
sg = str( lines.split( '### RESOURCE START' )[-1] )
sg = str( sg.split( '### RESOURCE END' )[0] )
rc = crec( sg )
return sz, cl, rc
#f = open('/media/.zkart/zkart.cfg','r')
#h = f.readlines()
#j = rcfg( h )
#from pcfg import pcfg, psec
#k = pcfg( h, 'COLOR' )
#ic = psec( k, 'icon-color' )
#print(ic)
<file_sep>from re import sub
def pcfg( cfg, sec ):
### parse lines of cfg for section
g = []
x = 0
for ln in cfg:
ln = str( ln )
if x == 1:
if 'END' in ln:
break
else:
ln = str( sub( '\n', '', ln ) ).strip()
ln = str( sub( ' ', ' ', ln ) )
ll = len( ln )
if ll > 1:
g.append( ln )
if sec in ln:
x = 1
return g
def tsec( sec ):
### trim section to add alterd
new = []
cfsn = [ 'COLOR', 'RES SMALL', 'RESOURCE' ]
for c in cfsn:
c = str( c )
if c == sec:
pass
else:
new.append( c )
return new
def upcfg( new, sec, cur ):
### overwrite cfg: new 2 section 2 current 2 file
def colr( new ):
ovr = icc = prc = acc = hlc = lkc = txc = tlc = ''
for arg in new.split( '&' ):
arg = str( arg )
if '%' in arg:
arg = str( sub( '%23', '#', arg ) )
opt = str( arg.split('=')[-1] )
if arg.startswith( 'iconc' ):
icc = opt
if arg.startswith( 'primec' ):
prc = opt
if arg.startswith( 'acrc' ):
acc = opt
if arg.startswith( 'highc' ):
hlc = opt
if arg.startswith( 'lcrc' ):
lkc = opt
if arg.startswith( 'txtc' ):
txc = opt
if arg.startswith( 'ttlc' ):
tlc = opt
ovr = str( '''### COLOR START\n\nicon-color: %s\nprimary-color: %s\naccent-color: %s\n
highlight-color: %s\nlink-color: %s\ntext-color: %s\ntitle-color: %s\n\n### COLOR END''' % ( icc, prc, acc, hlc, lkc, txc, tlc ) )
return ovr
### add unalterd section to new
ret = ''
x = 1
unlt = tsec( sec )
if sec == 'COLOR':
ovr = colr( new )
for c in unlt:
c = str( c )
cfs = pcfg( cur, c )
lc = len( cfs )
for f in cfs:
f = str( f )
if x == 1:
ret = str( '%s### %s START\n' % ( ret, c) )
ret = str( '%s\n%s' % ( ret, f ) )
if x == lc:
ret = str( '%s\n\n### %s END\n\n' % ( ret, c ) )
x = 1
else:
x = x + 1
ret = str( '%s\n\n%s' % ( ret, ovr ) )
return ret
<file_sep># -*- coding: utf-8 -*-
from os import getcwd, path
from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server
from metric.header import headerz
from figc.cenv import cfp
from figc.chrt import vym
from figc.upcfg import upcfg
from cssc.cssc import cssc
from cssc.b64dir import cvert
from cssc.sbar import sidebar
from magik.jscr import jscr
from httpc.spage import spages
from httpc import webc
from sql.dbfg import dbfg
webc = webc.webc
join = path.join
sep = path.sep
def read(environ):
length = int(environ.get('CONTENT_LENGTH', 0))
stream = environ['wsgi.input']
body = TemporaryFile( mode='w+b' )
while length > 0:
part = stream.read(min(length, 1024*200)) # 200KB buffer size
if not part: break
body.write( part )
length -= len( part )
body.seek(0)
environ['wsgi.input'] = body
return body
def zkart( environ, start_response ):
setup_testing_defaults(environ)
cf = str( cfp() )
zf = str( join( sep, cf, 'zdb' ) )
cwd = str( getcwd() )
bins = str( join( sep, cwd, 'bins' ) )
icn = str( join( sep, bins, 'icn' ) )
bmp = str( join( sep, bins, 'bmp' ) )
tlb = str( join( sep, bmp, 'ttl' ) )
sbr = str( join( sep, icn, 'sidebar' ) )
tbr = str( join( sep, icn, 'topbar' ) )
qstring = None
cfd = open( cf, 'r' )
lns = cfd.readlines()
cfd.close()
zfg = dbfg( lns, zf )
try:
req_page = str( environ['PATH_INFO'] )
method = str( environ['REQUEST_METHOD'] )
rhost = str( environ['REMOTE_HOST'] )
except:
return '<html><body>bad juju</body></hmtl>'
try:
qstring = str( environ['QUERY_STRING'] )
except:
pass
if qstring:
if qstring.endswith( 'SaveClr' ):
ncf = upcfg( qstring, 'COLOR', lns )
a = open( cf, 'w' )
a.write( ncf )
a.close()
cfd = open( cf, 'r' )
lns = cfd.readlines()
cfd.close()
##### parse image on post todo: change qstring, add method
# if 'title' in qstring:
# try:
# body = read(environ)
# print(body)
# path = FieldStorage(fp=body, environ=environ, keep_blank_values=True)
# title = str( path )
# print( title )
# title = str( title.split("dtails', '")[-1] )
# title = str( title.split(",")[0] )
# path = path["dtails"].value
# print(path)
# except:
# pass
### CSS
cbar = str( cvert( sbr, lns ) )
tbar = str( cvert( tbr, lns ) )
tlc = str( cvert( tlb, lns ) )
csc = str( cssc( lns ) )
csp = str( sidebar() )
cs = str( '%s\n%s\n%s\n%s\n%s\n' % ( cbar, tbar, tlc, csc, csp ) )
### JAVA
jsp = str( jscr() )
### HTML
whl = str( vym() )
body = str( webc( 'body', '/', environ ) )
pgs = str( spages( lns, whl ) )
### Return Response
html = str( '<html><head><style>%s</style><script>%s</script></head><body>%s\n%s</body></html>' % ( cs, jsp, body, pgs ) )
headers = [ ('Server', 'ZenKart-0.0.0'),('Content-type', 'text/html'),( 'charset','utf-8') ]
status = '200 OK'
start_response( status, headers )
return html
def phew():
try:
from sys import argv
port = int( argv[1] )
except:
port = 8080
httpd = make_server('127.0.0.1', port, zkart )
print( "Accepting on port %d" % port )
httpd.serve_forever()
con.close()
phew()
<file_sep># -*- coding: utf-8 -*-
def webc( mthd, pth, vars=None ):
### parse mathod, path, vars, return html
### bounds
if pth:
mthd = str( mthd )
pth = str( pth )
else:
return
def body( head ):
html = str( '''\
<div id="header-wrapper"><div id="header">
<center><div class="zkart"/></center>
</div></div>
<div id="content-wrapper" >
<a id="users" href="#entance"><div class="user"> </a></div>
</div>
<div id="maltent-wrapper" ><br><br><br>
<br><br><div><div class="column-left"><br>
<a id="new" href="#newp"><div class="new"></div></a><br>
<a id="calender" href="#calp"><div class="calender"></div></a><br>
<a id="items" href="#itmp"><div class="items"></div></a><br>
<a id="metrics" href="#metp"><div class="metrics"></div></a><br>
<a id="ordering" href="#ordp"><div class="ordering"></div></a><br>
<a id="pictures" href="#picp"><div class="pictures"></div></a><br>
<a id="pricing" href="#prip"><div class="pricing"></div></a><br>
</div></div>
<div class="column-center">
mooo<br>%s<br><br><br><br>
</div>
<div class="column-right"></div>
<!--
<div id="wrapper">
<form action="/" method="post" type="image" class="bi"><div class="bi"></div></form>
<br><br><br><br>-->
<div id="footerwrap"><div id="footer">
<div class="column-left"> <a href="#savep"><div class="save"></div></a></div>
<div class="column-center"><label>Some Tail</div>
<div class="column-right"> <a href="#confp"><div class="conf"></div></a></div>
</div>
</div>''' % head )
return html
def lost():
html = 'are you lost, would like some candy?'
return html
def landing():
html = str( body() )
return html
### main
# try:
# ret = eval( mthd )
# ret = str( ret() )
# return ret
# except:
# return 'The Wizard is unavailable at the moment.'
if mthd == 'body':
src = str( body( vars ) )
return src
<file_sep># -*- coding: utf-8 -*-
from . import cenv, ccfg, chrt
<file_sep>def jscr():
### select, set - color, conf
src = str( '''\
function sselect( fid )
{
document.getElementById('cslct').value = fid;
}
function setcc()
{
var clr = document.getElementById('tinput').value;
var fig = document.getElementById('cslct').value;
var pbx = fig.substring(0, fig.length - 1) + 'b';
console.log( 'pbx ' + pbx );
document.getElementById( fig ).value = clr;
document.getElementById( pbx ).style.backgroundColor = clr;
}
function svclr()
{
var icr = document.getElementById('icri').value;
var pcr = document.getElementById('pcri').value;
var acr = document.getElementById('acri').value;
var hcr = document.getElementById('hcri').value;
var lcr = document.getElementById('lcri').value;
var txt = document.getElementById('txti').value;
var ttl = document.getElementById('ttli').value;
var str = icr + ' ' + pcr + ' ' + acr + ' ' + hcr + ' ' + lcr + ' ' +txt + ' ' + ttl;
console.log( str );
}
function fjava( btn )
{
document.getElementById( 'uref' ).value = btn;
if ( btn == 'udelete' )
document.getElementById( 'urin' ).value = "Delete User?";
else
document.getElementById( 'urin' ).value = "";
}
function rmin( str )
{
document.getElementById( 'refu' ).value = str;
}
''' )
return src
#'iconc=%2369b543&primec=%23664b4b&accentc=%237d8182&highc=%23272c2e&linkc=yellow&txtc=purple&ttlc=yellow'
| 68d464fc0067f32b6d57a50670917bf530df3441 | [
"Markdown",
"Python"
] | 23 | Python | bman7903/zkart | 2665ed4d658135fd68d3036b7c4b9c4de59c384b | 9f1d5f93b8d36a110aaaffcff5d4d440df9b71e0 | |
refs/heads/master | <repo_name>camoy/fm<file_sep>/README.md
# fm
`fm` extracts or strips frontmatter data using `sed`.
## Usage
Given the following file in `example.md`.
---
title: Example
...
Whereof one cannot speak, thereof one must be silent.
It is possible to extract the frontmatter data.
cat example.md | fm
The default document marker style is `---` to `...` and the
default operation is extraction.
* `-s` strips the frontmatter leaving only the body.
* `-d` uses the `---` to `---` document marker style.
* `-p` uses the `+++` to `+++` document marker style.
## Installing
Install the script to a directory in `$PATH` like `/usr/local/bin`.
You may need to run as root.
wget https://raw.github.com/camoy/fm/master/fm -O /usr/local/bin/fm
chmod +x /usr/local/bin/fm
## Legal
This software is in the public domain. Anyone is free to use and
distribute it for any purpose.
`fm` is maintained by <NAME>.
<file_sep>/fm
#!/bin/bash
extract=1
style=0
_fm_extract() {
case $style in
0) sed -n "/^---$/,/^\.\.\.$/p" | sed "1d;$ d";;
1) sed -n "/^---$/,/^---$/p" | sed "1d;$ d";;
2) sed -n "/^+++$/,/^+++$/p" | sed "1d;$ d";;
esac
}
_fm_strip() {
case $style in
0) sed "/^---$/,/^\.\.\.$/d";;
1) sed "/^---$/,/^---$/d";;
2) sed "/^+++$/,/^+++$/d";;
esac
}
while getopts 'sdp' flag; do
case "${flag}" in
s) extract=0 ;;
d) style=1 ;;
p) style=2 ;;
esac
done
if [ $extract -eq 1 ]
then
_fm_extract
else
_fm_strip
fi
exit 0
| b3092c99811ba460b7bca8cc749618e0187642df | [
"Markdown",
"Shell"
] | 2 | Markdown | camoy/fm | 3d82277609896a3ea5cf0a6acd43e60d5b63352a | c4612b4c4f768c82dd436ec17b2a7f943b17ea8b | |
refs/heads/master | <repo_name>ArtemGovorov/wallaby-402<file_sep>/test/polyfill.js
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
// test this.prototype in case of native functions binding:
if (this.prototype)
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
nextSource = Object(nextSource);
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
});
}<file_sep>/app/constants/build_constants.js
var imageRoot = "/app/images/";
var fontRoot = "/app/fonts/";
var styleRoot = "/app/style/";
var mobileDir = "Mobile_Assets/";
var webDir = "Client_Assets/";
var webPath = imageRoot + webDir;
var mobilePath = imageRoot + mobileDir;
var demoPath = "http://url1.com/";
var devPath = "https://url2.net";
// these variables are injected into both Javascript and SCSS.
module.exports = {
templateDir: JSON.stringify("jsx-templates/foxwoods/"),
styleDir: JSON.stringify("style/foxwoods/"),
webPath: JSON.stringify(imageRoot + webDir),
mobilePath: JSON.stringify(imageRoot + mobileDir),
_facebookEnabled: false,
WebpackAPIRoot: JSON.stringify(devPath)
};<file_sep>/app/game-wrappers/gamesInterface.js
var keyMirror = require('keymirror');
import * as _ from 'lodash';
var events = keyMirror({
ERROR_DESCRIPTION: null,
TEST: null
});
var Actions = keyMirror({
NOT_IMPLEMENTED: null,
ERROR_DESCRIPTION: null
});
console.log(WebpackAPIRoot);
/**
* @name buildAction
* @param suppliedType string
* @param suppliedJson {json | string}
*/
export function buildAction(suppliedType, suppliedJson) {
return {type: suppliedType, json: suppliedJson, errors: []};
}
/**
* @name notifyViewEventDispatcher
* @param actionObject Action
*/
export function notifyViewEventDispatcher(actionObject) {
// stub
}
/**
* @name notifyViewEventDispatcher
* @param key
* @param value
* @param actionObject
*
**/
export function notifyServerEventDispatcher(key, value, actionObject) {
// stub
}
export function stubbedListener(event) {
if (event === undefined || event === null) {
console.log("Undefined or null event. Returning.");
return;
}
if (event.target == document.getElementById("iframeCanvas")) {
var data = event.data;
var separator = data.indexOf(":");
var key = data.substr(0, separator);
var value = data.substr(separator + 1);
notifyPropertyChanged(key, value);
}
}
/**
* @name sendEventToIFrame
* @param key
* @param value
* @method
*/
export function sendEventToIFrame(key, value = null){
let dataString = "";
if(value === null){
dataString = key;
}else{
dataString = key.toString().toUpperCase()+":"+value.toString().toUpperCase();
}
document.getElementById("iframeCanvas").contentWindow.postMessage(dataString, "*");
}
export function addFrameEventListener(eventRef, suppliedListener = stubbedListener) {
eventRef.addEventListener('message', suppliedListener, false);
}
export function removeFrameEventListener(eventRef, suppliedListener = stubbedListener) {
eventRef.removeEventListener("message", suppliedListener);
console.log("Event listener removed.");
}
export function notImplemented(suppliedKey, suppliedValue) {
notifyViewEventDispatcher(buildAction(
Actions.NOT_IMPLEMENTED,
JSON.stringify({[suppliedKey]: suppliedValue}),
"{}"
// JSON.stringify({key: suppliedValue})
//JSON.stringify({[suppliedKey]: suppliedValue})
));
}
export function notifyPropertyChanged(key, value) {
var eventReactions = {
[events.ERROR_DESCRIPTION]: function logError(message) {
console.warn("error: " + message);
}
};
if (_.includes(Object.keys(events), key)) {
eventReactions[key](value);
}
}
var publicObj = {
notifyPropertyChanged: notifyPropertyChanged,
addGameEventListener: addFrameEventListener,
removeGameEventListener: removeFrameEventListener,
sendEventToGame: sendEventToIFrame
};
export default publicObj;
<file_sep>/app/game-wrappers/gamesInterface-Test.js
import GamesInterface from './gamesInterface';
var domino = require('domino');
describe('gamesInterface', function () {
it('should receive events from supplied element', function (done) {
var window = domino.createWindow('<iframe id="iframeCanvas" src="about:blank" sandbox="allow-same-origin allow-scripts"></iframe>');
var document = window.document;
function spyOnListener (event) {
var testData = event.data;
assert.equal(testData, "TEST:SUCCESS");
done();
}
var elementRef = document.getElementById("iframeCanvas");
should.exist(elementRef);
GamesInterface.addGameEventListener(elementRef,spyOnListener);
var event = document.createEvent('Event');
event.initEvent('message', true, true);
event.origin = "https://expectedUrl.com";
event.data = "TEST:SUCCESS";
elementRef.dispatchEvent(event);
});
});
| 83e31f7fbdb617339a4a12993d220e8d417ac299 | [
"JavaScript"
] | 4 | JavaScript | ArtemGovorov/wallaby-402 | c5919a81ede05c3504c41efb852d24975d72666b | abf4d29842bafae3b0e07ba56e4fb64ab5a00de8 | |
refs/heads/master | <repo_name>sgart-it/SharePointQueryViewer<file_sep>/SgartSPQueryViewer/SgartSPQueryViewer/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Utilities;
using SPU = Microsoft.SharePoint.Client.Utilities;
using System.Diagnostics;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
namespace SgartSPQueryViewer
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
progressBar1.Visible = false;
progressBar1.Minimum = 0;
progressBar1.Maximum = 7;
progressBar1.Value = 0;
tpCaml.Select();
ProxyUrl = "";
txtCSharp.Clear();
txtCaml.Clear();
txtListData.Clear();
txtViewData.Clear();
txtCaml.Enabled = false;
txtCSharp.Enabled = false;
txtListData.Enabled = false;
txtViewData.Enabled = false;
//tabControl1.Enabled = false;
btnCopy.Enabled = false;
cmbFilterField.Enabled = false;
txtFields.Clear();
txtContentTypes.Clear();
btnConnect.Enabled = false;
cmbLists.Enabled = false;
cmbViews.Enabled = false;
cmbViews.ResetText();
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
this.Text = Application.ProductName + " 2013 - v. " + Application.ProductVersion;
btnRandomGuid_Click(null, null);
txtUrl.Focus();
}
public string ProxyUrl { get; set; }
public string ProxyUser { get; set; }
public string ProxyPwd { get; set; }
private SP.ClientContext GetClientContext(string webUrl)
{
SP.ClientContext ctx = new SP.ClientContext(webUrl);
if (txtUser.Text != "")
{
string domain = "";
string user = "";
if (txtUser.Text.Replace('/', '\\').Contains('\\'))
{
string[] tmp = txtUser.Text.Split('\\');
domain = tmp[0];
user = tmp[1];
}
else
{
user = txtUser.Text;
}
string password = txtPwd.Text;
if (chkLoginOnline.Checked)
{
System.Security.SecureString secpwd = new System.Security.SecureString();
for (int i = 0; i < password.Length; i++)
{
secpwd.AppendChar(password[i]);
}
//ClientAuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
//FormsAuthenticationLoginInfo creds = new FormsAuthenticationLoginInfo(User, Password);
SharePointOnlineCredentials creds = new SharePointOnlineCredentials(user, secpwd);
ctx.Credentials = creds;
}
else
{
ctx.Credentials = new System.Net.NetworkCredential(user, txtPwd.Text, domain);
}
}
if (string.IsNullOrEmpty(ProxyUrl) == false)
{
ctx.ExecutingWebRequest += (sen, args) =>
{
System.Net.WebProxy myProxy = new System.Net.WebProxy(ProxyUrl);
string domain = "";
string user = "";
if (ProxyUser.Replace('/', '\\').Contains('\\'))
{
string[] tmp = ProxyUser.Split('\\');
domain = tmp[0];
user = tmp[1];
}
// myProxy.Credentials = new System.Net.NetworkCredential(ProxyUser, ProxyPwd, domain);
myProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
myProxy.UseDefaultCredentials = true;
args.WebRequestExecutor.WebRequest.Proxy = myProxy;
};
}
return ctx;
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (btnConnect.Enabled == false)
return;
progressBar1.Value = 1;
progressBar1.Visible = true;
string webUrl = txtUrl.Text;
cmbLists.Items.Clear();
cmbLists.Enabled = false;
cmbViews.Items.Clear();
cmbViews.ResetText();
cmbViews.Enabled = false;
txtCaml.Clear();
txtCSharp.Clear();
txtListData.Clear();
txtViewData.Clear();
txtCaml.Enabled = false;
txtCSharp.Enabled = false;
txtListData.Enabled = false;
txtViewData.Enabled = false;
//tabControl1.Enabled = false;
lblWait.Visible = true;
lblViewName.Text = "";
btnCopy.Enabled = false;
cmbFilterField.Enabled = false;
txtFields.Clear();
txtContentTypes.Clear();
txtListID.Clear();
txtListName.Clear();
txtListTitle.Clear();
txtCreated.Clear();
txtItemCount.Clear();
txtViewID.Clear();
txtViewName.Clear();
Application.DoEvents();
try
{
if (chkTryFindWebUrl.Checked)
webUrl = TryToFindCorrectUrl(webUrl);
progressBar1.Value = 1;
using (SP.ClientContext ctx = GetClientContext(webUrl))
{
SP.Web web = ctx.Web;
SP.ListCollection lists = web.Lists;
ctx.Load(lists);
ctx.ExecuteQuery();
progressBar1.Value++;
txtUrl.Text = webUrl;
foreach (var list in lists)
{
cmbLists.Items.Add(list.Title);
}
if (cmbLists.Items.Count > 0)
cmbLists.SelectedIndex = 0;
cmbLists.Enabled = true;
}
}
catch (System.Net.WebException ex)
{
bool resolved = false;
if (ex.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse response = (HttpWebResponse)ex.Response;
if (response.StatusCode == HttpStatusCode.ProxyAuthenticationRequired)
{
ProxyCredentialRequest frmProxy = new ProxyCredentialRequest();
frmProxy.ProxyUrl = response.ResponseUri.ToString();
if (string.IsNullOrEmpty(frmProxy.ProxyUser))
{
frmProxy.ProxyUser = txtUser.Text;
frmProxy.ProxyPwd = txtPwd.Text;
}
else
{
frmProxy.ProxyUser = ProxyUser;
frmProxy.ProxyPwd = ProxyPwd;
}
DialogResult r = frmProxy.ShowDialog();
if (r == System.Windows.Forms.DialogResult.OK)
{
ProxyUrl = frmProxy.ProxyUrl;
ProxyUser = frmProxy.ProxyUser;
ProxyPwd = frmProxy.ProxyPwd;
resolved = true;
btnConnect_Click(null, null);
}
}
}
if (resolved == false)
{
ProxyUrl = "";
MessageBox.Show(ex.Message, "SgartSPQueryViewer", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SgartSPQueryViewer", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
lblWait.Visible = false;
progressBar1.Visible = false;
}
}
private static bool customXertificateValidation(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
return true;
}
private static string TryToFindCorrectUrl(string webUrl)
{
Uri url = new Uri(webUrl);
webUrl = url.GetLeftPart(UriPartial.Path);
int p = webUrl.ToLower().IndexOf("/_layouts/");
if (p > 0)
{
webUrl = webUrl.Substring(0, p);
}
p = webUrl.ToLower().IndexOf("/_vti_bin/");
if (p > 0)
{
webUrl = webUrl.Substring(0, p);
}
p = webUrl.ToLower().LastIndexOf("/lists/");
if (p > 0)
{
webUrl = webUrl.Substring(0, p);
}
else
{
p = webUrl.ToLower().LastIndexOf("/liste/");
if (p > 0)
{
webUrl = webUrl.Substring(0, p);
}
}
if (webUrl.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase)
|| webUrl.EndsWith(".asmx", StringComparison.InvariantCultureIgnoreCase)
|| webUrl.EndsWith(".vsc", StringComparison.InvariantCultureIgnoreCase))
{
p = webUrl.LastIndexOf('/');
webUrl = webUrl.Substring(0, p);
}
return webUrl;
}
private void cmbLists_SelectedIndexChanged(object sender, EventArgs e)
{
progressBar1.Value = 1;
progressBar1.Visible = true;
cmbViews.Items.Clear();
cmbViews.ResetText();
cmbViews.Enabled = false;
//tabControl1.Enabled = false;
txtCaml.Clear();
txtCSharp.Clear();
txtListData.Clear();
txtListData.Enabled = false;
txtViewData.Clear();
txtViewID.Clear();
txtViewName.Clear();
lblWait.Visible = true;
lblViewName.Text = "";
btnCopy.Enabled = false;
dgResults.DataSource = null;
Application.DoEvents();
try
{
string webUrl = txtUrl.Text;
using (SP.ClientContext ctx = GetClientContext(webUrl))
{
SP.Web web = ctx.Web;
string listTitle = (string)cmbLists.SelectedItem;
SP.List list = web.Lists.GetByTitle(listTitle);
SP.ViewCollection views = list.Views;
ctx.Load(list);
ctx.Load(list, x => x.SchemaXml);
ctx.Load(list.Fields);
ctx.Load(views);
ctx.ExecuteQuery();
progressBar1.Value++;
txtListData.Text = FormatXml(list.SchemaXml);
LoadFields(list);
LoadContentTypes(list);
foreach (SP.View view in views)
{
string id = view.Id.ToString("B").ToUpper();
string title = view.Title;
if (title == "")
{
title = id;
}
MyListItem itm = new MyListItem(id, title);
cmbViews.Items.Add(itm);
}
if (cmbViews.Items.Count > 0)
{
cmbViews.SelectedIndex = 0;
}
cmbViews.Enabled = true;
txtListData.Enabled = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SgartSPQueryViewer", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
lblWait.Visible = false;
progressBar1.Visible = false;
}
}
private string allContentTypes = "";
private void LoadContentTypes(SP.List list)
{
cmbFilterContentType.Enabled = false;
cmbFilterContentType.Items.Clear();
if (cmbLists.SelectedIndex >= 0)
{
string webUrl = txtUrl.Text;
List<string> contentTypes = new List<string>();
contentTypes.Add("");
using (SP.ClientContext ctx = GetClientContext(webUrl))
{
Web oWebsite = ctx.Web;
SP.List list1 = oWebsite.Lists.GetById(list.Id);
ctx.Load(list1);
SP.ContentTypeCollection coll = list1.ContentTypes;
ctx.Load(coll, cts => cts.Include(
ct => ct.Name
, ct => ct.Description
, ct => ct.SchemaXml
));
ctx.ExecuteQuery();
progressBar1.Value++;
StringBuilder sb = new StringBuilder();
sb.Append("<ContentTypes>");
foreach (var item in coll)
{
contentTypes.Add(item.Name + " ( " + item.Description + " )");
sb.Append(item.SchemaXml);
}
sb.Append("</ContentTypes>");
allContentTypes = sb.ToString();
txtContentTypes.Text = FormatXml(allContentTypes);
contentTypes.Sort();
cmbFilterContentType.Items.AddRange(contentTypes.ToArray());
}
cmbFilterContentType.Enabled = true;
}
}
private void cmbFilterContentType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbFilterContentType.SelectedIndex > 0)
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(allContentTypes);
string internalName = (string)cmbFilterContentType.SelectedItem;
int p = internalName.IndexOf('(');
if (p > 0)
internalName = internalName.Substring(0, p).TrimEnd();
XmlNodeList nodes = xDoc.SelectNodes("ContentTypes/ContentType[@Name='" + internalName + "']");
StringBuilder sb = new StringBuilder();
sb.Append("<ContentTypes>");
foreach (XmlNode fld in nodes)
{
sb.Append(fld.OuterXml);
}
sb.Append("</ContentTypes>");
txtContentTypes.Text = FormatXml(sb.ToString());
}
else
{
txtContentTypes.Text = FormatXml(allContentTypes);
}
}
private string allFields = "";
private void LoadFields(SP.List list)
{
cmbFilterField.Enabled = false;
cmbFilterField.Items.Clear();
if (cmbLists.SelectedIndex >= 0)
{
string webUrl = txtUrl.Text;
List<string> fields = new List<string>();
fields.Add("");
using (SP.ClientContext ctx = GetClientContext(webUrl))
{
StringBuilder sb = new StringBuilder();
sb.Append("<Fields>");
progressBar1.Value++;
foreach (var item in list.Fields)
{
fields.Add(item.InternalName + " ( " + item.Title + " )");
sb.Append(item.SchemaXml);
}
sb.Append("</Fields>");
allFields = sb.ToString();
txtFields.Text = FormatXml(allFields);
fields.Sort();
cmbFilterField.Items.AddRange(fields.ToArray());
}
cmbFilterField.Enabled = true;
}
}
private void cmbFilterField_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbFilterField.SelectedIndex > 0)
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(allFields);
string internalName = (string)cmbFilterField.SelectedItem;
int p = internalName.IndexOf('(');
if (p > 0)
internalName = internalName.Substring(0, p).TrimEnd();
XmlNodeList nodes = xDoc.SelectNodes("Fields/Field[@Name='" + internalName + "']");
StringBuilder sb = new StringBuilder();
sb.Append("<Fields>");
foreach (XmlNode fld in nodes)
{
sb.Append(fld.OuterXml);
}
sb.Append("</Fields>");
txtFields.Text = FormatXml(sb.ToString());
}
else
{
txtFields.Text = FormatXml(allFields);
}
}
private void cmbViews_SelectedIndexChanged(object sender, EventArgs e)
{
progressBar1.Value = 1;
progressBar1.Visible = true;
LoadDetailView(false);
progressBar1.Visible = false;
}
private void btnResultsRefresh_Click(object sender, EventArgs e)
{
progressBar1.Value = 1;
progressBar1.Visible = true;
progressBar1.Value = 1;
LoadDetailView(true);
progressBar1.Visible = false;
}
private void LoadDetailView(bool loadData)
{
dgResults.DataSource = null;
Guid viewId = new Guid(((MyListItem)cmbViews.SelectedItem).Key);
lblWait.Visible = true;
txtCaml.Enabled = false;
txtCSharp.Enabled = false;
txtCaml.Clear();
txtCSharp.Clear();
//tabControl1.Enabled = false;
lblViewName.Text = "";
btnCopy.Enabled = false;
txtListID.Clear();
txtListName.Clear();
txtListTitle.Clear();
txtCreated.Clear();
txtItemCount.Clear();
txtViewID.Clear();
txtViewName.Clear();
btnResultsRefresh.Enabled = false;
Application.DoEvents();
try
{
string webUrl = txtUrl.Text;
using (SP.ClientContext ctx = GetClientContext(webUrl))
{
SP.Web web = ctx.Web;
string listTitle = (string)cmbLists.SelectedItem;
SP.List list = web.Lists.GetByTitle(listTitle);
SP.View view = list.Views.GetById(viewId);
//ctx.Load(view, w => w.ViewQuery, w => w.ViewFields, w => w.ViewData, w => w.Title, w => w.HtmlSchemaXml);
ctx.Load(list);
ctx.Load(list.RootFolder);
ctx.Load(view);
ctx.Load(view.ViewFields);
ctx.ExecuteQuery();
progressBar1.Value++;
if (view != null)
{
lblViewName.Text = view.ServerRelativeUrl;
StringBuilder sb = new StringBuilder();
sb.Append("<View>");
sb.Append("<Query>");
sb.Append(view.ViewQuery);
sb.Append("</Query>");
sb.AppendFormat("<RowLimit>{0}</RowLimit>", view.RowLimit);
sb.AppendFormat("<ViewFields>{0}</ViewFields>", view.ViewFields.SchemaXml);
sb.Append("</View>");
txtCaml.Text = FormatXml(sb.ToString());
if (loadData == false)
{
txtResultsNumber.Text = view.RowLimit.ToString();
}
txtViewData.Text = FormatXml(view.HtmlSchemaXml);
txtCSharp.Text = FormatCSharp(list, view);
LoadInfo(list, view);
if (loadData == true)
{
LoadItems(ctx, list, view);
}
//tabControl1.Enabled = true;
txtCaml.Enabled = true;
txtCSharp.Enabled = true;
txtViewData.Enabled = true;
btnCopy.Enabled = true;
btnResultsRefresh.Enabled = true;
cmbFilterField.Enabled = true;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SgartSPQueryViewer", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
lblWait.Visible = false;
}
}
private void LoadItems(SP.ClientContext ctx, SP.List list, SP.View view)
{
SP.CamlQuery query = new SP.CamlQuery();
query.ViewXml = "<View>" + view.ViewQuery + "<RowLimit>" + txtResultsNumber.Text + "</RowLimit></View>";
var items = list.GetItems(query);
ctx.Load(items, itms => itms.ListItemCollectionPosition
, itms => itms.Include(
itm => itm.FieldValuesAsText
, itm => itm.ContentType
)
);
ctx.ExecuteQuery();
progressBar1.Value++;
DataTable tbl = new DataTable();
DataColumnCollection columns = tbl.Columns;
DataRowCollection rows = tbl.Rows;
if (items != null && items.Count > 0)
{
columns.Add("N.", typeof(System.String));
columns.Add("ContentType", typeof(System.String));
foreach (var fld in items[0].FieldValuesAsText.FieldValues)
{
columns.Add(fld.Key, typeof(System.String));
}
int i = 1;
foreach (var item in items)
{
DataRow row = tbl.NewRow();
row["N."] = i;
row["ContentType"] = item.ContentType.Name;
foreach (var fld in item.FieldValuesAsText.FieldValues)
{
if (fld.Value != null)
{
row[fld.Key] = item.FieldValuesAsText[fld.Key];
}
}
rows.Add(row);
i++;
}
}
dgResults.AutoGenerateColumns = true;
dgResults.AutoSize = true;
dgResults.DataSource = tbl;
}
private void LoadInfo(SP.List list, SP.View view)
{
txtListID.Text = list.Id.ToString("B");
txtListName.Text = list.RootFolder.ServerRelativeUrl;
txtListTitle.Text = list.Title;
txtCreated.Text = list.Created.ToString() + " ( UTC: " + list.Created.ToString("s") + " )";
txtItemCount.Text = list.ItemCount.ToString();
txtViewID.Text = view.Id.ToString("B");
txtViewName.Text = view.ServerRelativeUrl;
chkPersonalView.Checked = view.PersonalView;
chkHiddenView.Checked = view.Hidden;
chkDefaultView.Checked = view.DefaultView;
progressBar1.Value++;
}
private void txtUrl_TextChanged(object sender, EventArgs e)
{
btnConnect.Enabled = txtUrl.Text.Trim().Length > 0;
}
private string FormatXml(string xml)
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xml);
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = Formatting.Indented;
xw.Indentation = 2;
xw.IndentChar = ' ';
xDoc.WriteTo(xw);
return sw.ToString();
}
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process myProcess = new Process();
try
{
// true is the default, but it is important not to set it to false
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = "http://www.sgart.it/?prg=SgartSPQueryViewer";
myProcess.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SgartSPQueryViewer", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private string FormatCSharp(SP.List list, SP.View view)
{
StringBuilder sb = new StringBuilder();
string listUrl = list.RootFolder.ServerRelativeUrl.Substring(list.ParentWebUrl.Length);
sb.AppendFormat(@"// Generated by SgartSPQueryViewer - http://www.sgart.it
//using Microsoft.SharePoint;
string url = ""{0}"";
string listUrl = ""{1}"";
using (SPSite site = new SPSite(url))
{{
using (SPWeb web = site.OpenWeb())
{{
SPList list = web.GetList(web.ServerRelativeUrl.TrimEnd('/') + listUrl);
SPFieldCollection fields = list.Fields;"
, txtUrl.Text, listUrl);
//field
string firstField = "LinkTitle";
if (view.ViewFields.Count == 0)
{
sb.Append(@"
SPField fldLinkTitle = fields.GetFieldByInternalName(""LinkTitle"");");
}
else
{
foreach (var fld in view.ViewFields)
{
string fldName = fld.Substring(0, 1).ToUpper() + fld.Substring(1);
if (firstField == "LinkTitle")
firstField = fldName;
sb.AppendFormat(@"
SPField fld{1} = fields.GetFieldByInternalName(""{0}"");"
, fld, fldName);
}
}
sb.AppendFormat(@"
SPQuery query = new SPQuery();
query.Query = @""{0}"";
query.RowLimit = 0;
query.ViewFields = @""{1}"";
query.ViewFieldsOnly = true;
query.ViewAttributes = ""Scope='{3}'""; //Default, FilesOnly, Recursive, RecursiveAll
SPListItemCollection items = list.GetItems(query);
Console.WriteLine(""Items found: "" + items.Count);
foreach (SPListItem item in items)
{{
//TODO: insert your code
//Console.WriteLine(string.Format(""ID: {{0}} - Title: {{1}}"", item.ID, item.Title));
Console.WriteLine(string.Format(""ID: {{0}} - Title: {{1}}""
, item.ID
, fld{2}.GetFieldValueAsText(item[fld{2}.Id])
}}
}}
}}
", view.ViewQuery.Replace("\"", "'"), view.ViewFields.SchemaXml.Replace("\"", "'"), firstField, view.Scope);
return sb.ToString();
}
private void btnCopy_Click(object sender, EventArgs e)
{
switch (tabControl1.SelectedTab.Name)
{
case "tpCaml":
txtCaml.SelectAll();
txtCaml.Copy();
break;
case "tpCSharp":
txtCSharp.SelectAll();
txtCSharp.Copy();
break;
case "tpListData":
txtListData.SelectAll();
txtListData.Copy();
break;
case "tpViewData":
txtViewData.SelectAll();
txtViewData.Copy();
break;
case "tpFields":
txtFields.SelectAll();
txtFields.Copy();
break;
case "tpContentTypes":
txtContentTypes.SelectAll();
txtContentTypes.Copy();
break;
default:
break;
}
}
private void btnRandomGuid_Click(object sender, EventArgs e)
{
txtRandomGuid.Clear();
Application.DoEvents();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 20; i++)
{
sb.AppendLine(Guid.NewGuid().ToString("B"));
}
txtRandomGuid.Text = sb.ToString();
}
private void txtResultsNumber_Leave(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
int v = 30;
if (Int32.TryParse(txt.Text, out v) == true)
{
if (v < -1)
{
txt.Text = "-1";
}
}
else
{
txt.Text = v.ToString();
}
}
}
}
<file_sep>/SgartSPQueryViewer/SgartSPQueryViewer/ProxyCredentialRequest.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SgartSPQueryViewer
{
public partial class ProxyCredentialRequest : Form
{
public ProxyCredentialRequest()
{
InitializeComponent();
}
public string ProxyUrl { get; set; }
public string ProxyUser { get; set; }
public string ProxyPwd { get; set; }
private void ProxyCredential_Load(object sender, EventArgs e)
{
txtUrl.Text = this.ProxyUrl;
txtUser.Text = this.ProxyUser;
txtPwd.Text = this.ProxyPwd;
btnOk.DialogResult = System.Windows.Forms.DialogResult.OK;
btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
}
private void btnOk_Click(object sender, EventArgs e)
{
this.ProxyUser = txtUser.Text;
this.ProxyPwd = txtPwd.Text;
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
| c48abc5224df2b654e701ce8549eee5aa1bdd1ef | [
"C#"
] | 2 | C# | sgart-it/SharePointQueryViewer | 6be230d57c7d8c178e3bf9d1a91185a03250762f | e8a1c1f8405bec5862ce2a310041cb7ef038ab2d | |
refs/heads/main | <file_sep><?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Propriete
*
* @ORM\Table(name="propriete", indexes={@ORM\Index(name="IDX_73A85B935BA3388B", columns={"id_type_habitat_id"})})
* @ORM\Entity
*/
class Propriete
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @Assert\Unique
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nom", type="string", length=40, nullable=false)
*/
private $nom;
/**
* @var string
*
* @ORM\Column(name="type", type="string", length=30, nullable=false)
*/
private $type;
/**
* @var bool
*
* @ORM\Column(name="obligatoire", type="boolean", nullable=false)
*/
private $obligatoire;
/**
* @var \TypeHabitat
*
* @ORM\ManyToOne(targetEntity="TypeHabitat")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_type_habitat_id", referencedColumnName="id")
* })
*/
private $idTypeHabitat;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $image;
public function __construct()
{
$this->image = "images/proprietes/2.png";
}
public function getId(): ?int
{
return $this->id;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(string $type): self
{
$this->type = $type;
return $this;
}
public function getObligatoire(): ?bool
{
return $this->obligatoire;
}
public function setObligatoire(bool $obligatoire): self
{
$this->obligatoire = $obligatoire;
return $this;
}
public function getIdTypeHabitat(): ?TypeHabitat
{
return $this->idTypeHabitat;
}
public function setIdTypeHabitat(?TypeHabitat $idTypeHabitat): self
{
$this->idTypeHabitat = $idTypeHabitat;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class SearchContentController extends AbstractController
{
/**
* @Route("/search/content", name="search_content")
*/
public function index(): Response
{
return $this->render('search_content/index.html.twig', [
'controller_name' => 'SearchContentController',
]);
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\CalendrierDomaineRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=CalendrierDomaineRepository::class)
*/
class CalendrierDomaine
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="date")
*/
private $dateDispo;
/**
* @ORM\ManyToOne(targetEntity=Domaine::class, inversedBy="calendrierDomaines")
*/
private $idDomaine;
public function getId(): ?int
{
return $this->id;
}
public function getDateDispo(): ?\DateTimeInterface
{
return $this->dateDispo;
}
public function setDateDispo(\DateTimeInterface $dateDispo): self
{
$this->dateDispo = $dateDispo;
return $this;
}
public function getIdDomaine(): ?Domaine
{
return $this->idDomaine;
}
public function setIdDomaine(?Domaine $idDomaine): self
{
$this->idDomaine = $idDomaine;
return $this;
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Coordonnees;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class CoordonneesType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('civilite', ChoiceType::class, [
'choices' => [
'Madame' => "Madame",
'Monsieur' => "Monsieur",
],
'expanded' => true,
'multiple' => false,
])
->add('nom', TextType::class, [
'attr' => array(
'placeholder' => 'Votre Nom'
)
])
->add('prenom', TextType::class, [
'attr' => array(
'placeholder' => 'Votre Prénom'
)
])
->add('email', EmailType::class, [
'attr' => array(
'placeholder' => '<EMAIL>'
)
])
->add('telephone', NumberType::class, [
'attr' => array(
'placeholder' => 'Votre Numéro de Téléphone'
)])
->add('adresse', TextType::class, [
'attr' => array(
'placeholder' => '123 Rue'
)
])
->add('cp', NumberType::class, [
'attr' => array(
'placeholder' => 'Votre Code Postal'
)
])
->add('ville', TextType::class, [
'attr' => array(
'placeholder' => 'Votre Ville',
'readonly' => true,
),
'help' => 'Entrer votre code postal pour afficher votre ville',
])
->add('pays', CountryType::class, [
'preferred_choices' => ['FR'],
])
->add('save', SubmitType::class, [
'attr' => ['class' => 'stripe-button'],
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Coordonnees::class,
]);
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\Propriete;
use App\Entity\Notification;
use App\Entity\ProprieteHabitat;
use App\Form\Propriete1Type;
use App\Repository\ProprieteRepository;
use App\Repository\ProprieteHabitatRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/propriete")
*/
class ProprieteController extends AbstractController
{
/**
* @Route("/", name="propriete_index", methods={"GET"})
*/
public function index(ProprieteRepository $proprieteRepository): Response
{
return $this->render('propriete/index.html.twig', [
'proprietes' => $proprieteRepository->findAll(),
]);
}
/**
* @Route("/new", name="propriete_new", methods={"POST"})
*/
public function new(Request $request): Response
{
$propriete = new Propriete();
$notification = new Notification();
$propriete_habitat = new ProprieteHabitat();
$notification->setTitle("Ajout d'un paramètre");
$form = $this->createForm(Propriete1Type::class, $propriete);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($propriete);
$propriete_habitat->setIdPropriete($propriete->getId());
$entityManager->persist($propriete_habitat);
$notification->setContenu("Un nouveau paramètre vient d'être ajouté pour les ".$propriete->getIdTypeHabitat() );
$notification->setTypeHabitat($propriete->getIdTypeHabitat());
$entityManager->persist($notification);
$entityManager->flush();
return $this->redirectToRoute('propriete_index');
}
return $this->render('propriete/new.html.twig', [
'propriete' => $propriete,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="propriete_show", methods={"GET"})
*/
public function show(Propriete $propriete): Response
{
return $this->render('propriete/show.html.twig', [
'propriete' => $propriete,
]);
}
/**
* @Route("/{id}/edit", name="propriete_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Propriete $propriete): Response
{
$form = $this->createForm(Propriete1Type::class, $propriete);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('propriete_index');
}
return $this->render('propriete/edit.html.twig', [
'propriete' => $propriete,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="propriete_delete", methods={"DELETE"})
*/
public function delete(Request $request, Propriete $propriete): Response
{
if ($this->isCsrfTokenValid('delete'.$propriete->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($propriete);
$entityManager->flush();
}
return $this->redirectToRoute('propriete_index');
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class PaiementController extends AbstractController
{
/**
* @Route("/paiement", name="paiement")
*/
public function index(): Response
{
return $this->render('paiement/index.html.twig', [
'controller_name' => 'PaiementController',
]);
}
/**
* @Route("/etape/reservation", name="paiement")
*/
public function stepReservation(): Response
{
return $this->render('paiement/index.html.twig', [
'controller_name' => 'PaiementController',
]);
}
}
<file_sep><?php
namespace App\DataFixtures;
use App\Entity\User;
use App\Entity\Activite;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
class UserFixtures extends Fixture
{
private $passwordEncoder ;
public function __construct(UserPasswordEncoderInterface $passwordEncoder)
{
$this->passwordEncoder = $passwordEncoder;
}
public function load(ObjectManager $manager)
{
$product = new User() ;
$product->setLogin("eshwar");
$product->setRoles(["ROLE_USER"]);
$product->setEmail("<EMAIL>");
$product->setNom("eshwar");
$product->setPrenom("tillai");
$product->setAdresse("202 Rue Desaix");
$product->setVille("Evry");
$product->setCP("72000");
$product->setDateNaissance(new \DateTime('now'));
$product->setGenre("Homme");
$product->setTelephone("0646437355");
$password = $this->passwordEncoder->encodePassword($product, 'mdpasse');
$product->setPassword($password);
$manager->persist($product);
$manager->flush();
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Repository\UserRepository;
use App\Entity\User ;
use App\Entity\Habitat ;
use App\Entity\Location;
use App\Entity\Equipement;
use App\Entity\Commentaire;
use App\Entity\PriseDeVue;
use App\Util\UploadedBase64;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Routing\Annotation\Route;
class ApiPostController extends AbstractController
{
/**
* @Route("userss", name="userss" , methods={"GET"})
*/
public function index(SerializerInterface $serializer): JsonResponse
{
$user = $this->getDoctrine()->getRepository(User::class)->findAll();
$json = $serializer->serialize($user, 'json' , ['groups' => 'user:read']);
$response = new JsonResponse($json, 200, [], true);
return $response;
}
/**
* @Route("display/{id}" , name="display" , methods={"GET"})
*/
public function gettroisNotifications(int $id, SerializerInterface $serializer): JsonResponse
{
$idLocataire = $this->getDoctrine()->getRepository(User::class)->findOneBy([ 'id' => $id ]);
$sql = 'SELECT DISTINCT (notification.id) , notification.titre, notification.contenu , notification.date_publication
FROM type_habitat,habitat,domaine,notification
WHERE type_habitat.id = habitat.id_type_habitat_id
AND domaine.id = habitat.id_domaine_id
AND type_habitat.id = notification.id_type_habitat
AND domaine.id_proprietaire_id = '.$id.'
AND notification.id_type_habitat IN (SELECT habitat.id_type_habitat_id
FROM habitat)
ORDER BY notification.date_publication DESC
LIMIT 3';
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$json = $serializer->serialize($stmt, 'json' , ['groups' => 'notification:info']);
$response = new JsonResponse($json, 200, [], true);
return $response;
}
/**
* @Route("utilisateurs/{id}" , name="usersid" , methods={"GET"})
*/
public function getUsersInfo(int $id, SerializerInterface $serializer): JsonResponse
{
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy([ 'id' => $id]);
$json = $serializer->serialize($user, 'json' , ['groups' => 'location:info']);
$response = new JsonResponse($json, 200, [], true);
return $response;
}
/**
* @Route("connexion", name="connexion" , methods={"POST"})
*/
public function loginUser(SerializerInterface $serializer, Request $request,UserPasswordEncoderInterface $encoder) : JsonResponse
{
$email = $request->query->get('email');
$password = $request->query->get('password');
$user = $this->getDoctrine()->getRepository(User::class)->findBy([ 'password' => $<PASSWORD>, 'email' => $email ]);
$json = $serializer->serialize($user, 'json' , ['groups' => 'user:read']);
$response = new JsonResponse($json, 200, [], true);
return $response;
}
/**
* @Route("habitatapp/{id}" , name="habitats_app" , methods={"GET"})
*/
public function getHabitat(int $id, SerializerInterface $serializer): JsonResponse
{
$habitat = $this->getDoctrine()->getRepository(Habitat::class)->findBy([ 'id' => $id]);
$json = $serializer->serialize($habitat, 'json' , ['groups' => 'location:info']);
$response = new JsonResponse($json, 200, [], true);
return $response;
}
/**
* @Route("rental/{id}" , name="locations_app" , methods={"GET"})
*/
public function getLocations(int $id, SerializerInterface $serializer): JsonResponse
{
$locataire = $this->getDoctrine()->getRepository(Location::class)->findBy([ 'idUserLocataire' => $id
]);
$json = $serializer->serialize($locataire, 'json' , ['groups' => 'location:info']);
$response = new JsonResponse($json, 200, [], true);
return $response;
}
/**
* @Route("equipement" , name="equipement_app" , methods={"GET"})
*/
public function getEquipements(SerializerInterface $serializer): JsonResponse
{
$equiped = $this->getDoctrine()->getRepository(Equipement::class)->findAll();
$json = $serializer->serialize($equiped, 'json' , ['groups' => 'location:info']);
$response = new JsonResponse($json, 200, [], true);
return $response;
}
/**
* @Route("commentapp/{id}" , name="comment_app" , methods={"GET"})
*/
public function getComments(int $id , SerializerInterface $serializer): JsonResponse
{
$comment = $this->getDoctrine()->getRepository(Commentaire::class)->findBy(['idHabitatIdCommentaire' => $id]);
$json = $serializer->serialize($comment, 'json' , ['groups' => 'location:info']);
$response = new JsonResponse($json, 200, [], true);
return $response;
}
/**
* @Route("photosapp/{id}" , name="photos_app" , methods={"GET"})
*/
public function getPhotos(int $id , SerializerInterface $serializer): JsonResponse
{
$comment = $this->getDoctrine()->getRepository(PriseDeVue::class)->findBy(['idHabitatIdPrisedevue' => $id]);
$json = $serializer->serialize($comment, 'json' , ['groups' => 'location:info']);
$response = new JsonResponse($json, 200, [], true);
return $response;
}
/**
* @Route("addphotoapp" , name="photo_app_add" , methods={"POST"})
*/
public function savePhotos(Request $request, SerializerInterface $serializer) : Response
{
$jsonRecu = $request->getContent();
$photos = $serializer->deserialize($jsonRecu, PriseDeVue::class, 'json');
$bien = $this->getDoctrine()->getRepository(Habitat::class)->findOneBy(['nom' => $photos->getIdHabitatIdPrisedevue()->getNom()]);
$prisedevue = new PriseDeVue();
$imageurl = $photos->getUrl();
$img = "<img src= 'data:image/jpeg;base64, $imageurl' />";
$fichier = md5(uniqid()).'.jpg';
$directory = $this->getParameter('photo_directory');
$success = file_put_contents($fichier, $img);
$imageFile = new UploadedBase64($img, $fichier);
$imageFile->move($directory, $fichier);
$prisedevue->setUrl($fichier);
$prisedevue->setIdHabitatIdPrisedevue($bien);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($prisedevue);
$entityManager->flush();
$response = new Response(
'Content',
Response::HTTP_OK,
['content-type' => 'text/html']
);
return $response;
}
/**
* @Route("addcommentapp" , name="comment_app_add" , methods={"POST"})
*/
public function saveComment(Request $request, SerializerInterface $serializer)
{
$entityManager = $this->getDoctrine()->getManager();
$jsonRecu = $request->getContent();
$comment = $serializer->deserialize($jsonRecu, Commentaire::class, 'json');
$habitat = $this->getDoctrine()->getRepository(Habitat::class)->findOneBy(['nom' => $comment->getIdHabitatIdCommentaire()->getNom()]);
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email' => $comment->getIdUser()->getEmail()]);
$commentaire = new Commentaire();
$commentaire->setTitre($comment->getTitre());
$commentaire->setContenu($comment->getContenu());
$commentaire->setIdHabitatIdCommentaire($habitat);
$commentaire->setIdUser($user);
$entityManager->persist($commentaire);
$entityManager->flush();
}
/**
* @Route("notifs/{id}" , name="notifs" , methods={"GET"})
*/
public function getNotifications(int $id, SerializerInterface $serializer): JsonResponse
{
$idLocataire = $this->getDoctrine()->getRepository(User::class)->findOneBy([ 'id' => $id ]);
$sql = 'SELECT DISTINCT (notification.id) , notification.titre, notification.contenu , notification.date_publication
FROM type_habitat,habitat,domaine,notification
WHERE type_habitat.id = habitat.id_type_habitat_id
AND domaine.id = habitat.id_domaine_id
AND type_habitat.id = notification.id_type_habitat
AND domaine.id_proprietaire_id = '.$id.'
AND notification.id_type_habitat IN (SELECT habitat.id_type_habitat_id
FROM habitat)
ORDER BY notification.date_publication DESC';
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$json = $serializer->serialize($stmt, 'json' , ['groups' => 'notification:info']);
$response = new JsonResponse($json, 200, [], true);
return $response;
}
/**
* @Route("userlogin" , name="user_login_app" , methods={"POST"})
*/
public function seConnecter(Request $request, SerializerInterface $serializer)
{
$entityManager = $this->getDoctrine()->getManager();
$jsonRecu = $request->getContent();
$loginsession = $serializer->deserialize($jsonRecu, User::class, 'json');
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy([ 'password' => $loginsession->getPassword() , 'email' => $loginsession->getEmail() ]);
$json = $serializer->serialize($user, 'json' , ['groups' => 'location:info']);
$response = new JsonResponse($json, 200, [], true);
return $response;
}
}
<file_sep><?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* PriseDeVue
*
* @ORM\Table(name="prise_de_vue", indexes={@ORM\Index(name="IDX_3EAEED81B5E42F98", columns={"id_activite_habitat_id"}), @ORM\Index(name="IDX_3EAEED81A74ADF1", columns={"id_habitat_id_prisedevue"})})
* @ORM\Entity
*/
class PriseDeVue
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @Assert\Unique
* @Groups("location:info")
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="url", type="string", length=150, nullable=false)
* @Assert\Image(
* minWidth = 1300,
* maxWidth = 1900,
* minHeight = 900,
* maxHeight = 1400,
* allowLandscape = false,
* allowPortrait = false
* )
* @Groups("location:info")
*/
private $url;
/**
* @var \Habitat
*
* @ORM\ManyToOne(targetEntity="Habitat")
* @Groups("location:info")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_habitat_id_prisedevue", referencedColumnName="id")
* })
*/
private $idHabitatIdPrisedevue;
/**
* @var \ActiviteHabitat
*
* @ORM\ManyToOne(targetEntity="ActiviteHabitat")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_activite_habitat_id", referencedColumnName="id")
* })
*/
private $idActiviteHabitat;
public function getId(): ?int
{
return $this->id;
}
public function getUrl(): ?string
{
return $this->url;
}
public function setUrl(string $url): self
{
$this->url = $url;
return $this;
}
public function getIdHabitatIdPrisedevue(): ?Habitat
{
return $this->idHabitatIdPrisedevue;
}
public function setIdHabitatIdPrisedevue(?Habitat $idHabitatIdPrisedevue): self
{
$this->idHabitatIdPrisedevue = $idHabitatIdPrisedevue;
return $this;
}
public function getIdActiviteHabitat(): ?ActiviteHabitat
{
return $this->idActiviteHabitat;
}
public function setIdActiviteHabitat(?ActiviteHabitat $idActiviteHabitat): self
{
$this->idActiviteHabitat = $idActiviteHabitat;
return $this;
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\Domaine;
use App\Form\DomaineType;
use App\Repository\DomaineRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/domaine")
*/
class DomaineController extends AbstractController
{
/**
* @Route("/", name="domaine_index", methods={"GET"})
*/
public function index(DomaineRepository $domaineRepository): Response
{
return $this->render('domaine/index.html.twig', [
'domaines' => $domaineRepository->findAll(),
]);
}
/**
* @Route("/new", name="domaine_new", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$domaine = new Domaine();
$form = $this->createForm(DomaineType::class, $domaine);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($domaine);
$entityManager->flush();
return $this->redirectToRoute('domaine_index');
}
return $this->render('domaine/new.html.twig', [
'domaine' => $domaine,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="domaine_show", methods={"GET"})
*/
public function show(Domaine $domaine): Response
{
return $this->render('domaine/show.html.twig', [
'domaine' => $domaine,
]);
}
/**
* @Route("/{id}/edit", name="domaine_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Domaine $domaine): Response
{
$form = $this->createForm(DomaineType::class, $domaine);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('domaine_index');
}
return $this->render('domaine/edit.html.twig', [
'domaine' => $domaine,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="domaine_delete", methods={"DELETE"})
*/
public function delete(Request $request, Domaine $domaine): Response
{
if ($this->isCsrfTokenValid('delete'.$domaine->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($domaine);
$entityManager->flush();
}
return $this->redirectToRoute('domaine_index');
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Domaine;
use App\Entity\DispoDomaine;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use App\Form\LocationOccupantType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use App\Form\DispoDomaineType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class DomaineCalendrierType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('dispoDomaine', CollectionType::class, [
'entry_type' => DispoDomaineType::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
])
->add('save', SubmitType::class, [
'attr' => ['class' => 'stripe-button'],
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Domaine::class,
]);
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Calendrier;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use App\Form\CalendarHabitatType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class DispoLogementType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('dateDispo', CollectionType::class, [
'entry_type' => CalendarHabitatType::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
'attr' => ['class' => 'js-datepicker'],
])
->add('save', SubmitType::class, [
'attr' => ['class' => 'stripe-button'],
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
]);
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20210619104501 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE newsletter (id INT AUTO_INCREMENT NOT NULL, email VARCHAR(150) NOT NULL, prenom VARCHAR(150) NOT NULL, anniversaire DATE DEFAULT NULL, hebergement_prefere VARCHAR(100) NOT NULL, region VARCHAR(200) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('ALTER TABLE propriete_habitat ADD CONSTRAINT FK_849F5456B3F033AD FOREIGN KEY (id_habitat_propriete_id) REFERENCES habitat (id)');
$this->addSql('CREATE INDEX IDX_849F5456B3F033AD ON propriete_habitat (id_habitat_propriete_id)');
$this->addSql('ALTER TABLE user CHANGE url url VARCHAR(65535) NOT NULL');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('DROP TABLE newsletter');
$this->addSql('ALTER TABLE propriete_habitat DROP FOREIGN KEY FK_849F5456B3F033AD');
$this->addSql('DROP INDEX IDX_849F5456B3F033AD ON propriete_habitat');
$this->addSql('ALTER TABLE user CHANGE url url TEXT CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_unicode_ci`');
}
}
<file_sep><?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* TypeHabitat
*
* @ORM\Table(name="type_habitat")
* @ORM\Entity
*/
class TypeHabitat
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @Assert\Unique
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
* @Assert\NotBlank
* @ORM\Column(name="nom", type="string", length=30, nullable=false)
*/
private $nom;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $description;
/**
* @ORM\Column(type="string", length=100)
* @Assert\Image(
* minWidth = 1300,
* maxWidth = 1900,
* minHeight = 900,
* maxHeight = 1400,
* allowLandscape = false,
* allowPortrait = false
* )
*/
private $image;
public function getId(): ?int
{
return $this->id;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function __toString() {
return $this->getId()."-".$this->getNom();
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\CalendrierRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=CalendrierRepository::class)
*/
class Calendrier
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="date")
*/
private $dateDispo;
/**
* @ORM\ManyToOne(targetEntity=Habitat::class)
*/
private $idHabitat;
/**
* @ORM\Column(type="string", length=100, nullable=true)
*/
private $etat;
public function getId(): ?int
{
return $this->id;
}
public function getDateDispo(): ?\DateTimeInterface
{
return $this->dateDispo;
}
public function setDateDispo(\DateTimeInterface $dateDispo): self
{
$this->dateDispo = $dateDispo;
return $this;
}
public function getIdHabitat(): ?Habitat
{
return $this->idHabitat;
}
public function setIdHabitat(?Habitat $idHabitat): self
{
$this->idHabitat = $idHabitat;
return $this;
}
public function getEtat(): ?string
{
return $this->etat;
}
public function setEtat(?string $etat): self
{
$this->etat = $etat;
return $this;
}
}
<file_sep><?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ReservationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('occupant', CollectionType::class, [
'entry_type' => OccupantType::class,
'entry_options' => ['label' => false],
]); ;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
// Configure your form options here
]);
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20210402110703 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE propriete_habitat DROP FOREIGN KEY FK_849F5456583BB8B6');
$this->addSql('DROP INDEX IDX_849F5456A74ADF1 ON propriete_habitat');
$this->addSql('ALTER TABLE propriete_habitat ADD id_habitat_propriete_id INT NOT NULL, DROP id_habitat_id_propriete, CHANGE id_propriete_id id_propriete_id INT NOT NULL, CHANGE valeur_propriete valeur_propriete VARCHAR(120) DEFAULT NULL');
$this->addSql('ALTER TABLE propriete_habitat ADD CONSTRAINT FK_849F5456B3F033AD FOREIGN KEY (id_habitat_propriete_id) REFERENCES habitat (id)');
$this->addSql('CREATE INDEX IDX_849F5456B3F033AD ON propriete_habitat (id_habitat_propriete_id)');
$this->addSql('ALTER TABLE user CHANGE url url VARCHAR(65535) NOT NULL');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE propriete_habitat DROP FOREIGN KEY FK_849F5456B3F033AD');
$this->addSql('DROP INDEX IDX_849F5456B3F033AD ON propriete_habitat');
$this->addSql('ALTER TABLE propriete_habitat ADD id_habitat_id_propriete INT DEFAULT NULL, DROP id_habitat_propriete_id, CHANGE id_propriete_id id_propriete_id INT DEFAULT NULL, CHANGE valeur_propriete valeur_propriete VARCHAR(30) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_unicode_ci`');
$this->addSql('ALTER TABLE propriete_habitat ADD CONSTRAINT FK_849F5456583BB8B6 FOREIGN KEY (id_habitat_id_propriete) REFERENCES habitat (id) ON UPDATE NO ACTION ON DELETE NO ACTION');
$this->addSql('CREATE INDEX IDX_849F5456A74ADF1 ON propriete_habitat (id_habitat_id_propriete)');
$this->addSql('ALTER TABLE user CHANGE url url TEXT CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_unicode_ci`');
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Location;
use App\Entity\Occupant;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use App\Form\LocationOccupantType;
use App\Form\OccupantType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class LocationOccupantType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('occupants', CollectionType::class, [
'entry_type' => OccupantType::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
])
->add('save', SubmitType::class, [
'attr' => ['class' => 'stripe-button'],
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Location::class,
]);
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20210106180558 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('DROP TABLE propriete_habitat');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE propriete_habitat (id INT AUTO_INCREMENT NOT NULL, id_propriete_id INT DEFAULT NULL, id_habitat_id_propriete INT DEFAULT NULL, valeur_propriete VARCHAR(30) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_unicode_ci`, INDEX IDX_849F54563B9719DD (id_propriete_id), INDEX IDX_849F5456A74ADF1 (id_habitat_id_propriete), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_unicode_ci` ENGINE = InnoDB COMMENT = \'\' ');
$this->addSql('ALTER TABLE propriete_habitat ADD CONSTRAINT FK_849F54563B9719DD FOREIGN KEY (id_propriete_id) REFERENCES propriete (id) ON UPDATE NO ACTION ON DELETE NO ACTION');
$this->addSql('ALTER TABLE propriete_habitat ADD CONSTRAINT FK_849F5456583BB8B6 FOREIGN KEY (id_habitat_id_propriete) REFERENCES habitat (id) ON UPDATE NO ACTION ON DELETE NO ACTION');
}
}
<file_sep><?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* ActiviteHabitat
*
* @ORM\Table(name="activite_habitat", indexes={@ORM\Index(name="IDX_7191756DD0165F20", columns={"type_activite_id"})})
* @ORM\Entity
*/
class ActiviteHabitat
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @Assert\Unique
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var float
* @ORM\Column(name="distance", type="float", precision=10, scale=0, nullable=false)
*/
private $distance;
/**
* @var \Activite
*
* @ORM\ManyToOne(targetEntity="Activite")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="type_activite_id", referencedColumnName="id")
* })
*/
private $typeActivite;
/**
* @ORM\ManyToOne(targetEntity=Habitat::class)
* @ORM\JoinColumn(nullable=false)
*/
private $idHabitat;
/**
* Constructor
*/
public function __construct()
{
$this->habitat = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getDistance(): ?float
{
return $this->distance;
}
public function setDistance(float $distance): self
{
$this->distance = $distance;
return $this;
}
public function getTypeActivite(): ?Activite
{
return $this->typeActivite;
}
public function setTypeActivite(?Activite $typeActivite): self
{
$this->typeActivite = $typeActivite;
return $this;
}
public function getIdHabitat(): ?Habitat
{
return $this->idHabitat;
}
public function setIdHabitat(?Habitat $idHabitat): self
{
$this->idHabitat = $idHabitat;
return $this;
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Domaine;
use App\Entity\Region ;
use App\Entity\Equipement;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TimeType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class DomaineType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nom')
->add('description', TextareaType::class)
->add('image', FileType::class, array('data_class' => null))
->add('arrive', TimeType::class, [
'input' => 'datetime',
'widget' => 'single_text',
])
->add('depart', TimeType::class, [
'input' => 'datetime',
'widget' => 'single_text',
])
->add('adresse')
->add('ville')
->add('region', EntityType::class, [
// looks for choices from this entity
'class' => Region::class,
// uses the User.username property as the visible option string
'choice_label' => 'Nom',
// used to render a select box, check boxes or radios
'multiple' => false,
'expanded' => false,
])
->add('equipement', EntityType::class, [
// looks for choices from this entity
'class' => Equipement::class,
// uses the User.username property as the visible option string
'choice_label' => 'Nom',
// used to render a select box, check boxes or radios
'multiple' => true,
'expanded' => true,
])
->add('save', SubmitType::class, [
'attr' => ['class' => 'btn-edit-profile '],
'label' => "Enregistrez"
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Domaine::class,
]);
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\ActiviteHabitat;
use App\Entity\Habitat;
use App\Form\ActiviteHabitat1Type;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/activite/habitat")
*/
class ActiviteHabitatController extends AbstractController
{
/**
* @Route("/{id}", name="activite_habitat_index", methods={"GET"})
*/
public function index(int $id): Response
{
$activiteHabitats = $this->getDoctrine()->getRepository(ActiviteHabitat::class)->findBy(['idHabitat' => $id ]);
$habitat = $this->getDoctrine()->getRepository(Habitat::class)->find($id);
return $this->render('activite_habitat/index.html.twig', [
'activite_habitats' => $activiteHabitats,
'habitat' => $habitat
]);
}
/**
* @Route("{id}/new", name="activite_habitat_new", methods={"GET","POST"})
*/
public function new(int $id , Request $request): Response
{
$activiteHabitat = new ActiviteHabitat();
$habitat = $this->getDoctrine()->getRepository(Habitat::class)->find($id);
$form = $this->createForm(ActiviteHabitat1Type::class, $activiteHabitat);
$activiteHabitat->setIdHabitat($habitat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($activiteHabitat);
$entityManager->flush();
return $this->redirectToRoute('/habitat' );
}
return $this->render('activite_habitat/new.html.twig', [
'activite_habitat' => $activiteHabitat,
'form' => $form->createView(),
'habitat' => $habitat,
]);
}
/**
* @Route("/{idActiviteH}", name="activite_habitat_show", methods={"GET"})
*/
public function show(ActiviteHabitat $activiteHabitat): Response
{
return $this->render('activite_habitat/show.html.twig', [
'activite_habitat' => $activiteHabitat,
]);
}
/**
* @Route("/{idActiviteH}/edit", name="activite_habitat_edit", methods={"GET","POST"})
*/
public function edit(Request $request, ActiviteHabitat $activiteHabitat): Response
{
$form = $this->createForm(ActiviteHabitat1Type::class, $activiteHabitat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('activite_habitat_index');
}
return $this->render('activite_habitat/edit.html.twig', [
'activite_habitat' => $activiteHabitat,
'form' => $form->createView(),
]);
}
/**
* @Route("/{idActiviteH}", name="activite_habitat_delete", methods={"DELETE"})
*/
public function delete(Request $request, ActiviteHabitat $activiteHabitat): Response
{
if ($this->isCsrfTokenValid('delete'.$activiteHabitat->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($activiteHabitat);
$entityManager->flush();
}
return $this->redirectToRoute('activite_habitat_index');
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\NotificationRepository;
use App\Entity\Notification ;
use App\Entity\User;
class NotificationController extends AbstractController
{
/**
* @Route("/notification", name="notification")
*/
public function index(NotificationRepository $notification)
{
$user = 4;
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$sql = 'SELECT DISTINCT (notification.id) , notification.titre, notification.contenu , notification.date_publication
FROM type_habitat,habitat,domaine,notification
WHERE type_habitat.id = habitat.id_type_habitat_id
AND domaine.id = habitat.id_domaine_id
AND type_habitat.id = notification.id_type_habitat
AND domaine.id_proprietaire_id = '.$user.'
AND notification.id_type_habitat IN (SELECT habitat.id_type_habitat_id
FROM habitat)
ORDER BY notification.date_publication DESC';
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$notification->countBy($user);
return $this->render('userinterface/alertes.html.twig', [
'controller_name' => 'NotificationController', 'notifs' => $stmt , 'profil' => $profil
]);
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20210101172833 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE domaine_equipement MODIFY id INT NOT NULL');
$this->addSql('ALTER TABLE domaine_equipement DROP FOREIGN KEY FK_23C6DFED3E47DE39');
$this->addSql('ALTER TABLE domaine_equipement DROP FOREIGN KEY FK_23C6DFEDDE2F4FD7');
$this->addSql('DROP INDEX IDX_23C6DFED3E47DE39 ON domaine_equipement');
$this->addSql('DROP INDEX IDX_23C6DFEDDE2F4FD7 ON domaine_equipement');
$this->addSql('ALTER TABLE domaine_equipement DROP PRIMARY KEY');
$this->addSql('ALTER TABLE domaine_equipement ADD domaine_id INT NOT NULL, ADD equipement_id INT NOT NULL, DROP id, DROP id_domaine_equip_id, DROP id_equipement_id');
$this->addSql('ALTER TABLE domaine_equipement ADD CONSTRAINT FK_23C6DFED4272FC9F FOREIGN KEY (domaine_id) REFERENCES domaine (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE domaine_equipement ADD CONSTRAINT FK_23C6DFED806F0F5C FOREIGN KEY (equipement_id) REFERENCES equipement (id) ON DELETE CASCADE');
$this->addSql('CREATE INDEX IDX_23C6DFED4272FC9F ON domaine_equipement (domaine_id)');
$this->addSql('CREATE INDEX IDX_23C6DFED806F0F5C ON domaine_equipement (equipement_id)');
$this->addSql('ALTER TABLE domaine_equipement ADD PRIMARY KEY (domaine_id, equipement_id)');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE domaine_equipement DROP FOREIGN KEY FK_23C6DFED4272FC9F');
$this->addSql('ALTER TABLE domaine_equipement DROP FOREIGN KEY FK_23C6DFED806F0F5C');
$this->addSql('DROP INDEX IDX_23C6DFED4272FC9F ON domaine_equipement');
$this->addSql('DROP INDEX IDX_23C6DFED806F0F5C ON domaine_equipement');
$this->addSql('ALTER TABLE domaine_equipement ADD id INT AUTO_INCREMENT NOT NULL, ADD id_domaine_equip_id INT NOT NULL, ADD id_equipement_id INT NOT NULL, DROP domaine_id, DROP equipement_id, DROP PRIMARY KEY, ADD PRIMARY KEY (id)');
$this->addSql('ALTER TABLE domaine_equipement ADD CONSTRAINT FK_23C6DFED3E47DE39 FOREIGN KEY (id_equipement_id) REFERENCES equipement (id) ON UPDATE NO ACTION ON DELETE NO ACTION');
$this->addSql('ALTER TABLE domaine_equipement ADD CONSTRAINT FK_23C6DFEDDE2F4FD7 FOREIGN KEY (id_domaine_equip_id) REFERENCES domaine (id) ON UPDATE NO ACTION ON DELETE NO ACTION');
$this->addSql('CREATE INDEX IDX_23C6DFED3E47DE39 ON domaine_equipement (id_equipement_id)');
$this->addSql('CREATE INDEX IDX_23C6DFEDDE2F4FD7 ON domaine_equipement (id_domaine_equip_id)');
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Habitat;
use App\Entity\TypeHabitat;
use App\Entity\Region;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class SearchHabitatType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('region', EntityType::class, [
// looks for choices from this entity
'class' => Region::class,
'label' => false,
'help' => 'Make sure to add a valid email',
'attr' => ['class' => 'champCustomize'],
// uses the User.username property as the visible option string
'choice_label' => 'Nom',
'placeholder' => "Destination",
])
->add('capacite', ChoiceType::class, [
'choices' => [
'1' => 1,
'2' => 2,
'3' => 3,
'4' => 4,
'5' => 5,
'6' => 6,
'7' => 7,
'8' => 8,
'9' => 9,
'10' => 10,],
'choice_attr' => function($choice, $key, $value) {
return ['class' => 'optionNb'];
},
'help' => 'Make sure to add a valid email',
'placeholder' => 'Personnes',
'attr' => ['class' => 'champCustomize'],
'label' => false,
])
->add('idTypeHabitat', EntityType::class, [
// looks for choices from this entity
'class' => TypeHabitat::class,
'label' => false,
'help' => 'Make sure to add a valid email',
// uses the User.username property as the visible option string
'choice_label' => 'Nom',
'placeholder' => "Type d'Habitat",
'attr' => [
'id' => 'jetestedestrucs',
'class' => 'champCustomize'
],
// used to render a select box, check boxes or radios
'multiple' => false,
'expanded' => false,
])
->add('save', SubmitType::class, [
]);
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Habitat::class,
]);
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Habitat;
use App\Entity\TypeHabitat;
use App\Entity\Activite;
use Symfony\Component\Form\AbstractType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
class HabitatType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nom', TextType::class)
->add('idTypeHabitat', EntityType::class, [
// looks for choices from this entity
'class' => TypeHabitat::class,
// uses the User.username property as the visible option string
'choice_label' => 'Nom',
// used to render a select box, check boxes or radios
'multiple' => false,
'expanded' => false,
])
->add('nbCouchages', ChoiceType::class, [
'choices' => [
'1' => 1,
'2' => 2,
'3' => 3,
'4' => 4,
'5' => 5,
'6' => 6,
'7' => 7,
'8' => 8,
'9' => 9,
'10' => 10,
]
])
->add('capacite', ChoiceType::class, [
'choices' => [
'1' => 1,
'2' => 2,
'3' => 3,
'4' => 4,
'5' => 5,
'6' => 6,
'7' => 7,
'8' => 8,
'9' => 9,
'10' => 10,
]
])
->add('prix', MoneyType::class)
->add('ville', TextType::class)
->add('url',FileType::class, array('data_class' => null))
->add('description', TextareaType::class)
->add('activiteHabitat', EntityType::class, [
// looks for choices from this entity
'class' => Activite::class,
'mapped' => false ,
// uses the User.username property as the visible option string
'choice_label' => 'Nom',
// used to render a select box, check boxes or radios
'multiple' => true,
'expanded' => true
])
->add('save', SubmitType::class, [
'attr' => ['class' => 'btn-edit-profile '],
'label' => "Enregistrez"
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Habitat::class,
]);
}
}
<file_sep><?php
namespace App\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use App\Entity\TypeHabitat;
use App\Entity\Activite;
use App\Entity\Habitat;
use App\Entity\User;
use Symfony\Component\Validator\Constraints\DateTime;
class AppFixtures extends Fixture
{
public function load(ObjectManager $manager)
{
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20210624191943 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE location (id INT AUTO_INCREMENT NOT NULL, id_user_locataire INT DEFAULT NULL, id_habitat_id_location INT DEFAULT NULL, date_reservation DATETIME NOT NULL, dateDebut DATETIME NOT NULL, dateFin DATETIME NOT NULL, statut VARCHAR(25) NOT NULL, appreciation TINYINT(1) DEFAULT NULL, nb_personnes INT NOT NULL, INDEX IDX_5E9E89CB79F37AE5 (id_user_locataire), INDEX IDX_5E9E89CBA74ADF1 (id_habitat_id_location), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('CREATE TABLE occupant (id INT AUTO_INCREMENT NOT NULL, id_location_id INT NOT NULL, type VARCHAR(200) NOT NULL, INDEX IDX_E7D9DBCA1E5FEC79 (id_location_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('ALTER TABLE location ADD CONSTRAINT FK_5E9E89CBF9FAC609 FOREIGN KEY (id_user_locataire) REFERENCES user (id)');
$this->addSql('ALTER TABLE location ADD CONSTRAINT FK_5E9E89CB79273E71 FOREIGN KEY (id_habitat_id_location) REFERENCES habitat (id)');
$this->addSql('ALTER TABLE occupant ADD CONSTRAINT FK_E7D9DBCA1E5FEC79 FOREIGN KEY (id_location_id) REFERENCES location (id)');
$this->addSql('ALTER TABLE habitat ADD CONSTRAINT FK_3B37B2E898260155 FOREIGN KEY (region_id) REFERENCES region (id)');
$this->addSql('CREATE INDEX IDX_3B37B2E898260155 ON habitat (region_id)');
$this->addSql('ALTER TABLE user CHANGE url url VARCHAR(65535) NOT NULL');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE occupant DROP FOREIGN KEY FK_E7D9DBCA1E5FEC79');
$this->addSql('DROP TABLE location');
$this->addSql('DROP TABLE occupant');
$this->addSql('ALTER TABLE habitat DROP FOREIGN KEY FK_3B37B2E898260155');
$this->addSql('DROP INDEX IDX_3B37B2E898260155 ON habitat');
$this->addSql('ALTER TABLE user CHANGE url url MEDIUMTEXT CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_unicode_ci`');
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Habitat;
use App\Entity\ActiviteHabitat;
use Symfony\Component\HttpFoundation\Session\Session;
use App\Entity\User;
use App\Entity\PriseDeVue;
use App\Entity\Region;
use App\Entity\Commentaire;
use App\Entity\Domaine;
use App\Entity\TypeHabitat;
use App\Entity\Location;
use App\Form\SearchHabitatType;
use App\Form\ContactOwnerType;
use App\Form\PriseDeVueType;
use App\Form\CommentaireType;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class InternauteController extends AbstractController
{
/**
* @Route("/internaute", name="internaute")
*/
public function index()
{
$habitat = new Habitat() ;
$activite = new ActiviteHabitat();
$userId = 4 ;
$profil = $this->getDoctrine()->getRepository(User::class)->find($userId);
$repository = $this->getDoctrine()->getRepository(Location::class);
$historique = $repository->findBy([ 'idUserLocataire' => $userId]
);
//$this->denyAccessUnlessGranted('ROLE_USER');
return $this->render('userinterface/dashboard.html.twig', [
'habitat' => $habitat , 'activite' => $activite , 'historiques' => $historique, 'profil' => $profil
]);
}
/**
* @Route("/home", name="home" , methods={"GET" ,"POST"})
*/
public function home(Request $request)
{
$typehabitat = $this->getDoctrine()->getRepository(TypeHabitat::class)->findAll();
$habitats = $this->getDoctrine()->getRepository(Domaine::class)->findAll();
$recherche = new Habitat();
$region = $this->getDoctrine()->getRepository(Region::class)->findAll();
$form = $this->createForm(SearchHabitatType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$recherche = $form->getData();
// ... do any other work - like sending them an email, etc
// maybe set a "flash" success message for the user
return $this->redirectToRoute('listeRecherche', ['habitat' => $recherche->getIdTypeHabitat()->getId() , 'region' => $recherche->getRegion()->getId() , 'capacite' => $recherche->getCapacite()]);
}
return $this->render('accueil/index.html.twig', [ 'habitats' => $habitats, 'regions' => $region ,'form' => $form->createView() ,'types' => $typehabitat
]);
}
/**
* @Route("/listeDomaines", name="domaine_liste")
*/
public function listeDomaine() {
$types = $this->getDoctrine()->getRepository(Region::class)->findAll();
return $this->render('etablissement/domaines.html.twig', [
'controller_name' => 'InternauteController' , 'types' => $types
]);
}
/**
* @Route("/hebergement", name="hebergements")
*/
public function listeHebergement() {
$typehabitat = $this->getDoctrine()->getRepository(TypeHabitat::class)->findAll();
return $this->render('hebergements/hebergement.html.twig', [
'controller_name' => 'InternauteController' ,'types' => $typehabitat
]);
}
/**
* @Route("/domaines/locations/{id}", name="domaine_details")
*/
public function listeLocations(int $id) {
$contact = $this->createForm(ContactOwnerType::class);
$domaine = $this->getDoctrine()->getRepository(Domaine::class)->find($id);
$habitat= $this->getDoctrine()->getRepository(Habitat::class)->findby(
[ 'idDomaine' => $id ]
);
if ($contact->isSubmitted() && $contact->isValid()) {
$expediteur = $contact->get('email')->getData();
$objet = $contact->get('objet')->getData();
$contenu = $contact->get('contenu')->getData();
$destinataire = $user->getEmail();
$email = (new Email())
->from($expediteur)
->to('<EMAIL>')
->subject($objet)
->text($contenu);
$mailer->send($email);
return $this->redirectToRoute('habitat_domaines' , array('id' => $location->getId()));
}
return $this->render('etablissement/locations.html.twig', [
'controller_name' => 'InternauteController' , 'domaine' => $domaine , 'habitats' => $habitat , 'contact' => $contact->createView()
]);
}
/**
* @Route("/listeHistorique", name="listeHistorique")
*/
public function listeHistorique()
{
$userId = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($userId);
$repository = $this->getDoctrine()->getRepository(Location::class);
$user = $this->getDoctrine()->getRepository(User::class)->find($this->getUser()->getId());
$historique = $repository->findby(['idUserLocataire' => $user , 'statut' => "Valide"]);
return $this->render('userinterface/meslocations.html.twig', [
'controller_name' => 'InternauteController', 'locations' => $historique , 'profil' => $profil
]);
}
/**
* @Route("/locations/comment", name="locations_comments")
*/
public function locationsCommentaire()
{
$userId = 4;
$profil = $this->getDoctrine()->getRepository(User::class)->find($userId);
$repository = $this->getDoctrine()->getRepository(Location::class);
$user = $this->getDoctrine()->getRepository(User::class)->find($userId);
$historique = $repository->findby(['idUserLocataire' => $user , 'statut' => "Valide"]);
return $this->render('userinterface/comment/listeLocation.html.twig', [
'controller_name' => 'InternauteController', 'locations' => $historique , 'profil' => $profil
]);
}
/**
* @Route("/listeHistorique/details/{id}", name="listeHistorique_details")
*/
public function showDetailsReservation(Request $request , int $id){
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$habitat = $this->getDoctrine()->getRepository(Location::class)->find($id);
$bien = $habitat->getIdHabitatIdLocation();
$idBien = $bien->getId();
$activite = $this->getDoctrine()->getRepository(ActiviteHabitat::class)->findby(['idHabitat' => $idBien]);
$photo = $this->createForm(PriseDeVueType::class);
$form = $this->createForm(CommentaireType::class);
$commentaire = new Commentaire();
$prisedevue = new PriseDeVue();
$prisedevue->setIdHabitatIdPrisedevue($bien);
$form->handleRequest($request);
$photo->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$commentaire = $form->getData();
$commentaire->setIdUser($this->getUser());
$commentaire->setIdHabitatIdCommentaire($bien);
// ... do any other work - like sending them an email, etc
// maybe set a "flash" success message for the user
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($commentaire);
$entityManager->flush();
return $this->redirectToRoute('listeHistorique_details', ['id' => $id ]);
}
if ($photo->isSubmitted() && $photo->isValid()) {
$imageurl = $photo->get('url')->getData();
$fichier = md5(uniqid()) . '.' . $imageurl->guessExtension();
$directory = $this->getParameter('photo_directory');
$extension = $imageurl->guessExtension();
$imageurl->move($directory, $fichier);
$prisedevue->setUrl($fichier);
$prisedevue->setIdHabitatIdPrisedevue($bien);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($prisedevue);
$entityManager->flush();
return $this->redirectToRoute('listeHistorique_details', ['id' => $id ]);
}
return $this->render('userinterface/meslocationsdetails.html.twig', [
'controller_name' => 'InternauteController', 'profil' => $profil , 'location' => $habitat , 'form' => $form->createView() , 'activites' => $activite , 'photo' => $photo->createView()
]);
}
/**
* @Route("/reservationAttente/{id}", name="reservation_attente")
*/
public function gererReservation(int $id)
{
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$reservation = $this->getDoctrine()->getRepository(Location::class)->findBy(['idHabitatIdLocation' => $id , 'statut' => 'En Attente']);
return $this->render('userinterface/reservationHabitat.html.twig', [
'controller_name' => 'InternauteController', 'locations' => $reservation , 'profil' => $profil]);
}
/**
* @Route("/searchresult", name="searchresult")
*/
public function searchResult() {
return $this->render('searchresult.html.twig', [
'controller_name' => 'InternauteController']);
}
/**
* @Route("/valider/{idLocation}", name="valider")
*/
public function valider(int $idLocation)
{
$repository = $this->getDoctrine()->getManager();
$location = $repository->getRepository(Location::class)->find($idLocation);
$idhabitat = $location->getIdHabitatIdLocation();
$location->setStatut('Validé');
$repository->flush();
$this->addFlash('success', 'La réservation à bien été validé');
return $this->redirectToRoute('reservation_attente' , ['id' => $idhabitat]);
}
}
<file_sep><?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Serializer\Annotation\Groups;
use Doctrine\ORM\Mapping as ORM;
/**
* Notification
*
* @ORM\Table(name="notification", indexes={@ORM\Index(name="fk_typehabitat", columns={"id_type_habitat"})})
* @ORM\Entity
*/
class Notification
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
* @Groups("notification:info")
* @ORM\Column(name="titre", type="string", length=50, nullable=false)
*/
private $titre;
/**
* @var string
* @Groups("notification:info")
* @ORM\Column(name="contenu", type="string", length=255, nullable=false)
*/
private $contenu;
/**
* @var \TypeHabitat
*
* @ORM\ManyToOne(targetEntity="TypeHabitat")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_type_habitat", referencedColumnName="id")
* })
*/
private $idTypeHabitat;
/**
* @ORM\ManyToMany(targetEntity=Habitat::class, inversedBy="notification")
*/
private $idHabitat;
/**
* @ORM\Column(type="date")
*/
private $datePublication;
public function __construct()
{
$this->idHabitat = new ArrayCollection();
$this->datePublication = new \DateTime('now');
}
public function getId(): ?int
{
return $this->id;
}
public function getTitre(): ?string
{
return $this->titre;
}
public function setTitre(string $titre): self
{
$this->titre = $titre;
return $this;
}
public function getContenu(): ?string
{
return $this->contenu;
}
public function setContenu(string $contenu): self
{
$this->contenu = $contenu;
return $this;
}
public function getIdTypeHabitat(): ?TypeHabitat
{
return $this->idTypeHabitat;
}
public function setIdTypeHabitat(?TypeHabitat $idTypeHabitat): self
{
$this->idTypeHabitat = $idTypeHabitat;
return $this;
}
/**
* @return Collection|Habitat[]
*/
public function getIdHabitat(): Collection
{
return $this->idHabitat;
}
public function addIdHabitat(Habitat $idHabitat): self
{
if (!$this->idHabitat->contains($idHabitat)) {
$this->idHabitat[] = $idHabitat;
}
return $this;
}
public function removeIdHabitat(Habitat $idHabitat): self
{
$this->idHabitat->removeElement($idHabitat);
return $this;
}
public function getDatePublication(): ?\DateTimeInterface
{
return $this->datePublication;
}
public function setDatePublication(\DateTimeInterface $datePublication): self
{
$this->datePublication = $datePublication;
return $this;
}
}
<file_sep><?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Braintree
*
* @ORM\Table(name="braintree")
* @ORM\Entity
*/
class Braintree
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="merchant_id", type="string", length=40, nullable=false)
*/
private $merchantId;
/**
* @var string
*
* @ORM\Column(name="public_key", type="string", length=30, nullable=false)
*/
private $publicKey;
/**
* @var string
*
* @ORM\Column(name="private_key", type="string", length=70, nullable=false)
*/
private $privateKey;
public function getId(): ?int
{
return $this->id;
}
public function getMerchantId(): ?string
{
return $this->merchantId;
}
public function setMerchantId(string $merchantId): self
{
$this->merchantId = $merchantId;
return $this;
}
public function getPublicKey(): ?string
{
return $this->publicKey;
}
public function setPublicKey(string $publicKey): self
{
$this->publicKey = $publicKey;
return $this;
}
public function getPrivateKey(): ?string
{
return $this->privateKey;
}
public function setPrivateKey(string $privateKey): self
{
$this->privateKey = $privateKey;
return $this;
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20201227091538 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE domaine_equipement (id INT AUTO_INCREMENT NOT NULL, id_domaine_equip_id INT NOT NULL, id_equipement_id INT NOT NULL, INDEX IDX_23C6DFEDDE2F4FD7 (id_domaine_equip_id), INDEX IDX_23C6DFED3E47DE39 (id_equipement_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('ALTER TABLE domaine_equipement ADD CONSTRAINT FK_23C6DFEDDE2F4FD7 FOREIGN KEY (id_domaine_equip_id) REFERENCES domaine (id)');
$this->addSql('ALTER TABLE domaine_equipement ADD CONSTRAINT FK_23C6DFED3E47DE39 FOREIGN KEY (id_equipement_id) REFERENCES equipement (id)');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('DROP TABLE domaine_equipement');
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Propriete;
use App\Entity\TypeHabitat;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ProprieteType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nom', TextType::class)
->add('type', ChoiceType::class, [
'choices' => [
'Chaîne de caractère' => 'chaine',
'Entier' => 'entier',
'Décimal' => "decimal",
]])
->add('obligatoire', CheckboxType::class , array('required' => false , 'data' => true))
->add('idTypeHabitat',EntityType::class, [
'class' => TypeHabitat::class,
// uses the User.username property as the visible option string
'choice_label' => 'Nom',
// used to render a select box, check boxes or radios
'multiple' => false,
'expanded' => false,
])
->add('save', SubmitType::class, ['label' => 'Valider'])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Propriete::class,
]);
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\NewsletterRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=NewsletterRepository::class)
*/
class Newsletter
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=150)
*/
private $email;
/**
* @ORM\Column(type="string", length=150)
*/
private $prenom;
/**
* @ORM\Column(type="date", nullable=true)
*/
private $anniversaire;
/**
* @ORM\ManyToOne(targetEntity=Region::class)
* @ORM\JoinColumn(nullable=false)
*/
private $region;
/**
* @ORM\ManyToOne(targetEntity=TypeHabitat::class)
* @ORM\JoinColumn(nullable=false)
*/
private $Hebergement;
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getPrenom(): ?string
{
return $this->prenom;
}
public function setPrenom(string $prenom): self
{
$this->prenom = $prenom;
return $this;
}
public function getAnniversaire(): ?\DateTimeInterface
{
return $this->anniversaire;
}
public function setAnniversaire(?\DateTimeInterface $anniversaire): self
{
$this->anniversaire = $anniversaire;
return $this;
}
public function getRegion(): ?Region
{
return $this->region;
}
public function setRegion(?Region $region): self
{
$this->region = $region;
return $this;
}
public function getHebergement(): ?TypeHabitat
{
return $this->Hebergement;
}
public function setHebergement(?TypeHabitat $Hebergement): self
{
$this->Hebergement = $Hebergement;
return $this;
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\ProprieteHabitatRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=ProprieteHabitatRepository::class)
*/
class ProprieteHabitat
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity=Propriete::class)
* @ORM\JoinColumn(nullable=false,onDelete="CASCADE")
*/
private $idPropriete;
/**
* @ORM\ManyToOne(targetEntity=Habitat::class)
* @ORM\JoinColumn(nullable=false)
*/
private $IdHabitatPropriete;
/**
* @ORM\Column(type="string", length=120, nullable=true)
*/
private $valeurPropriete;
public function getId(): ?int
{
return $this->id;
}
public function getIdPropriete(): ?Propriete
{
return $this->idPropriete;
}
public function setIdPropriete(?Propriete $idPropriete): self
{
$this->idPropriete = $idPropriete;
return $this;
}
public function getIdHabitatPropriete(): ?Habitat
{
return $this->IdHabitatPropriete;
}
public function setIdHabitatPropriete(?Habitat $IdHabitatPropriete): self
{
$this->IdHabitatPropriete = $IdHabitatPropriete;
return $this;
}
public function getValeurPropriete(): ?string
{
return $this->valeurPropriete;
}
public function setValeurPropriete(?string $valeurPropriete): self
{
$this->valeurPropriete = $valeurPropriete;
return $this;
}
}
<file_sep><?php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* Activite
*
* @ORM\Table(name="activite")
* @ORM\Entity
*/
class Activite
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nom", type="string", length=30, nullable=false)
*/
private $nom;
/**
*
* @ORM\Column(type="string", length=150)
*/
private $image;
/**
* @ORM\Column(type="float")
*/
private $prix;
/**
* @ORM\Column(type="string", length=255)
*/
private $adresse;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $description;
/**
* @ORM\ManyToOne(targetEntity=Domaine::class)
* @ORM\JoinColumn(nullable=false)
*/
private $idDomaine;
public function getId(): ?int
{
return $this->id;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function __toString(){
// to show the name of the Category in the select
return $this->nom;
// to show the id of the Category in the select
// return $this->id;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
public function getPrix(): ?float
{
return $this->prix;
}
public function setPrix(float $prix): self
{
$this->prix = $prix;
return $this;
}
public function getAdresse(): ?string
{
return $this->adresse;
}
public function setAdresse(string $adresse): self
{
$this->adresse = $adresse;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getIdDomaine(): ?Domaine
{
return $this->idDomaine;
}
public function setIdDomaine(?Domaine $idDomaine): self
{
$this->idDomaine = $idDomaine;
return $this;
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Newsletter;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\RadioType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use App\Entity\TypeHabitat;
use App\Entity\Region;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class NewsletterType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email',EmailType::class, [
'help' => "Votre adresse mail devrat être vérifier",
'attr' => array(
'placeholder' => '<EMAIL>',
)
])
->add('prenom')
->add('anniversaire' , DateType::class, [
'widget' => 'single_text',
'attr' => ['class' => 'js-datepicker'],
'html5' => false,
])
->add('hebergement', EntityType::class, [
// looks for choices from this entity
'class' => TypeHabitat::class,
'label' => false,
'help' => 'Make sure to add a valid email',
// uses the User.username property as the visible option string
'choice_label' => 'Nom',
'placeholder' => "Choisissez une valeur",
'attr' => [
'id' => 'jetestedestrucs',
],
// used to render a select box, check boxes or radios
'multiple' => false,
'expanded' => false,
])
->add('region', EntityType::class, [
// looks for choices from this entity
'class' => Region::class,
'label' => false,
'help' => 'Make sure to add a valid email',
// uses the User.username property as the visible option string
'choice_label' => 'Nom',
'placeholder' => "Choisissez une valeur",
])
->add('save', SubmitType::class, [
'attr' => ['class' => 'bouton-violet'],
]);
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Newsletter::class,
]);
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use App\Entity\Location;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\InputBag;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
class StripeController extends AbstractController
{
/**
* @Route("/stripe", name="stripe")
*/
public function index(Request $request): Response
{
var_dump($request->request->all());
return $this->render('stripe/index.html.twig', [
'controller_name' => 'StripeController',
]);
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\DomaineRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Serializer\Annotation\Groups;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=DomaineRepository::class)
*/
class Domaine
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $nom;
/**
* @ORM\Column(type="string", length=255)
*/
private $description;
/**
* @ORM\ManyToOne(targetEntity=User::class)
* @ORM\JoinColumn(nullable=false)
*/
private $idProprietaire;
/**
* )
* @ORM\Column(type="string", length=45)
*/
private $image;
/**
* @ORM\Column(type="time")
*/
private $arrive;
/**
* @ORM\Column(type="time")
*/
private $depart;
/**
* @ORM\Column(type="string", length=50)
*/
private $adresse;
/**
* @ORM\Column(type="string", length=45)
*/
private $ville;
/**
* @ORM\Column(type="string", length=60)
*/
private $pays;
/**
* @ORM\ManyToMany(targetEntity=Equipement::class)
* @Groups("location:info")
*/
private $equipement;
/**
* @ORM\ManyToOne(targetEntity=Region::class)
* @ORM\JoinColumn(nullable=false)
*/
private $region;
public function __construct()
{
$this->equipement = new ArrayCollection();
$this->pays = "France" ;
$this->calendrierDomaines = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getIdProprietaire(): ?User
{
return $this->idProprietaire;
}
public function setIdProprietaire(?User $idProprietaire): self
{
$this->idProprietaire = $idProprietaire;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
public function getArrive(): ?\DateTimeInterface
{
return $this->arrive;
}
public function setArrive(\DateTimeInterface $arrive): self
{
$this->arrive = $arrive;
return $this;
}
public function getDepart(): ?\DateTimeInterface
{
return $this->depart;
}
public function setDepart(\DateTimeInterface $depart): self
{
$this->depart = $depart;
return $this;
}
public function getAdresse(): ?string
{
return $this->adresse;
}
public function setAdresse(string $adresse): self
{
$this->adresse = $adresse;
return $this;
}
public function getVille(): ?string
{
return $this->ville;
}
public function setVille(string $ville): self
{
$this->ville = $ville;
return $this;
}
public function getPays(): ?string
{
return $this->pays;
}
public function setPays(string $pays): self
{
$this->pays = $pays;
return $this;
}
/**
* @return Collection|Equipement[]
*/
public function getEquipement(): Collection
{
return $this->equipement;
}
public function addEquipement(Equipement $equipement): self
{
if (!$this->equipement->contains($equipement)) {
$this->equipement[] = $equipement;
}
return $this;
}
public function removeEquipement(Equipement $equipement): self
{
$this->equipement->removeElement($equipement);
return $this;
}
public function getRegion(): ?Region
{
return $this->region;
}
public function setRegion(?Region $region): self
{
$this->region = $region;
return $this;
}
/**
* @return Collection|DispoDomaine[]
*/
public function getDispoDomaine(): Collection
{
return $this->calendrierDomaines;
}
public function addDispoDomaine(DispoDomaine $dispo): self
{
if (!$this->calendrierDomaines->contains($dispo)) {
$this->calendrierDomaines[] = $dispo;
$dispo->setIdDomaine($this);
}
return $this;
}
public function removeDispoDomaine(DispoDomaine $dispo): self
{
if ($this->calendrierDomaines->removeElement($dispo)) {
// set the owning side to null (unless already changed)
if ($dispo->getIdDomaine() === $this) {
$dispo->setIdDomaine(null);
}
}
return $this;
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\EquipementRepository;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=EquipementRepository::class)
*/
class Equipement
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=45)
* @Assert\Unique
* @Groups("location:info")
*/
private $nom;
/**
* @ORM\Column(type="string", length=100)
* @Assert\Image(
* maxWidth = 512,
* maxHeight = 512,
* allowLandscape = false,
* allowPortrait = false
* )
*/
private $icon;
public function getId(): ?int
{
return $this->id;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getIcon(): ?string
{
return $this->icon;
}
public function setIcon(string $icon): self
{
$this->icon = $icon;
return $this;
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Location;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Validator\Constraints\DateTime ;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class Location1Type extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('dateDebut', DateType::class, [
'widget' => 'single_text',
// prevents rendering it as type="date", to avoid HTML5 date pickers
'html5' => false,
// adds a class that can be selected in JavaScript
'attr' => ['class' => 'js-datepicker'],
])
->add('dateFin', DateTimeType::class, [
'widget' => 'single_text',
// prevents rendering it as type="date", to avoid HTML5 date pickers
'html5' => false,
// adds a class that can be selected in JavaScript
'attr' => ['class' => 'js-datepicker'],
])
->add('nbpersonnes', ChoiceType::class, [
'choices' => [
'1 personne' => 1,
'2 personnes' => 2,
'3 personnes' => 3,
'4 personnes' => 4
],
])
->add('reserver', SubmitType::class) ;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Location::class,
]);
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\OccupantRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=OccupantRepository::class)
*/
class Occupant
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=200)
*/
private $type;
/**
* @ORM\ManyToOne(targetEntity=Location::class, inversedBy="occupants")
* @ORM\JoinColumn(nullable=false)
*/
private $idLocation;
public function getId(): ?int
{
return $this->id;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(string $type): self
{
$this->type = $type;
return $this;
}
public function getIdLocation(): ?Location
{
return $this->idLocation;
}
public function setIdLocation(?Location $idLocation): self
{
$this->idLocation = $idLocation;
return $this;
}
}
<file_sep><?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Constraints\RangeValidator;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Serializer\Annotation\Groups;
use Doctrine\ORM\Mapping as ORM;
/**
* Location
* @ORM\Table(name="location", indexes={@ORM\Index(name="IDX_5E9E89CB79F37AE5", columns={"id_user_locataire"}), @ORM\Index(name="IDX_5E9E89CBA74ADF1", columns={"id_habitat_id_location"})})
* @ORM\Entity
*/
class Location
{
/**
* @var int
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var \DateTime
* @Groups("location:info")
* @Groups("appitat:info")
* @ORM\Column(name="date_reservation", type="datetime", nullable=false)
*/
private $dateReservation;
/**
* @Assert\GreaterThan("+5 hours")
* @Groups("location:info")
* @Groups("appitat:info")
* @var \DateTime
* @ORM\Column(name="dateDebut", type="datetime", nullable=false)
*/
private $datedebut;
/**
* @Assert\GreaterThan("today")
* @Groups("location:info")
* @var \DateTime
* @ORM\Column(name="dateFin", type="datetime", nullable=false)
*/
private $datefin;
/**
* @var string
* @ORM\Column(name="statut", type="string", length=25, nullable=false)
*/
private $statut;
/**
* @var \User
* @ORM\ManyToOne(targetEntity="User")
* @Groups("location:info")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_user_locataire", referencedColumnName="id")
* })
*/
private $idUserLocataire;
/**
* @var \Habitat
* @ORM\ManyToOne(targetEntity="Habitat")
* @Groups("location:info")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_habitat_id_location", referencedColumnName="id")
* })
*/
private $idHabitatIdLocation;
/**
* @ORM\Column(type="boolean", nullable=true)
*/
private $appreciation;
/**
* @ORM\Column(type="integer")
*/
private $nbPersonnes;
/**
* @ORM\OneToMany(targetEntity=Occupant::class, mappedBy="idLocation", orphanRemoval=true)
*/
private $occupants;
/**
* Constructor
*/
public function __construct()
{
$this->dateReservation = new \DateTime('now');
$this->statut = "En Attente";
$this->occupants = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getDateReservation(): ?\DateTimeInterface
{
return $this->dateReservation;
}
public function setDateReservation(\DateTimeInterface $dateReservation): self
{
$this->dateReservation = $dateReservation;
return $this;
}
public function getDatedebut(): ?\DateTimeInterface
{
return $this->datedebut;
}
public function setDatedebut($datedebut): self
{
$this->datedebut = $datedebut;
return $this;
}
public function getDatefin(): ?\DateTimeInterface
{
return $this->datefin;
}
public function setDatefin($datefin): self
{
$this->datefin = $datefin;
return $this;
}
public function getStatut(): ?string
{
return $this->statut;
}
public function setStatut(string $statut): self
{
$this->statut = $statut;
return $this;
}
public function getIdUserLocataire(): ?User
{
return $this->idUserLocataire;
}
public function setIdUserLocataire(?User $idUserLocataire): self
{
$this->idUserLocataire = $idUserLocataire;
return $this;
}
public function getIdHabitatIdLocation(): ?Habitat
{
return $this->idHabitatIdLocation;
}
public function setIdHabitatIdLocation(?Habitat $idHabitatIdLocation): self
{
$this->idHabitatIdLocation = $idHabitatIdLocation;
return $this;
}
public function getAppreciation(): ?bool
{
return $this->appreciation;
}
public function setAppreciation(?bool $appreciation): self
{
$this->appreciation = $appreciation;
return $this;
}
public function getNbPersonnes(): ?int
{
return $this->nbPersonnes;
}
public function setNbPersonnes(int $nbPersonnes): self
{
$this->nbPersonnes = $nbPersonnes;
return $this;
}
/**
* @return Collection|Occupant[]
*/
public function getOccupants(): Collection
{
return $this->occupants;
}
public function addOccupant(Occupant $occupant): self
{
if (!$this->occupants->contains($occupant)) {
$this->occupants[] = $occupant;
$occupant->setIdLocation($this);
}
return $this;
}
public function removeOccupant(Occupant $occupant): self
{
if ($this->occupants->removeElement($occupant)) {
// set the owning side to null (unless already changed)
if ($occupant->getIdLocation() === $this) {
$occupant->setIdLocation(null);
}
}
return $this;
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Domaine ;
use App\Entity\ActiviteHabitat;
use App\Entity\Activite;
use App\Entity\Habitat;
use App\Entity\Location;
use App\Entity\Commentaire;
use App\Entity\Calendrier;
use App\Form\Location1Type;
use App\Form\ContactOwnerType;
use App\Entity\PriseDeVue ;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Annotation\Route;
class RentController extends AbstractController
{
/**
* @Route("/rent", name="rent")
*/
public function index(): Response
{
return $this->render('rent/index.html.twig', [
'controller_name' => 'RentController',
]);
}
/**
* @Route("/domaines/habitat/{id}", name="habitat_domaines")
*/
public function voirHabitat(Request $request , int $id, MailerInterface $mailer) {
$habitat= $this->getDoctrine()->getRepository(Habitat::class)->find($id);
$domaine= $this->getDoctrine()->getRepository(Domaine::class)->findOneby(
[ 'id' => $habitat->getIdDomaine() ]
);
$commentaire = $this->getDoctrine()->getRepository(Commentaire::class)->findby(
[ 'idHabitatIdCommentaire' => $habitat->getId() ]
);
$photos = $this->getDoctrine()->getRepository(PriseDeVue::class)->findby(
[ 'idHabitatIdPrisedevue' => $habitat->getId() ]
);
$location = new Location();
$user = $this->getUser();
$location->setIdUserLocataire($user);
$location->setIdHabitatIdLocation($habitat);
$activite = $this->getDoctrine()->getRepository(Activite::class)->findby(['idDomaine' => $id]);
$formReservation = $this->createForm(Location1Type::class, $location);
$dispoHabitat = $this->getDoctrine()->getRepository(Calendrier::class)->findBy([ 'idHabitat' => $id , 'etat' => 'D']);
$dateOccupe = $this->getDoctrine()->getRepository(Calendrier::class)->findBy([ 'idHabitat' => $id , 'etat' => 'O']);
$formReservation->handleRequest($request);
if ($formReservation->isSubmitted() && $formReservation->isValid()) {
$depart = $formReservation->get('dateDebut')->getData();
$arrivee = $formReservation->get('dateFin')->getData();
$occupant = $formReservation->get('nbpersonnes')->getData();
$this->get('session')->set('depart', $depart);
$this->get('session')->set('arrivee', $arrivee);
$this->get('session')->set('occupant', $occupant);
return $this->redirectToRoute('reserver' , array('id' => $id ));
// ... further modify the response or return it directly
}
return $this->render('etablissement/habitat.html.twig', [
'controller_name' => 'InternauteController' ,'comments' => $commentaire , 'rent' => $formReservation->createView() ,'activites' => $activite , 'habitats' => $habitat , 'domaines' => $domaine , 'photos' => $photos , 'datesHabitats' => $dispoHabitat , 'dateOccupes' => $dateOccupe ,
]);
}
/**
* @Route("habitatactivite/{id}", name="habitat_activite")
*/
public function showActivite(int $id) {
$activite = $this->getDoctrine()->getRepository(ActiviteHabitat::class)->findOneBy(['typeActivite' => $id ]);
$habitat = $activite->getIdHabitat();
$commentaire = $this->getDoctrine()->getRepository(Commentaire::class)->findby(
[ 'idActiviteHabitat' => $activite->getId() ]
);
$photos = $this->getDoctrine()->getRepository(PriseDeVue::class)->findby(
[ 'idActiviteHabitat' => $activite->getId() ]
);
return $this->render('etablissement/activiteprhabitat.html.twig', [
'controller_name' => 'InternauteController' , 'habitat' => $habitat ,'activite' => $activite , 'photos' => $photos , 'comments' => $commentaire
]);
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20210706183046 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE calendrier (id INT AUTO_INCREMENT NOT NULL, date_dispo DATE NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('ALTER TABLE habitat ADD CONSTRAINT FK_3B37B2E898260155 FOREIGN KEY (region_id) REFERENCES region (id)');
$this->addSql('CREATE INDEX IDX_3B37B2E898260155 ON habitat (region_id)');
$this->addSql('ALTER TABLE user CHANGE url url VARCHAR(65535) NOT NULL');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('DROP TABLE calendrier');
$this->addSql('ALTER TABLE habitat DROP FOREIGN KEY FK_3B37B2E898260155');
$this->addSql('DROP INDEX IDX_3B37B2E898260155 ON habitat');
$this->addSql('ALTER TABLE user CHANGE url url MEDIUMTEXT CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_unicode_ci`');
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class InscriptionUserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('password', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Mot de Passe'),
'second_options' => array('label' => 'Confirmez votre Mot de Passe'),
))
->add('email', EmailType::class , ['label' => 'Adresse E-Mail'])
->add('nom', TextType::class, ['label' => 'Nom'])
->add('prenom', TextType::class,['label' => 'Prénom'])
->add('adresse', TextType::class, ['label' => 'Adresse'])
->add('ville', TextType::class, ['label' => 'Ville'])
->add('cp', TextType::class, ['label' => 'Code Postal'])
->add('dateNaissance', DateType::class, [
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
// prevents rendering it as type="date", to avoid HTML5 date pickers
'html5' => false,
'attr' => ['class' => 'calendate']])
// adds a class that can be selected in JavaScript)
->add('genre', ChoiceType::class, [
'choices' => [
'Homme' => "Homme",
'Femme' => "Femme",
],
'multiple' => false,
'expanded' => true])
->add('telephone')
->add('biographie')
->add("Validez", SubmitType::class, [
'attr' => ['class' => 'btn btn-primary m-5 stripe-button'],
]); ;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
// Configure your form options here
]);
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20201226214934 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE habitat ADD id_domaine_id INT NOT NULL');
$this->addSql('ALTER TABLE habitat ADD CONSTRAINT FK_3B37B2E8E7F87C48 FOREIGN KEY (id_domaine_id) REFERENCES domaine (id)');
$this->addSql('CREATE INDEX IDX_3B37B2E8E7F87C48 ON habitat (id_domaine_id)');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE habitat DROP FOREIGN KEY FK_3B37B2E8E7F87C48');
$this->addSql('DROP INDEX IDX_3B37B2E8E7F87C48 ON habitat');
$this->addSql('ALTER TABLE habitat DROP id_domaine_id');
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20201227090857 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE domaine_equipement (domaine_id INT NOT NULL, equipement_id INT NOT NULL, INDEX IDX_23C6DFED4272FC9F (domaine_id), INDEX IDX_23C6DFED806F0F5C (equipement_id), PRIMARY KEY(domaine_id, equipement_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('CREATE TABLE equipement (id INT AUTO_INCREMENT NOT NULL, nom VARCHAR(45) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('ALTER TABLE domaine_equipement ADD CONSTRAINT FK_23C6DFED4272FC9F FOREIGN KEY (domaine_id) REFERENCES domaine (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE domaine_equipement ADD CONSTRAINT FK_23C6DFED806F0F5C FOREIGN KEY (equipement_id) REFERENCES equipement (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE domaine ADD arrive TIME NOT NULL, ADD depart TIME NOT NULL');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE domaine_equipement DROP FOREIGN KEY FK_23C6DFED806F0F5C');
$this->addSql('DROP TABLE domaine_equipement');
$this->addSql('DROP TABLE equipement');
$this->addSql('ALTER TABLE domaine DROP arrive, DROP depart');
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Propriete;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class Propriete1Type extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nom')
->add('type', ChoiceType::class, [
'choices' => [
'Chaîne de caractère' => 'chaine',
'Entier' => 'entier',
'Décimal' => "decimal",
]]) ->add('obligatoire')
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Propriete::class,
]);
}
}
<file_sep><?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* Commentaire
*
* @ORM\Table(name="commentaire", uniqueConstraints={@ORM\UniqueConstraint(name="UNIQ_67F068BC79F37AE5", columns={"id_user_id"})}, indexes={@ORM\Index(name="IDX_67F068BCA74ADF1", columns={"id_habitat_id_commentaire"})})
* @ORM\Entity
*/
class Commentaire
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @Groups("location:info")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="contenu", type="text", length=0, nullable=false)
* @Groups("location:info")
*/
private $contenu;
/**
* @var \User
*
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_user_id", referencedColumnName="id")
* })
* @Groups("location:info")
*/
private $idUser;
/**
* @var \Habitat
*
* @ORM\ManyToOne(targetEntity="Habitat")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_habitat_id_commentaire", referencedColumnName="id")
* })
*/
private $idHabitatIdCommentaire;
/**
* @ORM\Column(type="string", length=45)
* @Groups("location:info")
*/
private $titre;
/**
* @ORM\ManyToOne(targetEntity=ActiviteHabitat::class)
* @ORM\JoinColumn(nullable=true)
*/
private $idActiviteHabitat;
public function getId(): ?int
{
return $this->id;
}
public function getContenu(): ?string
{
return $this->contenu;
}
public function setContenu(string $contenu): self
{
$this->contenu = $contenu;
return $this;
}
public function getIdUser(): ?User
{
return $this->idUser;
}
public function setIdUser(?User $idUser): self
{
$this->idUser = $idUser;
return $this;
}
public function getIdHabitatIdCommentaire(): ?Habitat
{
return $this->idHabitatIdCommentaire;
}
public function setIdHabitatIdCommentaire(?Habitat $idHabitatIdCommentaire): self
{
$this->idHabitatIdCommentaire = $idHabitatIdCommentaire;
return $this;
}
public function getTitre(): ?string
{
return $this->titre;
}
public function setTitre(string $titre): self
{
$this->titre = $titre;
return $this;
}
public function getIdActiviteHabitat(): ?ActiviteHabitat
{
return $this->idActiviteHabitat;
}
public function setIdActiviteHabitat(?ActiviteHabitat $idActiviteHabitat): self
{
$this->idActiviteHabitat = $idActiviteHabitat;
return $this;
}
}
<file_sep><?php
namespace App\Repository;
use App\Entity\Habitat;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Component\Validator\Constraints\NotEqualTo;
use Symfony\Component\Validator\Constraints\NotEqualToValidator;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method Habitat|null find($id, $lockMode = null, $lockVersion = null)
* @method Habitat|null findOneBy(array $criteria, array $orderBy = null)
* @method Habitat[] findAll()
* @method Habitat[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class HabitatRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Habitat::class);
}
/**
* @return Habitat[] Returns an array of Habitat objects
*/
public function findByProprietaire($user)
{
return $this->createQueryBuilder('h')
->andWhere('h.id_proprietaire !== :user')
->setParameter($user , false)
->orderBy('h.datePublication', 'ASC')
->setMaxResults(20)
->getQuery()
->getResult()
;
}
public function countId()
{
return $this->createQueryBuilder('id')
->select('COUNT(id)')
->getQuery()
->getSingleScalarResult();
}
/*
public function findOneBySomeField($value): ?Habitat
{
return $this->createQueryBuilder('h')
->andWhere('h.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/}<file_sep><?php
namespace App\Controller;
use App\Entity\Habitat;
use App\Form\HabitatType;
use App\Entity\User;
use App\Repository\HabitatRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
*/
/**
* @Route("/habitat")
* @IsGranted("ROLE_USER")
*/
class HabitatController extends AbstractController
{
/**
* @Route("/", name="habitat_index", methods={"GET"})
*/
public function index(): Response
{
$user = $this->getUser();
$habitats = $this->getDoctrine()
->getRepository(Habitat::class)
->findBy(['proprietaire' => $user]);
return $this->render('habitat/index.html.twig', [
'habitats' => $habitats,
]);
}
/**
* @Route("/new", name="habitat_new", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$habitat = new Habitat();
$user = $this->getUser();
$habitat->setProprietaire($user);
$form = $this->createForm(HabitatType::class, $habitat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($habitat);
$entityManager->flush();
return $this->redirectToRoute('habitat_index');
}
return $this->render('habitat/new.html.twig', [
'habitat' => $habitat,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="habitat_show", methods={"GET"})
*/
public function show(Habitat $habitat): Response
{
return $this->render('habitat/show.html.twig', [
'habitat' => $habitat,
]);
}
/**
* @Route("/{id}/edit", name="habitat_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Habitat $habitat): Response
{
$form = $this->createForm(HabitatType::class, $habitat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('habitat_index');
}
return $this->render('habitat/edit.html.twig', [
'habitat' => $habitat,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="habitat_delete", methods={"DELETE"})
*/
public function delete(Request $request, Habitat $habitat): Response
{
if ($this->isCsrfTokenValid('delete'.$habitat->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($habitat);
$entityManager->flush();
}
return $this->redirectToRoute('habitat_index');
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Habitat;
use App\Entity\TypeHabitat;
use App\Entity\Activite;
use App\Entity\Notification ;
use App\Entity\User;
use App\Form\TypeHabitatType;
use App\Form\ProprieteType;
use App\Form\Activite1Type;
use App\Entity\Commentaire;
use App\Entity\ProprieteHabitat ;
use App\Form\Propriete1Type;
use App\Entity\Propriete;
use App\Entity\Location;
use Symfony\Component\HttpFoundation\Request;
use App\Repository\LocationRepository;
use App\Repository\HabitatRepository;
use App\Repository\TypeHabitatRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use App\Repository\ProprieteRepository;
use App\Repository\ActiviteRepository;
use App\Repository\UserRepository;
use App\Repository\PriseDeVueRepository;
use App\Repository\CommentaireRepository;
/**
* @Route("/gerant")
*/
class GerantController extends AbstractController
{
/**
* @Route("/dashboard", name="dashboard")
*/
public function index(): Response
{
$habitat = $this->getDoctrine()->getRepository(Habitat::class)->findAll();
$proprietes = $this->getDoctrine()->getRepository(Propriete::class)->findAll() ;
$comments = $this->getDoctrine()->getRepository(Commentaire::class)->findAll();
$location = $this->getDoctrine()->getRepository(Location::class);
$repoUser = $this->getDoctrine()->getRepository(User::class);
$repoBien = $this->getDoctrine()->getRepository(Habitat::class);
$user = $repoUser->createQueryBuilder('u')
// Filter by some parameter if you want
// ->where('a.published = 1')
->select('count(u.id)')
->getQuery()
->getSingleScalarResult();
$bien = $repoBien->createQueryBuilder('b')
// Filter by some parameter if you want
// ->where('a.published = 1')
->select('count(b.id)')
->getQuery()
->getSingleScalarResult();
$loc = $location->createQueryBuilder('l')
// Filter by some parameter if you want
->select('count(l.id)')
->getQuery()
->getSingleScalarResult();
return $this->render('backoff.html.twig', [
'controller_name' => 'GerantController', 'locations' => $loc , 'habitats' => $habitat , 'proprietes' => $proprietes , 'comments' => $comments , 'users' => $user , 'biens' => $bien
]);
}
/**
* @Route("/habitat", name="habitat")
*/
public function habitat(HabitatRepository $habitatRepository): Response
{
return $this->render('habitat_backoff.html.twig', [
'controller_name' => 'GerantController', 'habitats' => $habitatRepository->findAll()
]);
}
/**
* @Route("/typeActivites", name="typeActivites", methods={"GET"})
*/
public function typesActivites(ActiviteRepository $activiteRepository): Response
{
return $this->render('typeActivite.html.twig', [
'controller_name' => 'GerantController', 'typeActivites' => $activiteRepository->findAll()
]);
}
/**
* @Route("/proprietes", name="proprietes" , methods={"DELETE"})
*/
public function proprietes(ProprieteRepository $proprieteRepository): Response
{
return $this->render('proprietes_backoff.html.twig', [
'controller_name' => 'GerantController', 'proprietes' => $proprieteRepository->findAll()
]);
}
/**
* @Route("/proprietes/add", name="proprietes/add")
*/
public function addProprietes(Request $request): Response
{
$propriete = new Propriete();
$notification = new Notification();
$form = $this->createForm(ProprieteType::class, $propriete);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$form->getData();
$nomParam = $form->get('nom')->getData();
$habitatType = $form->get('idTypeHabitat')->getData()->getNom();
$type = $form->get('type')->getData();
$obligatoire = $form->get('obligatoire')->getData();
if ($obligatoire == true) {
$obligatoire = "oui" ;
}
else {
$obligatoire = "non" ;
}
$entryData = array(
'category' => $habitatType
, 'format' => $type
, 'obligatoire' => $obligatoire
, 'nomParam' => $nomParam
, 'type' => 'ajout'
);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($propriete);
$entityManager->flush();
//Ajout d'une notification
$notification->setTitre("Ajout d'un paramètre");
$parametre = $propriete->getIdTypeHabitat()->getNom() ;
$notification->setContenu("Un nouveau paramètre à été ajouté pour les ".$parametre);
$notification->setIdTypeHabitat($propriete->getIdTypeHabitat());
$entityManager->persist($notification);
$entityManager->flush();
// Notification Stuff
$context = new \ZMQContext();
$socket = $context->getSocket(\ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://localhost:5555");
$socket->send(json_encode($entryData));
return $this->redirectToRoute('proprietes');
}
return $this->render('proprietes_add.html.twig', [
'controller_name' => 'GerantController', 'propriete' => $propriete, 'form' => $form->createView(),
]);
}
/**
* @Route("/{id}/edit", name="proprietes_edit", methods={"GET","POST"})
*/
public function editProperty(Request $request, Propriete $propriete): Response
{
$form = $this->createForm(Propriete1Type::class, $propriete);
$form->handleRequest($request);
$notification = new Notification();
if ($form->isSubmitted() && $form->isValid()) {
$nomParam = $form->get('nom')->getData();
$habitatType = $form->get('idTypeHabitat')->getData()->getNom();
$type = $form->get('type')->getData();
$obligatoire = $form->get('obligatoire')->getData();
if ($obligatoire == true) {
$obligatoire = "oui" ;
}
else {
$obligatoire = "non" ;
}
$entryData = array(
'category' => $habitatType
, 'format' => $type
, 'obligatoire' => $obligatoire
, 'nomParam' => $nomParam
, 'type' => 'modification'
);
$notification->setTitre("Modification d'un paramètre");
$entityManager = $this->getDoctrine()->getManager();
$parametre = $propriete->getIdTypeHabitat()->getNom() ;
$notification->setContenu("Un paramètre à été modifié pour les ".$parametre);
$notification->setIdTypeHabitat($propriete->getIdTypeHabitat());
$entityManager->persist($notification);
$entityManager->flush();
$this->getDoctrine()->getManager()->flush();
// Notification Stuff
$context = new \ZMQContext();
$socket = $context->getSocket(\ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://localhost:5555");
$socket->send(json_encode($entryData));
return $this->redirectToRoute('proprietes');
}
return $this->render('propriete/edit.html.twig', [
'propriete' => $propriete,
'form' => $form->createView(),
]);
}
/**
* @Route("/proprietes/{id}", name="proprietes_delete", methods={"DELETE"})
*/
public function delete(Request $request, Propriete $propriete): Response
{
if ($this->isCsrfTokenValid('delete'.$propriete->getId(), $request->request->get('_token'))) {
$nomParam = $propriete->getNom();
$habitatType = $propriete->getIdTypeHabitat()->getNom();
$type = $propriete->getType();
$obligatoire = $propriete->getObligatoire();
if ($obligatoire == true) {
$obligatoire = "oui" ;
}
else {
$obligatoire = "non" ;
}
$entryData = array(
'category' => $habitatType
, 'format' => $type
, 'obligatoire' => $obligatoire
, 'nomParam' => $nomParam
, 'type' => 'modification'
);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($propriete);
$entityManager->flush();
$notification->setTitre("Supprimer d'un paramètre");
$parametre = $propriete->getIdTypeHabitat()->getNom() ;
$notification->setContenu("Un paramètre à été supprimé pour les ".$parametre);
$notification->setIdTypeHabitat($propriete->getIdTypeHabitat());
$entityManager->persist($notification);
$entityManager->flush();
}
return $this->redirectToRoute('proprietes');
}
/**
* @Route("/comments", name="comments")
*/
public function comments(CommentaireRepository $commentaireRepository): Response
{
return $this->render('comment_backoff.html.twig', [
'controller_name' => 'GerantController', 'comments' => $commentaireRepository->findAll()
]);
}
/**
* @Route("/photos", name="photos")
*/
public function photos(PriseDeVueRepository $prisedevueRepository): Response
{
return $this->render('photos_backoff.html.twig', [
'controller_name' => 'GerantController', 'photos' => $prisedevueRepository->findAll()
]);
}
/**
* @Route("/{id}", name="typesActivites_show", methods={"GET"})
*/
public function show(Activite $activite): Response
{
return $this->render('typeActivite_show.html.twig', [
'activites' => $activite
]);
}
/**
* @Route("/typeActivites/add", name="typeActivites/add" , methods={"GET","POST"})
*/
public function addTypeActivite(Request $request): Response
{
$activite = new Activite();
$form = $this->createForm(Activite1Type::class, $activite);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($activite);
$entityManager->flush();
return $this->redirectToRoute('typeActivites');
}
return $this->render('typeActivite_add.html.twig', [
'controller_name' => 'GerantController', 'activite' => $activite, 'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="typesActivites_edit", methods={"GET","POST"})
*/
public function edit(Activite $activite, Request $request): Response
{
$form = $this->createForm(Activite1Type::class, $activite);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('typesActivites');
}
return $this->render('typesActivites_edit.html.twig', [
'activites' => $activite,
'form' => $form->createView(),
]);
}
/**
* @Route("/typesActivites/{id}", name="typeActivites_delete", methods={"DELETE"})
*/
public function deleteTypeActivite(Activite $activite, Request $request): Response
{
if ($this->isCsrfTokenValid('delete'.$activite->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($activite);
$entityManager->flush();
}
return $this->redirectToRoute('typeActivites');
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Calendrier;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use App\Form\CalendarHabitatType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
class CalendarHabitatType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('dateDispo', DateType::class, [
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
// prevents rendering it as type="date", to avoid HTML5 date pickers
'html5' => false,
// adds a class that can be selected in JavaScript
])
->add('etat' , ChoiceType::class, [
'choices' => [
'Disponible' => "D",
'Occupé' => "O",
]
])
->add('save', SubmitType::class, [
'attr' => ['class' => 'stripe-button'],
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Calendrier::class,
]);
}
}
<file_sep><?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* User
*
* @ORM\Table(name="user", uniqueConstraints={@ORM\UniqueConstraint(name="UNIQ_8D93D649AA08CB10", columns={"login"})})
* @ORM\Entity
* @UniqueEntity(fields={"email"}, message="There is already an account with this email")
*/
class User implements UserInterface
{
/**
* @var int
* @Groups("location:info")
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @Assert\Unique
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
* @Groups("location:info")
* @ORM\Column(name="login", type="string", length=180, nullable=false)
*/
private $login;
/**
* @var json
* @Groups("location:info")
* @ORM\Column(name="roles", type="json", nullable=false)
*/
private $roles;
/**
* @var string
* @Groups("location:info")
* @ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
/**
* @var string
* @Groups("location:info")
* @ORM\Column(name="nom", type="string", length=50, nullable=false)
*/
private $nom;
/**
* @var string
* @Groups("location:info")
* @ORM\Column(name="prenom", type="string", length=50, nullable=false)
*/
private $prenom;
/**
* @var string
* @Groups("location:info")
* @ORM\Column(name="adresse", type="string", length=150, nullable=false)
*/
private $adresse;
/**
* @var string
* @Groups("location:info")
* @ORM\Column(name="ville", type="string", length=40, nullable=false)
*/
private $ville;
/**
* @var int
* @Groups("location:info")
* @ORM\Column(name="cp", type="integer", nullable=false)
*/
private $cp;
/**
* @var string
* @Groups("location:info")
* @ORM\Column(name="url", length=65535)
*/
private $url;
/**
* @Groups("location:info")
* @ORM\Column(name="email", type="string", length=45)
*/
private $email;
/**
* @Groups("location:info")
* @ORM\Column(type="date")
*/
private $dateNaissance;
/**
* @Groups("location:info")
* @ORM\Column(type="string", length=255)
*/
private $genre;
/**
* @Groups("location:info")
* @ORM\Column(type="integer")
*/
private $telephone;
/**
* @Groups("location:info")
* @ORM\Column(type="text", nullable=true)
*/
private $biographie;
/**
* Constructor
*/
public function __construct()
{
$this->url = "images/userDefault.svg";
$this->users = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getLogin(): ?string
{
return $this->login;
}
public function setLogin(string $login): self
{
$this->login = $login;
return $this;
}
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getPrenom(): ?string
{
return $this->prenom;
}
public function setPrenom(string $prenom): self
{
$this->prenom = $prenom;
return $this;
}
public function getAdresse(): ?string
{
return $this->adresse;
}
public function setAdresse(string $adresse): self
{
$this->adresse = $adresse;
return $this;
}
public function getVille(): ?string
{
return $this->ville;
}
public function setVille(string $ville): self
{
$this->ville = $ville;
return $this;
}
public function getCp(): ?int
{
return $this->cp;
}
public function setCp(int $cp): self
{
$this->cp = $cp;
return $this;
}
public function getUrl(): ?string
{
return $this->url;
}
public function setUrl(string $url): self
{
$this->url = $url;
return $this;
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getGenre(): ?string
{
return $this->genre;
}
public function setGenre(string $genre): self
{
$this->genre = $genre;
return $this;
}
public function getUsername()
{
return $this->email;
}
public function getDateNaissance(): ?\DateTimeInterface
{
return $this->dateNaissance;
}
public function setDateNaissance(\DateTimeInterface $dateNaissance): self
{
$this->dateNaissance = $dateNaissance;
return $this;
}
public function getTelephone(): ?int
{
return $this->telephone;
}
public function setTelephone(int $telephone): self
{
$this->telephone = $telephone;
return $this;
}
public function getBiographie(): ?string
{
return $this->biographie;
}
public function setBiographie(?string $biographie): self
{
$this->biographie = $biographie;
return $this;
}
}
<file_sep><?php
namespace App\WebSocket;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use App\WebSocket\Pusher;
use React\EventLoop\Factory ;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class PusherServerCommand extends Command
{
protected static $defaultName = "pusher-server";
protected function execute(InputInterface $input, OutputInterface $output)
{
$loop = \React\EventLoop\Factory::create();
$pusher = new \App\WebSocket\Pusher;
// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new \React\ZMQ\Context($loop);
$pull = $context->getSocket(\ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
$pull->on('message', array($pusher, 'onBlogEntry'));
// Set up our WebSocket server for clients wanting real-time updates
$webSock = new \React\Socket\Server('0.0.0.0:8080', $loop); // Binding to 0.0.0.0 means remotes can connect
$output->writeln("Serveur Démarré");
$webServer = new \Ratchet\Server\IoServer(
new \Ratchet\Http\HttpServer(
new \Ratchet\WebSocket\WsServer(
new \Ratchet\Wamp\WampServer(
$pusher
)
)
),
$webSock
);
$loop->run();
}
}
?><file_sep><?php
namespace App\Controller;
use App\Entity\User;
use App\Form\User1Type;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use App\Form\InscriptionUserType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("users")
*/
class UserController extends AbstractController
{
/**
* @Route("/", name="user", methods={"GET"})
*/
public function index(): Response
{
$users = $this->getDoctrine()
->getRepository(User::class)
->findAll();
return $this->render('user/index.html.twig', [
'users' => $users,
]);
}
/**
* @Route("/new", name="user_new", methods={"GET","POST"})
*/
public function new(Request $request, UserPasswordEncoderInterface $passwordEncoder): Response
{
$user = new User();
$form = $this->createForm(User1Type::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$user->setRoles(['ROLE_ADMIN']) ;
$password = $passwordEncoder->encodePassword($user, $user->getPassword());
$user->setPassword($password);
$entityManager->persist($user);
$entityManager->flush();
return $this->redirectToRoute('user');
}
return $this->render('user/new.html.twig', [
'user' => $user,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="user_show", methods={"GET"})
*/
public function show(User $user): Response
{
return $this->render('user/show.html.twig', [
'user' => $user,
]);
}
/**
* @Route("/{id}/edit", name="user_edit", methods={"GET","POST"})
*/
public function edit(Request $request, User $user, UserPasswordEncoderInterface $encoder): Response
{
$form = $this->createForm(User1Type::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$imageurl = $form->get('url')->getData();
$motdepasse = $form->get('password')->getData();
$fichier = md5(uniqid()) . '.' . $imageurl->guessExtension();
$directory = $this->getParameter('profil_directory');
$extension = $imageurl->guessExtension();
$imageurl->move($directory, $fichier);
$encoded = $encoder->encodePassword($user, $motdepasse);
$user->setUrl($fichier);
$user->setPassword($encoded);
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('user');
}
return $this->render('user/edit.html.twig', [
'user' => $user,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="user_delete", methods={"DELETE"})
*/
public function delete(Request $request, User $user): Response
{
if ($this->isCsrfTokenValid('delete'.$user->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($user);
$entityManager->flush();
}
return $this->redirectToRoute('user_index');
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\ProprieteHabitat;
use App\Entity\User;
use App\Form\ProprieteHabitatType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/proprietehabitat")
*/
class ProprieteHabitatController extends AbstractController
{
/**
* @Route("/", name="propriete_habitat_index", methods={"GET"})
*/
public function index(): Response
{
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$proprieteHabitats = $this->getDoctrine()
->getRepository(ProprieteHabitat::class)
->findAll();
return $this->render('propriete_habitat/index.html.twig', [
'propriete_habitats' => $proprieteHabitats, 'profil' => $profil
]);
}
/**
* @Route("/new", name="propriete_habitat_new", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$proprieteHabitat = new ProprieteHabitat();
$form = $this->createForm(ProprieteHabitatType::class, $proprieteHabitat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($proprieteHabitat);
$entityManager->flush();
return $this->redirectToRoute('propriete_habitat_index');
}
return $this->render('propriete_habitat/new.html.twig', [
'propriete_habitat' => $proprieteHabitat,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="propriete_habitat_show", methods={"GET"})
*/
public function show(ProprieteHabitat $proprieteHabitat): Response
{
return $this->render('propriete_habitat/show.html.twig', [
'propriete_habitat' => $proprieteHabitat,
]);
}
/**
* @Route("/{id}/edit", name="propriete_habitat_edit", methods={"GET","POST"})
*/
public function edit(Request $request, ProprieteHabitat $proprieteHabitat): Response
{
$form = $this->createForm(ProprieteHabitatType::class, $proprieteHabitat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('propriete_habitat_index');
}
return $this->render('propriete_habitat/edit.html.twig', [
'propriete_habitat' => $proprieteHabitat,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="propriete_habitat_delete", methods={"DELETE"})
*/
public function delete(Request $request, ProprieteHabitat $proprieteHabitat): Response
{
if ($this->isCsrfTokenValid('delete'.$proprieteHabitat->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($proprieteHabitat);
$entityManager->flush();
}
return $this->redirectToRoute('propriete_habitat_index');
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\PriseDeVue;
use App\Form\PriseDeVueType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Repository\PriseDeVueRepository;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/prisedevue")
*/
class PriseDeVueController extends AbstractController
{
/**
* @Route("/", name="prisedevue_index", methods={"GET"})
*/
public function index(PriseDeVueRepository $PriseDeVueRepository): Response
{
return $this->render('prise_de_vue/index.html.twig', [
'prise_de_vues' => $PriseDeVueRepository->findAll(),
]);
}
/**
* @Route("/{id}", name="prisedevue_show", methods={"GET"})
*/
public function show(PrisedeVue $prisedevue): Response
{
return $this->render('prise_de_vue/show.html.twig', [
'prise_de_vue' => $prisedevue,
]);
}
/**
* @Route("/newPhoto/{idHabitat}", name="prisedevue_new", methods={"GET","POST"})
*/
public function new(Request $request, Habitat $habitat): Response
{
$priseDeVue = new PriseDeVue();
$form = $this->createForm(PriseDeVueType::class, $priseDeVue);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($priseDeVue);
$entityManager->flush();
return $this->redirectToRoute('prise_de_vue_index');
}
return $this->render('prise_de_vue/new.html.twig', [
'prise_de_vue' => $priseDeVue,
'form' => $form->createView(),
]);
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use App\Entity\Habitat ;
use App\Form\ContactOwnerType;
use App\Entity\PriseDeVue ;
use Symfony\Component\Routing\Annotation\Route;
class ContactController extends AbstractController
{
/**
* @Route("/contact", name="contact")
*/
public function index(Request $request, MailerInterface $mailer): Response
{
$user = $this->getUser();
$contact = $this->createForm(ContactOwnerType::class);
$contact->handleRequest($request);
if ($contact->isSubmitted() && $contact->isValid()) {
$expediteur = $contact->get('email')->getData();
$objet = $contact->get('objet')->getData();
$contenu = $contact->get('contenu')->getData();
$destinataire = $user->getEmail();
$email = (new Email())
->from($expediteur)
->to('<EMAIL>')
->subject($objet)
->text($contenu);
$mailer->send($email);
return $this->redirectToRoute('home');
}
return $this->render('contact/index.html.twig', [
'controller_name' => 'ContactController', 'contact' => $contact->createView()
]);
}
/**
* @Route("/contact_owner/{id}", name="contact_owner")
*/
public function sendEmail(Habitat $habitats, MailerInterface $mailer)
{
$habitat = new Habitat();
$user = $this->getUser();
$form = $this->createForm(ContactType::class, $habitat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$envoyeur = $habitat->getIdProprietaire()->getEmail();
$destinataire = $user->getEmail();
$email = (new Email())
->from($envoyeur)
->to($destinataire)
//->cc('<EMAIL>')
//->bcc('<EMAIL>')
//->replyTo('<EMAIL>')
//->priority(Email::PRIORITY_HIGH)
->subject($data['sujet'])
->text($data['contenu']);
$mailer->send($email);
return $this->redirectToRoute('listHabitat');
}
return $this->render('contact/index.html.twig', [
'habitat' => $habitat,
'form' => $form->createView(),
]);
// ...
}
}<file_sep><?php
namespace App\Repository;
use App\Entity\DispoDomaine;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method DispoDomaine|null find($id, $lockMode = null, $lockVersion = null)
* @method DispoDomaine|null findOneBy(array $criteria, array $orderBy = null)
* @method DispoDomaine[] findAll()
* @method DispoDomaine[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class DispoDomaineRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, DispoDomaine::class);
}
// /**
// * @return DispoDomaine[] Returns an array of DispoDomaine objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('d')
->andWhere('d.exampleField = :val')
->setParameter('val', $value)
->orderBy('d.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?DispoDomaine
{
return $this->createQueryBuilder('d')
->andWhere('d.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Form\WebSocketTestType;
use Symfony\Component\HttpFoundation\Request;
class WebSocketController extends AbstractController
{
/**
* @Route("/websocket", name="web_socket")
*/
public function index(): Response
{
$form = $this->createForm(WebSocketTestType::class);
$request = Request::createFromGlobals();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entryData = $form->getData();
$context = new \ZMQContext();
$socket = $context->getSocket(\ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://localhost:5555");
$socket->send(json_encode($entryData));
}
// This is our new stuff
return $this->render('web_socket/index.html.twig', [
'controller_name' => 'WebSocketController',
'form' => $form->createView(),
]);
}
/**
* @Route("/testwb", name="web_socket_test")
*/
public function blankTest(): Response
{
return $this->render('web_socket/blankp.html.twig', [
'controller_name' => 'WebSocketController',
]);
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Commentaire;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class CommentaireType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('titre' , TextType::class)
->add('contenu' , TextareaType::class , [
'row_attr' => ['class' => 'commentBox']
])
->add('rechercher' , SubmitType::class, [
'attr' => ['class' => 'btn-edit-profile '],
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Commentaire::class,
]);
}
}
<file_sep><?php
namespace App\Entity;
use App\Repository\RegionRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass=RegionRepository::class)
*/
class Region
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @Assert\Unique
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank
*/
private $nom;
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @Assert\Image(
* minWidth = 1300,
* maxWidth = 1900,
* minHeight = 900,
* maxHeight = 1400,
* allowLandscape = false,
* allowPortrait = false
* )
*/
private $image;
public function getId(): ?int
{
return $this->id;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(?string $image): self
{
$this->image = $image;
return $this;
}
}
<file_sep><?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Serializer\Annotation\Groups;
use Doctrine\ORM\Mapping as ORM;
/**
* Habitat
*
* @ORM\Table(name="habitat", indexes={@ORM\Index(name="IDX_3B37B2E85BA3388B", columns={"id_type_habitat_id"})})
* @ORM\Entity
*/
class Habitat
{
/**
* @var int
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @Groups("location:info")
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
* @Groups("location:info")
* @ORM\Column(name="nom", type="string", length=30, nullable=false)
*/
private $nom;
/**
* @var string
* @Groups("location:info")
* @ORM\Column(name="nb_couchages", type="string", length=25, nullable=false)
*/
private $nbCouchages;
/**
* @var int
* @Groups("location:info")
* @ORM\Column(name="capacite", type="integer", nullable=false)
*/
private $capacite;
/**
* @var float
* @Groups("location:info")
* @ORM\Column(name="prix", type="float", precision=10, scale=0, nullable=false)
*/
private $prix;
/**
* @var string
* @Groups("location:info")
* @ORM\Column(name="pays", type="string", length=30, nullable=false)
*/
private $pays;
/**
* @var string
* @ORM\Column(name="ville", type="string", length=40, nullable=false)
* @Groups("location:info")
*/
private $ville;
/**
* @var string
* @ORM\Column(name="description", type="text", length=0, nullable=false)
* @Groups("location:info")
*/
private $description;
/**
* @var \DateTime
* @ORM\Column(name="date_publication", type="date", nullable=false)
* @Groups("location:info")
*/
private $datePublication;
/**
* @var string
* @Groups("location:info")
* @ORM\Column(name="url", type="text", length=65535, nullable=false)
*/
private $url;
/**
* @var \TypeHabitat
*
* @ORM\ManyToOne(targetEntity="TypeHabitat")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_type_habitat_id", referencedColumnName="id")
* })
* @Groups("location:info")
*/
private $idTypeHabitat;
/**
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\ManyToMany(targetEntity="ActiviteHabitat", mappedBy="habitat")
*/
private $activiteHabitat;
/**
* @ORM\ManyToMany(targetEntity=Notification::class, mappedBy="idHabitat")
*/
private $notification;
/**
* @ORM\ManyToOne(targetEntity=Domaine::class)
* @ORM\JoinColumn(nullable=false)
* @Groups("location:info")
*/
private $idDomaine;
/**
* @ORM\ManyToMany(targetEntity=Propriete::class)
*/
private $propriete;
/**
* @ORM\ManyToOne(targetEntity=Region::class)
* @Groups("location:info")
*/
private $region;
/**
* Constructor
*/
public function __construct()
{
$this->activiteHabitat = new \Doctrine\Common\Collections\ArrayCollection();
$this->notification = new ArrayCollection();
$this->datePublication = new \DateTime('now');
$this->url = "images/defaultHabitat.svg";
$this->propriete = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getNbCouchages(): ?string
{
return $this->nbCouchages;
}
public function setNbCouchages(string $nbCouchages): self
{
$this->nbCouchages = $nbCouchages;
return $this;
}
public function getCapacite(): ?int
{
return $this->capacite;
}
public function setCapacite(int $capacite): self
{
$this->capacite = $capacite;
return $this;
}
public function getPrix(): ?float
{
return $this->prix;
}
public function setPrix(float $prix): self
{
$this->prix = $prix;
return $this;
}
public function getPays(): ?string
{
return $this->pays;
}
public function setPays(string $pays): self
{
$this->pays = $pays;
return $this;
}
public function getVille(): ?string
{
return $this->ville;
}
public function setVille(string $ville): self
{
$this->ville = $ville;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getDatePublication(): ?\DateTimeInterface
{
return $this->datePublication;
}
public function setDatePublication(\DateTimeInterface $datePublication): self
{
$this->datePublication = $datePublication;
return $this;
}
public function getUrl(): ?string
{
return $this->url;
}
public function setUrl(string $url): self
{
$this->url = $url;
return $this;
}
public function getIdTypeHabitat(): ?TypeHabitat
{
return $this->idTypeHabitat;
}
public function setIdTypeHabitat(?TypeHabitat $idTypeHabitat): self
{
$this->idTypeHabitat = $idTypeHabitat;
return $this;
}
/**
* @return Collection|ActiviteHabitat[]
*/
public function getActiviteHabitat(): Collection
{
return $this->activiteHabitat;
}
public function addActiviteHabitat(ActiviteHabitat $activiteHabitat): self
{
if (!$this->activiteHabitat->contains($activiteHabitat)) {
$this->activiteHabitat[] = $activiteHabitat;
$activiteHabitat->addHabitat($this);
}
return $this;
}
public function removeActiviteHabitat(ActiviteHabitat $activiteHabitat): self
{
if ($this->activiteHabitat->removeElement($activiteHabitat)) {
$activiteHabitat->removeHabitat($this);
}
return $this;
}
/**
* @return Collection|Notification[]
*/
public function getNotification(): Collection
{
return $this->notification;
}
public function addNotification(Notification $notification): self
{
if (!$this->notification->contains($notification)) {
$this->notification[] = $notification;
$notification->addIdHabitat($this);
}
return $this;
}
public function removeNotification(Notification $notification): self
{
if ($this->notification->removeElement($notification)) {
$notification->removeIdHabitat($this);
}
return $this;
}
public function getIdDomaine(): ?Domaine
{
return $this->idDomaine;
}
public function setIdDomaine(?Domaine $idDomaine): self
{
$this->idDomaine = $idDomaine;
return $this;
}
/**
* @return Collection|Propriete[]
*/
public function getPropriete(): Collection
{
return $this->propriete;
}
public function addPropriete(Propriete $propriete): self
{
if (!$this->propriete->contains($propriete)) {
$this->propriete[] = $propriete;
}
return $this;
}
public function removePropriete(Propriete $propriete): self
{
$this->propriete->removeElement($propriete);
return $this;
}
public function getRegion(): ?Region
{
return $this->region;
}
public function setRegion(?Region $region): self
{
$this->region = $region;
return $this;
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Form\NewsletterType;
use App\Entity\Newsletter ;
class ContenuController extends AbstractController
{
/**
* @Route("/contenu", name="contenu")
*/
public function index(): Response
{
return $this->render('contenu/index.html.twig', [
'controller_name' => 'ContenuController',
]);
}
/**
* @Route("/questions", name="questions")
*/
public function showFaq() {
return $this->render('contenu/faq.html.twig', [
'controller_name' => 'ContenuController',
]);
}
/**
* @Route("/searchfaq", name="searchfaq")
*/
public function showFaqSearch() {
return $this->render('contenu/faq/search_hab.html.twig', [
'controller_name' => 'ContenuController',
]);
}
/**
* @Route("/bookingfaq", name="bookingfaq")
*/
public function showFaqBooking() {
return $this->render('contenu/faq./reservation_hab.html.twig', [
'controller_name' => 'ContenuController',
]);
}
/**
* @Route("/calendarfaq", name="calendarfaq")
*/
public function showFaqCalendar() {
return $this->render('contenu/faq/dispo_hab.html.twig', [
'controller_name' => 'ContenuController',
]);
}
/**
* @Route("/validerfaq", name="validerfaq")
*/
public function showFaqValider() {
return $this->render('contenu/faq/valider_res.html.twig', [
'controller_name' => 'ContenuController',
]);
}
/**
* @Route("/gererfaq", name="gererfaq")
*/
public function showFaqGerer() {
return $this->render('contenu/faq/gerer_hab.html.twig', [
'controller_name' => 'ContenuController',
]);
}
/**
* @Route("/paymentfaq", name="paymentfaq")
*/
public function showFaqPayment() {
return $this->render('contenu/faq/infos_payment.html.twig', [
'controller_name' => 'ContenuController',
]);
}
/**
* @Route("/aboutsus", name="about_us")
*/
public function showAbout() {
return $this->render('contenu/faq.html.twig', [
'controller_name' => 'ContenuController',
]);
}
/**
* @Route("/mentions-legales", name="mentions_legales")
*/
public function showMentions() {
return $this->render('contenu/mentions.html.twig', [
'controller_name' => 'ContenuController',
]);
}
/**
* @Route("/newsletter", name="newsletter")
*/
public function newsletter(Request $request) {
$newsletter = new Newsletter();
$form = $this->createForm(NewsletterType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$newsletter = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($newsletter);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('contenu/newsletter.html.twig', [
'controller_name' => 'ContenuController', 'form' => $form->createView()
]);
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\Commentaire;
use App\Repository\CommentaireRepository;
use App\Form\Commentaire1Type;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/commentaire")
*/
class CommentaireController extends AbstractController
{
/**
* @Route("/newComment/{idReservation}", name="commentaire_new", methods={"GET","POST"})
*/
public function new(Reservation $reservation): Response
{
$commentaire = new Commentaire();
$form = $this->createForm(Commentaire1Type::class, $commentaire);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($commentaire);
$entityManager->flush();
$this->addFlash('success', 'Votre commentaire a bien été posté !');
return $this->redirectToRoute('internaute');
}
return $this->render('commentaire/new.html.twig', [
'commentaire' => $commentaire,
'form' => $form->createView(),
]);
}
/**
* @Route("/newComment/{idHabitat}", name="commentaire_new", methods={"GET","POST"})
*/
public function newCommentActivites(ActiviteHabitat $activiteHabitat): Response
{
$commentaire = new Commentaire();
$form = $this->createForm(Commentaire1Type::class, $commentaire);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($commentaire);
$entityManager->flush();
return $this->redirectToRoute('commentaire_index');
}
return $this->render('commentaire/newActiviteComment.html.twig', [
'commentaire' => $commentaire,
'form' => $form->createView(),
]);
}
/**
* @Route("/", name="comment_index", methods={"GET"})
*/
public function index(CommentaireRepository $CommentaireRepository): Response
{
return $this->render('commentaire/index.html.twig', [
'commentaires' => $CommentaireRepository->findAll(),
]);
}
/**
* @Route("/{id}", name="comment_show", methods={"GET"})
*/
public function show(Commentaire $comment): Response
{
return $this->render('commentaire/show.html.twig', [
'commentaires' => $comment,
]);
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class User1Type extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('login', TextType::class , ['label' => "Nom d'utilisateur"])
->add('password', PasswordType::class , ['label' => 'Mot de Passe']
)
->add('email', EmailType::class , ['label' => 'Adresse E-Mail'])
->add('nom', TextType::class, ['label' => 'Nom'])
->add('prenom', TextType::class,['label' => 'Prénom'])
->add('adresse', TextType::class, ['label' => 'Adresse'])
->add('ville', TextType::class, ['label' => 'Ville'])
->add('cp', TextType::class, ['label' => 'Code Postal'])
->add('url', FileType::class , array('data_class' => null))
->add('dateNaissance')
->add('genre')
->add('telephone')
->add('biographie')
->add('save', SubmitType::class, [
'attr' => ['class' => 'btn-edit-profile'],
]); ;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}
}
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request ;
use App\Form\DomaineType;
use App\Entity\User;
use App\Entity\Region ;
use App\Entity\ActiviteHabitat;
use App\Entity\Habitat;
use App\Entity\Location ;
use App\Entity\Activite;
use App\Entity\ProprieteHabitat;
use App\Entity\Calendrier;
use App\Entity\DispoDomaine;
use App\Form\DispoDomaineType;
use App\Form\DispoLogementType;
use App\Form\CalendarHabitatType;
use App\Form\DomaineCalendrierType;
use Doctrine\Common\Collections\ArrayCollection;
use App\Form\User1Type;
use App\Form\ActiviteHabitatType;
use App\Form\ActiviteType;
use App\Form\HabitatType;
use App\Form\ProprieteHabitatType;
use App\Entity\PriseDeVue;
use App\Entity\Propriete;
use App\Entity\Commentaire;
use App\Form\PriseDeVueType;
use App\Form\CommentaireType;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use App\Entity\Domaine ;
class ProfileController extends AbstractController
{
/**
* @Route("/profile", name="profile")
*/
public function index(): Response
{
return $this->render('profile/index.html.twig', [
'controller_name' => 'ProfileController',
]);
}
/**
* @Route("internaute/meshabitats/", name="internaute_habitats")
*/
public function showHabitats() {
$user = 4 ;
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$domaine = $this->getDoctrine()->getRepository(Domaine::class)->findBy([ 'idProprietaire' => $user]);
$habitat = $this->getDoctrine()->getRepository(Habitat::class)->findBy([ 'idDomaine' => $domaine]);
return $this->render('userinterface/meshabitats.html.twig', [
'controller_name' => 'ProfileController', 'profil' => $profil , 'habitats' => $habitat
]);
}
/**
* @Route("internaute/{id}/meshabitats/new", name="internaute_habitats_new")
*/
public function addHabitats(Request $request) {
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$habitat = new Habitat();
$repository = $this->getDoctrine()->getRepository(Domaine::class);
$domaine = $repository->findOneBy([ 'idProprietaire' => $user]);
$form = $this->createForm(HabitatType::class, $habitat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$imageurl = $form->get('url')->getData();
$fichier = md5(uniqid()) . '.' . $imageurl->guessExtension();
$directory = $this->getParameter('habitat_directory');
$extension = $imageurl->guessExtension();
$imageurl->move($directory, $fichier);
$habitat->setUrl($fichier);
$habitat->setPays('France');
$habitat->setIdDomaine($domaine);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($habitat);
$entityManager->flush();
return $this->redirectToRoute('internaute_habitats_details', array( 'id' => $habitat->getId()));
}
return $this->render('userinterface/addhabitat.html.twig', [
'controller_name' => 'ProfileController', 'profil' => $profil , 'habitat' => $habitat , 'form' => $form->createView(),
]);
}
/**
* @Route("internaute/meshabitats/{id}", name="internaute_habitats_details")
*/
public function detailsHabitats(int $id) {
$user = 4 ;
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$habitat = $this->getDoctrine()->getRepository(Habitat::class)->find($id);
$repository = $this->getDoctrine()->getRepository(Domaine::class);
$domaine = $repository->findOneBy([ 'idProprietaire' => $user]);
$type = $habitat->getIdTypeHabitat();
$propriete = $this->getDoctrine()
->getRepository(Propriete::class)
->findby(['idTypeHabitat' => $type]);
$proprieteHabitats = $this->getDoctrine()
->getRepository(ProprieteHabitat::class)
->findby(['IdHabitatPropriete' => $id]);
$activite = $this->getDoctrine()->getRepository(Activite::class)->findBy([ 'idDomaine' => $domaine ]);
$activiteHabitat = $this->getDoctrine()->getRepository(ActiviteHabitat::class)->findby(
['idHabitat' => $id],
['typeActivite' => 'ASC']
);
return $this->render('userinterface/meshabitatsdetails.html.twig', [
'controller_name' => 'ProfileController', 'activites' => $activite ,'proprietes' => $propriete ,'profil' => $profil , 'proprieteHabitats' => $proprieteHabitats , 'habitat' => $habitat , 'activiteHabitats' => $activiteHabitat
]);
}
/**
* @Route("internaute/meshabitats/{id}/calendar", name="internaute_habitats_calendar")
*/
public function gererCalenderier(int $id) {
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$domaine = $this->getDoctrine()->getRepository(Domaine::class)->findOneBy([ 'idProprietaire' => $user]);
$dispoDomaine = $this->getDoctrine()->getRepository(DispoDomaine::class)->findBy([ 'idDomaine' => $domaine]);
$habitat = $this->getDoctrine()->getRepository(Habitat::class)->find($id);
$dispoHabitat = $this->getDoctrine()->getRepository(Calendrier::class)->findBy([ 'idHabitat' => $id]);
if (empty($dispoHabitat)) {
for ($i=0; $i <= count($dispoDomaine) ; $i++) {
$dateHabitat = new Calendrier();
$dateHabitat->setDateDispo( $dispoDomaine[$i]->getDateDispo());
$dateHabitat->setEtat("D");
$dateHabitat->setIdHabitat($habitat);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($dateHabitat);
$entityManager->flush();
}
}
$dateUpdate = $this->getDoctrine()->getRepository(Calendrier::class)->findBy([ 'idHabitat' => $id ]) ;
$originalDates = new ArrayCollection();
for ($i=0; $i < count($dispoDomaine) ; $i++) {
$date = $dispoDomaine[$i];
$originalDates->add($date);
}
$form = $this->createForm(DispoLogementType::class);
$request = Request::createFromGlobals();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$taille = count($form->get('dateDispo'));
for ($i=0; $i < $taille ; $i++) {
$dateUpdate[$i]->setEtat($form->get('dateDispo')->getData()[$i]->getEtat());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();
}
return $this->redirectToRoute('internaute_habitats_calendar', array( 'id' => $habitat->getId() ));
}
return $this->render('userinterface/calendarhabitat.html.twig', [
'controller_name' => 'ProfileController',
'form' => $form->createView(),
'dateDomaines' => $originalDates,
]);
}
/**
* @Route("internaute/meshabitats/{id}/edit", name="internaute_habitats_edit")
*/
public function editHabitats(int $id, Request $request) {
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$habitat = $this->getDoctrine()->getRepository(Habitat::class)->find($id);
$form = $this->createForm(HabitatType::class, $habitat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$imageurl = $form->get('url')->getData();
$fichier = md5(uniqid()) . '.' . $imageurl->guessExtension();
$directory = $this->getParameter('habitat_directory');
$extension = $imageurl->guessExtension();
$imageurl->move($directory, $fichier);
$habitat->setUrl($fichier);
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('internaute_habitats_details', array( 'id' => $habitat->getId()));
}
return $this->render('userinterface/meshabitatsedit.html.twig', [
'controller_name' => 'ProfileController', 'profil' => $profil , 'habitat' => $habitat , 'form' => $form->createView(),
]);
}
/**
* @Route("internaute/{idHabitat}/activite/{id}/edit", name="internaute_activite_edit")
*/
public function editActivite(int $id, Request $request, int $idHabitat) {
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$habitat = $this->getDoctrine()->getRepository(Habitat::class)->find($idHabitat);
$activite = $this->getDoctrine()->getRepository(Activite::class)->find($id);
$activiteHabitat = new ActiviteHabitat();
$form = $this->createForm(ActiviteHabitatType::class, $activiteHabitat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$activiteHabitat = $form->getData();
$activiteHabitat->setTypeActivite($activite);
$activiteHabitat->setIdHabitat($habitat);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($activiteHabitat);
$entityManager->flush();
return $this->redirectToRoute('internaute_habitats_details', array( 'id' => $habitat->getId()));
}
return $this->render('userinterface/activite_edit.html.twig', [
'controller_name' => 'ProfileController', 'profil' => $profil , 'habitat' => $habitat, 'activite' => $activiteHabitat , 'form' => $form->createView(),
]);
}
/**
* @Route("internaute/mondomaine/", name="internaute_domaine")
*/
public function showDomaine() {
$user = 4 ;
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$repository = $this->getDoctrine()->getRepository(Domaine::class);
$domaine = $repository->findBy([ 'idProprietaire' => $user]);
$activite = $this->getDoctrine()->getRepository(Activite::class)->findBy([ 'idDomaine' => $domaine ]);
return $this->render('userinterface/mondomaine.html.twig', [
'controller_name' => 'ProfileController', 'domaines' => $domaine , 'profil' => $profil , 'activites' => $activite
]);
}
/**
* @Route("internaute/mondomaine/{id}/calendar", name="internaute_domaine_calendar")
*/
public function gererCalenderierDomaine(int $id) {
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$domaine = $this->getDoctrine()->getRepository(Domaine::class)->findOneBy([ 'idProprietaire' => $user]);
$habitats = $this->getDoctrine()->getRepository(Habitat::class)->findBy([ 'idDomaine' => $domaine]);
$dispoDomaine = $this->getDoctrine()->getRepository(DispoDomaine::class)->findBy([ 'idDomaine' => $domaine]);
$originalDates = new Domaine() ;
for ($i=0; $i < count($dispoDomaine) ; $i++) {
$date[$i] = $dispoDomaine[$i];
$originalDates->getDispoDomaine()->add($date[$i]);
}
$form = $this->createForm(DomaineCalendrierType::class, $originalDates);
$request = Request::createFromGlobals();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$taille = count($form->get('dispoDomaine'));
// Ajout des Dates
for ($i=0; $i < $taille ; $i++) {
$dateDispo = $form->get('dispoDomaine')->getData()[$i] ;
$dateDispo->setIdDomaine($domaine) ;
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($dateDispo);
$entityManager->flush();
}
//Ajout des Dates pour chaque logement
foreach ($habitats as $habitat) {
for ($i=0; $i < $taille ; $i++) {
$dispoHabitat = new Calendrier();
$dispoHabitat->setIdHabitat($habitat);
$dispoHabitat->setDateDispo($form->get('dispoDomaine')->getData()[$i]->getDateDispo());
$dispoHabitat->setEtat("D");
$dispoHabitatBDD = $this->getDoctrine()->getRepository(Calendrier::class)->findOneBy([ 'idHabitat' => $habitat->getId() , 'dateDispo' => $form->get('dispoDomaine')->getData()[$i]->getDateDispo() ]);
if ($dispoHabitatBDD == null) {
$entityManager->persist($dispoHabitat);
$entityManager->flush();
}
}
}
//Suppression des Dates
foreach ($dispoDomaine as $dates) {
if (false === $originalDates->getDispoDomaine()->contains($dates)) {
$entityManager->remove($dates);
$entityManager->flush();
}
}
return $this->redirectToRoute('internaute_domaine_calendar', array( 'id' => $domaine->getId() ));
// $form->getData() holds the submitted values
// but, the original `$task` variable has also been updated
// ... perform some action, such as saving the task to the database
}
return $this->render('userinterface/calendardomaine.html.twig', [
'controller_name' => 'ProfileController',
'form' => $form->createView(),
'dispoDomaine' => $dispoDomaine,
]);
}
/**
* @Route("internaute/mondomaine/new", name="internaute_domaine_new")
*/
public function addDomaine(Request $request) {
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$domaine = new Domaine();
$form = $this->createForm(DomaineType::class, $domaine);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$imageurl = $form->get('image')->getData();
$fichier = md5(uniqid()) . '.' . $imageurl->guessExtension();
$directory = $this->getParameter('domaine_directory');
$extension = $imageurl->guessExtension();
$imageurl->move($directory, $fichier);
$domaine->setImage($fichier);
$entityManager = $this->getDoctrine()->getManager();
$domaine->setIdProprietaire($this->getUser());
$entityManager->persist($domaine);
$entityManager->flush();
return $this->redirectToRoute('internaute_domaine');
}
return $this->render('userinterface/adddomaine.html.twig', [
'controller_name' => 'ProfileController', 'profil' => $profil , 'form' => $form->createView(),
]);
}
/**
* @Route("internaute/mondomaine/{id}/edit", name="internaute_domaine_edit" , methods={"GET","POST"})
*/
public function editDomaine(Request $request, Domaine $domaine) {
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$form = $this->createForm(DomaineType::class, $domaine);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$imageurl = $form->get('image')->getData();
$fichier = md5(uniqid()) . '.' . $imageurl->guessExtension();
$directory = $this->getParameter('domaine_directory');
$extension = $imageurl->guessExtension();
$imageurl->move($directory, $fichier);
$domaine->setImage($fichier);
$domaine->setPays('France');
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('internaute_domaine');
}
return $this->render('userinterface/domainedit.html.twig', [
'domaine' => $domaine,
'form' => $form->createView(),
'profil' => $profil
]);
}
/**
* @Route("internaute/profil/{id}/edit", name="internaute_profil_edit" , methods={"GET","POST"})
*/
public function editProfil(Request $request, User $user, UserPasswordEncoderInterface $encoder) {
$form = $this->createForm(User1Type::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$imageurl = $form->get('url')->getData();
$motdepasse = $form->get('password')->getData();
$fichier = md5(uniqid()) . '.' . $imageurl->guessExtension();
$directory = $this->getParameter('profil_directory');
$extension = $imageurl->guessExtension();
$imageurl->move($directory, $fichier);
$encoded = $encoder->encodePassword($user, $motdepasse);
$user->setUrl($fichier);
$user->setPassword($encoded);
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('internaute');
}
return $this->render('userinterface/editprofile.html.twig', [
'profil' => $user,
'form' => $form->createView(),
]);
}
/**
* @Route("internaute/location", name="internaute_location")
*/
public function showLocation() {
$idUser = 4 ;
$profil = $this->getDoctrine()->getRepository(User::class)->find($idUser);
$repository = $this->getDoctrine()->getRepository(Location::class);
$user = $this->getDoctrine()->getRepository(User::class)->find($idUser);
$historique = $repository->findby(['idUserLocataire' => $user , 'statut' => "En Attente"]);
return $this->render('userinterface/showLocation.html.twig', [
'controller_name' => 'InternauteController', 'locations' => $historique , 'profil' => $profil
]);
}
/**
* @Route("internaute/location/activite/{id}", name="internaute_location_activite")
*/
public function showActivite(int $id, Request $request) {
$activite = $this->getDoctrine()->getRepository(ActiviteHabitat::class)->find($id);
$photos = $this->getDoctrine()->getRepository(PriseDeVue::class)->findby(
[ 'idActiviteHabitat' => $activite->getId() ]
);
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$photo = $this->createForm(PriseDeVueType::class);
$form = $this->createForm(CommentaireType::class);
$commentaire = new Commentaire();
$prisedevue = new PriseDeVue();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$commentaire = $form->getData();
$commentaire->setIdUser($this->getUser());
$commentaire->setIdActiviteHabitat($activite);
// ... do any other work - like sending them an email, etc
// maybe set a "flash" success message for the user
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($commentaire);
$entityManager->flush();
return $this->redirectToRoute('internaute_location_activite', ['id' => $activite->getId() ]);
}
if ($photo->isSubmitted() && $photo->isValid()) {
$prisedevue = $photo->getData();
// ... do any other work - like sending them an email, etc
// maybe set a "flash" success message for the user
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($prisedevue);
$entityManager->flush();
return $this->redirectToRoute('internaute_location_activite', ['id' => $activite->getId() ]);
}
return $this->render('userinterface/activitedetailsuser.html.twig', [
'controller_name' => 'InternauteController' , 'profil' => $profil , 'activite' => $activite , 'form' => $form->createView() , 'photo' => $photo->createView()
]);
}
/**
* @Route("internaute/{id}/propriete", name="internaute_propriete_index", methods={"GET"})
*/
public function showProperty(int $id, Request $request): Response
{
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$habitat = $this->getDoctrine()->getRepository(Habitat::class)->find($id);
$proprieteForm = $this->createForm(ProprieteHabitatType::class);
$type = $habitat->getIdTypeHabitat();
$proprieteForm->handleRequest($request);
$proprieteHabitats = $this->getDoctrine()
->getRepository(Propriete::class)
->findby(['idTypeHabitat' => $type]);
return $this->render('propriete_habitat/index.html.twig', [
'propriete_habitats' => $proprieteHabitats, 'profil' => $profil, 'form' => $proprieteForm->createView(), 'habitat' => $habitat
]);
}
/**
* @Route("internaute/propriete/{idHabitat}/{id}/edit", name="internaute_propriete_edit" , methods={"GET", "POST"})
*/
public function editProperty(int $id, Request $request, int $idHabitat): Response
{
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$proprieteForm = $this->createForm(ProprieteHabitatType::class);
$habitat = $this->getDoctrine()->getRepository(Habitat::class)->find($idHabitat);
$proprieteForm->handleRequest($request);
$proprieteHabitats = $this->getDoctrine()->getRepository(Propriete::class)->findOneby(['id' => $id]);
if ($proprieteForm->isSubmitted() && $proprieteForm->isValid()) {
$data = $proprieteForm->get('valeurPropriete')->getData();
$propriete = new ProprieteHabitat();
$propriete->setIdHabitatPropriete($habitat);
$propriete->setIdPropriete($proprieteHabitats);
$propriete->setValeurPropriete($data);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($propriete);
$entityManager->flush();
return $this->redirectToRoute('internaute_propriete_index');
}
return $this->render('propriete_habitat/edit.html.twig', [
'propriete' => $proprieteHabitats, 'profil' => $profil, 'form' => $proprieteForm->createView(),
]);
}
/**
* @Route("internaute/mondomaine/{id}/activite", name="internaute_domaine_activite")
*/
public function showActivityDomaine(int $id) {
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$repository = $this->getDoctrine()->getRepository(Activite::class);
$repository2 = $this->getDoctrine()->getRepository(Domaine::class);
$domaine = $repository2->findBy([ 'idProprietaire' => $user]);
$activite = $this->getDoctrine()->getRepository(Activite::class)->find($id);
return $this->render('userinterface/activitedomaine/show.html.twig', [
'controller_name' => 'ProfileController', 'activite' => $activite , 'profil' => $profil
]);
}
/**
* @Route("internaute/activite/domaine/new", name="domaine_activite_new")
*/
public function newActivityDomaine(Request $request){
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$domaine = $this->getDoctrine()->getRepository(Domaine::class)->findOneBy([ 'idProprietaire' => $user ]);
$activite = new Activite();
$form = $this->createForm(ActiviteType::class, $activite);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$imageurl = $form->get('image')->getData();
$fichier = md5(uniqid()) . '.' . $imageurl->guessExtension();
$directory = $this->getParameter('activite_directory');
$extension = $imageurl->guessExtension();
$imageurl->move($directory, $fichier);
$activite->setImage($fichier);
$activite->setIdDomaine($domaine);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($activite);
$entityManager->flush();
return $this->redirectToRoute('internaute_domaine');
}
return $this->render('userinterface/activitedomaine/new.html.twig', [
'controller_name' => 'ProfileController' , 'profil' => $profil , 'form' => $form->createView()
]);
}
/**
* @Route("internaute/activite/domaine/{id}/edit", name="domaine_activite_edit")
*/
public function editActivityDomaine(Request $request , Activite $activite) {
$user = $this->getUser()->getId();
$profil = $this->getDoctrine()->getRepository(User::class)->find($user);
$form = $this->createForm(ActiviteType::class, $activite);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$imageurl = $form->get('image')->getData();
$fichier = md5(uniqid()) . '.' . $imageurl->guessExtension();
$directory = $this->getParameter('activite_directory');
$extension = $imageurl->guessExtension();
$imageurl->move($directory, $fichier);
$activite->setImage($fichier);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($activite);
$entityManager->flush();
return $this->redirectToRoute('internaute_activite');
}
return $this->render('userinterface/activitedomaine/edit.html.twig', [
'controller_name' => 'ProfileController', 'activite' => $activite , 'profil' => $profil , 'form' => $form->createView()
]);
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20210619134555 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE newsletter ADD region_id INT NOT NULL, ADD hebergement_id INT NOT NULL, DROP hebergement_prefere, DROP region');
$this->addSql('ALTER TABLE newsletter ADD CONSTRAINT FK_7E8585C898260155 FOREIGN KEY (region_id) REFERENCES region (id)');
$this->addSql('ALTER TABLE newsletter ADD CONSTRAINT FK_7E8585C823BB0F66 FOREIGN KEY (hebergement_id) REFERENCES type_habitat (id)');
$this->addSql('CREATE INDEX IDX_7E8585C898260155 ON newsletter (region_id)');
$this->addSql('CREATE INDEX IDX_7E8585C823BB0F66 ON newsletter (hebergement_id)');
$this->addSql('ALTER TABLE user CHANGE url url VARCHAR(65535) NOT NULL');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE newsletter DROP FOREIGN KEY FK_7E8585C898260155');
$this->addSql('ALTER TABLE newsletter DROP FOREIGN KEY FK_<KEY>');
$this->addSql('DROP INDEX IDX_7E8585C898260155 ON newsletter');
$this->addSql('DROP INDEX IDX_7E8585C823BB0F66 ON newsletter');
$this->addSql('ALTER TABLE newsletter ADD hebergement_prefere VARCHAR(100) CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_unicode_ci`, ADD region VARCHAR(200) CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_unicode_ci`, DROP region_id, DROP hebergement_id');
$this->addSql('ALTER TABLE user CHANGE url url MEDIUMTEXT CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_unicode_ci`');
}
}
<file_sep><?php
namespace Tests\AppBundle\Entity;
use PHPUnit\Framework\TestCase;
class LocationTest extends TestCase
{
public function testStatut()
{
$location = new Location(1, new \DateTime('now'),new \DateTime('now'));
$this->assertSame("Validé", $location->setStatut("Validé"));
}
}<file_sep><?php
namespace App\Controller;
use App\Entity\TypeHabitat;
use App\Form\TypeHabitat1Type;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("gerant/type/habitat")
*/
class TypeHabitatController extends AbstractController
{
/**
* @Route("/", name="type_habitat_index", methods={"GET"})
*/
public function index(): Response
{
$typeHabitats = $this->getDoctrine()
->getRepository(TypeHabitat::class)
->findAll();
return $this->render('type_habitat/index.html.twig', [
'type_habitats' => $typeHabitats,
]);
}
/**
* @Route("/new", name="type_habitat_new", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$typeHabitat = new TypeHabitat();
$form = $this->createForm(TypeHabitat1Type::class, $typeHabitat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($typeHabitat);
$entityManager->flush();
return $this->redirectToRoute('type_habitat_index');
}
return $this->render('type_habitat/new.html.twig', [
'type_habitat' => $typeHabitat,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="type_habitat_show", methods={"GET"})
*/
public function show(TypeHabitat $typeHabitat): Response
{
return $this->render('type_habitat/show.html.twig', [
'type_habitat' => $typeHabitat,
]);
}
/**
* @Route("/{id}/edit", name="type_habitat_edit", methods={"GET","POST"})
*/
public function edit(Request $request, TypeHabitat $typeHabitat): Response
{
$form = $this->createForm(TypeHabitat1Type::class, $typeHabitat);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('type_habitat_index');
}
return $this->render('type_habitat/edit.html.twig', [
'type_habitat' => $typeHabitat,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="type_habitat_delete", methods={"DELETE"})
*/
public function delete(Request $request, TypeHabitat $typeHabitat): Response
{
if ($this->isCsrfTokenValid('delete'.$typeHabitat->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($typeHabitat);
$entityManager->flush();
}
return $this->redirectToRoute('type_habitat_index');
}
}
<file_sep><?php
namespace App\Form;
use App\Entity\Activite;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class ActiviteType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nom', TextType::class)
->add('image', FileType::class, array('data_class' => null))
->add('prix', MoneyType::class)
->add('adresse', TextType::class)
->add('description', TextareaType::class)
->add('ajouter' , SubmitType::class, [
'attr' => ['class' => 'btn-edit-profile '],
])
; ;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Activite::class,
]);
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\Habitat;
use App\Entity\Region;
use App\Entity\Occupant;
use App\Entity\TypeHabitat;
use App\Entity\Coordonnees;
use App\Entity\Commentaire;
use App\Entity\PriseDeVue;
use App\Entity\Location;
use App\Entity\ActiviteHabitat;
use App\Form\CommentaireType;
use App\Form\OccupantType;
use App\Form\CoordonneesType;
use App\Form\Location1Type;
use App\Form\LocationOccupantType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use App\Repository\CommentaireRepository;
use App\Repository\PriseDeVueRepository;
use App\Repository\HabitatRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse ;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Session\Session;
class ProductController extends AbstractController
{
/**
* @Route("/listHabitat", name="listHabitat")
*/
public function liste(HabitatRepository $habitatRepository): Response
{
$user = $this->getUser();
$typehabitats = $this->getDoctrine()->getRepository(TypeHabitat::class)->findAll();
$liste = $this->getDoctrine()->getRepository(Habitat::class)->findAll();
return $this->render('product/listeHabitat.html.twig', [
'controller_name' => 'ProductController',
'habitats' => $liste, 'typehabitats' => $typehabitats
]);
}
/**
* @Route("/listeRecherche/{habitat}/{region}/{capacite}", name="listeRecherche", methods={"POST","GET"})
*/
public function listeRecherche(int $habitat , string $region , int $capacite): Response
{
$regionObj = $this->getDoctrine()->getRepository(Region::class)->findOneBy(['id' => 2 ]);
$liste = $this->getDoctrine()->getRepository(Habitat::class)->findBy(['idTypeHabitat' => $habitat , 'region' => $regionObj->getId() , 'capacite' => $capacite]);
return $this->render('product/listeHabitat.html.twig', [
'controller_name' => 'ProductController',
'habitats' => $liste,
]);
}
/**
* @Route("/failed", name="failed")
*/
public function failed(): Response
{
$this->addFlash(
'warning',
'Your changes were saved!'
);
return $this->render('internaute.html.twig', [
'controller_name' => 'StripeController',
]);
}
/**
* @Route("/success", name="success")
*/
public function success(): Response
{
$this->addFlash(
'success',
'Your changes were saved!'
);
return $this->render('internaute.html.twig', [
'controller_name' => 'StripeController',
]);
}
/**
* @Route("/product/{id}", name="product", methods={"GET","POST"})
*/
public function product(int $id, CommentaireRepository $commentRepository, PriseDeVueRepository $prisedevueRepository, Request $request): Response
{
$habitats = $this->getDoctrine()->getRepository(Habitat::class)->find($id);
$comments = $this->getDoctrine()->getRepository(Commentaire::class)->findBy(
['idHabitatIdCommentaire' => $habitats->getId() ],
['id' => 'DESC']
);
$photo = $this->getDoctrine()->getRepository(PriseDeVue::class)->findAll($id);
$activite = $this->getDoctrine()->getRepository(ActiviteHabitat::class)->findAll($id);
$location = new Location();
$user = $this->getUser();
$location->setIdUserLocataire($user);
$location->setIdHabitatIdLocation($habitats);
$comment = new Commentaire();
$comment->setIdUser($user);
$comment->setIdHabitatIdCommentaire($habitats);
$formComment = $this->createForm(CommentaireType::class, $comment);
$formReservation = $this->createForm(Location1Type::class, $location);
$formComment->handleRequest($request);
if ($formComment->isSubmitted() && $formComment->isValid()) {
$comment = $formComment->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
// ... do any other work - like sending them an email, etc
// maybe set a "flash" success message for the user
return $this->redirectToRoute('product' , array('id' => $id));
}
$formReservation->handleRequest($request);
if ($formReservation->isSubmitted() && $formReservation->isValid()) {
$location = $formReservation->getData();
$comment = $formComment->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($location);
$entityManager->flush();
// sets a HTTP response header
// prints the HTTP headers followed by the content
return $this->redirectToRoute('reserver' , array('id' => $location->getId()));
// ... do any other work - like sending them an email, etc
// maybe set a "flash" success message for the user
}
return $this->render('product/index.html.twig', [
'controller_name' => 'ProductController',
'formComment' => $formComment->createView(),
'formLocation' => $formReservation->createView(),
'habitats' => $habitats,
'comments' => $comments,
'photos' => $photo,
'activites' => $activite
]);
}
/**
* @Route("/reserver/{id}", name="reserver", methods={"POST","GET"})
*/
public function reserver(int $id): Response
{
$location = new Location();
$depart = $this->get('session')->get('depart');
$arrivee = $this->get('session')->get('arrivee');
$nbpersonne = $this->get('session')->get('occupant');
// dummy code - add some example tags to the task
// (otherwise, the template will render an empty list of tags)
// create 20 products! Bam!
for ($i = 0; $i < $nbpersonne; $i++) {
$occupants[$i] = new Occupant() ;
$occupants[$i]->setType('Bébé');
$location->getOccupants()->add($occupants[$i]);
}
$dateDifference = $arrivee->diff($depart);
// end dummy code
$form = $this->createForm(LocationOccupantType::class, $location);
$request = Request::createFromGlobals();
$form->handleRequest($request);
$habitat= $this->getDoctrine()->getRepository(Habitat::class)->findOneBy(['id' => $id ]);
$coordonnees= $this->createForm(CoordonneesType::class);
$occupant= $this->createForm(OccupantType::class);
if ($form->isSubmitted() && $form->isValid()) {
$tabOccupants = $form->get('occupants')->getData();
$nbOccupants = count($tabOccupants);
$prixttc = $habitat->getPrix() * $dateDifference->days ;
$this->get('session')->set('infosOccupants', $tabOccupants);
$this->get('session')->set('nbOccupants', $nbOccupants);
$this->get('session')->set('prixTTC', $prixttc);
return $this->redirectToRoute('coordonnees' , array('id' => $id ));
}
return $this->render('product/reserver.html.twig', [
'controller_name' => 'ProductController',
'habitats' => $habitat,
'form' => $form->createView(),
'depart' => $depart,
'arrivee' => $arrivee,
'occupant' => $occupant->createView(),
'nuits'=> $dateDifference,
]);
}
/**
* @Route("/coordonnees/{id}", name="coordonnees", methods={"POST","GET"})
*/
public function coordonnees(int $id): Response
{
$coordonnees = new Coordonnees();
$form = $this->createForm(CoordonneesType::class, $coordonnees);
$habitat= $this->getDoctrine()->getRepository(Habitat::class)->findOneBy(['id' => $id ]);
$request = Request::createFromGlobals();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$tabOccupants = $form->getData();
$this->get('session')->set('coordonnees', $coordonnees);
return $this->redirectToRoute('payment' , array('id' => $id ));
}
return $this->render('coordonnees.html.twig', [
'controller_name' => 'ProductController',
'habitats' => $habitat,
'form' => $form->createView(),
]);
}
/**
* @Route("/payment/{id}", name="payment", methods={"POST","GET"})
*/
public function payment(int $id): Response {
$habitat= $this->getDoctrine()->getRepository(Habitat::class)->findOneBy(['id' => $id ]);
return $this->render('payments.html.twig', [
'controller_name' => 'ProductController',
'habitats' => $habitat,
]);
}
/**
* @Route("/create-checkout-session", name="checkout")
*/
public function checkout(Request $request): JsonResponse
{
$request->request->all();
\Stripe\Stripe::setApiKey('<KEY>');
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'price_data' => [
'currency' => 'eur',
'unit_amount' => 12000,
'product_data' => [
'name' => 'Mobile Home de',
'images' => ["public/images/userDefault.svg"],
],
],
'quantity' => 1,
]],
'mode' => 'payment',
'success_url' => $this->generateUrl('internaute' , [], UrlGeneratorInterface::ABSOLUTE_URL),
'cancel_url' => $this->generateUrl('internaute' , [], UrlGeneratorInterface::ABSOLUTE_URL),
]);
return $response = new JsonResponse(['id' => $session->id ]);
}
}
| 6cccdbc367d5d31f77e574ed9bdfb492aee47027 | [
"PHP"
] | 74 | PHP | Viqnesh/AHouse | be53113bfce3a9d7c7da7818cc270ffc9b6cc513 | ce061ed141ef3fc7d3c8b1d4ec3dcc689715acc1 | |
refs/heads/master | <repo_name>aswinkumar1999/Huffman-Encoder<file_sep>/Makefile
compileRunAndDelete:
@clear
@g++ -std=c++11 main.cpp huffman.cpp
@./a.out ${input} ${output}
@rm -f ./a.out ./codes.dat
<file_sep>/huffman.h
using namespace std;
typedef struct charWithFreq
{
//data
char ch;
int freq;
//functions
charWithFreq();
} charWithFreq;
typedef struct huffmanTreeNode
{
//data
charWithFreq data;
struct huffmanTreeNode *left, *right;
//functions
huffmanTreeNode(charWithFreq temp);
} huffmanTreeNode;
typedef struct charWithCode
{
//data
char ch;
string code;
//functions
charWithCode(char x = '~', string str = "");
} charWithCode;
//for the priority_queue comparing function.
typedef struct heapCompare
{
//functions
bool operator()(huffmanTreeNode* l, huffmanTreeNode* r);
} heapCompare;
//functions
void formHuffmanTree(vector<charWithFreq> contentDistinct);
bool freqOrder(charWithFreq a, charWithFreq b);
vector<charWithFreq> distinctCharactersAndFrequency(string sortedText);
void printCodes(huffmanTreeNode *root, string str);
string getCode(char x, vector<charWithCode> encode);
<file_sep>/README.md
# Huffman Coding
[](LICENSE)
[](https://github.com/aklsh/huffman-coding)
[](Makefile)
[](https://github.com/aklsh/huffman-coding/archive/master.zip)
This repository supplements my [blog post on huffman encoding](https://aklsh.me/Huffman-Encoding).
## Requirements
[](https://en.wikipedia.org/wiki/C%2B%2B11)
This project is written in C++11. For user comfort, I have also included a makefile that uses g++ as the compiler. Install `g++` if you want to do an automatic compilation and running of the program.
## Install
* Clone this repository with `git clone https://github.com/aklsh/huffman-coding`
* You can also download this repository by clicking on the big green button near the top of this page.

## Usage
I have included a makefile that will automatically do all the compilation and running of the program. You have to only specify the input file and the output file to the program.
```bash
make input="<path of input file>" output="<path of output file>"
```
The files have to be *__TEXT FILES ONLY (.txt)__* .
## Organization of files
`main.cpp` - contains the `main()` for the program.
`huffman.h` - contains declaration of all classes and functions.
`huffman.cpp` - contains definitions for all functions (_including member functions of classes_) declared in `huffman.h`.
`Makefile` - a bash script to automatically compile and run the program.
`sample inputs/` - folder containing a few sample input text files.
## Some example Outputs



## Contributing

Please feel free to submit pull requests to this repository!
## License
[MIT © <NAME>](LICENSE)
<file_sep>/main.cpp
#include <bits/stdc++.h>
#include <chrono>
#include "huffman.h"
using namespace std;
int main(int argc, char *argv[])
{
//timing analysis - Credits: https://www.geeksforgeeks.org/measure-execution-time-with-high-precision-in-c-c/
auto start = chrono::high_resolution_clock::now();
ios_base::sync_with_stdio(false);
//reading from input file
ifstream textFile(argv[1]);
string content((istreambuf_iterator<char>(textFile)), (istreambuf_iterator<char>()));
textFile.close();
//finding out the distinct characters and their frequency of appearance in file
string contentSorted = content;
sort(contentSorted.begin(),contentSorted.end());
vector<charWithFreq> contentDistinct;
contentDistinct = distinctCharactersAndFrequency(contentSorted);
//displaying input file contents
char userResponse;
cout << "Do you want to display the input file contents (y/N)? ";
cin >> userResponse;
if(userResponse == 'y')
{
system("clear");
cout << "Content in file:" << endl;
cout << "-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" << endl;
cout << content << endl;
cout << "-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" << endl;
cout << endl;
cout << endl;
cout << "Press c to continue...";
//pause func
do
{
for(int i = 0; i < 10; i++);
}while(cin.get() != 'c');
}
//debugging statements
/*
cout << "Sorted Content:";
cout << contentSorted;
cout << endl;
cout << "\nDistinct Sorted Content:";
for(int i = 0;i < contentDistinct.size();i++)
cout << contentDistinct[i].ch << contentDistinct[i].freq << " ";
cout << endl;
*/
//forming and displaying the huffman codes
system("clear");
cout << "The huffman codes for the characters in the file are:" << endl;
cout << "----------------------------------------------------" << endl;
formHuffmanTree(contentDistinct);
cout << "----------------------------------------------------" << endl;
//checking codes.dat content
/*
charWithCode crap;
ifstream crapFile("codes.dat", ios::binary);
while(crapFile.read((char*) &crap, sizeof(crap)))
{
if(crap.ch != '\n')
cout << crap.ch << " " << crap.code << endl;
else
cout << "\\n" << " " << crap.code << endl;
}
crapFile.close();
*/
cout << endl;
cout << "The output file has been generated." << endl;
cout << endl;
//reading from codes.dat
vector<charWithCode> encoding;
charWithCode crap2;
ifstream crapFile2("codes.dat", ios::binary);
while(crapFile2.read((char*) &crap2, sizeof(crap2)))
encoding.push_back(crap2);
crapFile2.close();
//writing to compressed file
ofstream encodeFile(argv[2]);
for(int i = 0;i < content.size();i++)
encodeFile << getCode(content[i], encoding);
encodeFile.close();
//timing analysis - Credits: https://www.geeksforgeeks.org/measure-execution-time-with-high-precision-in-c-c/
auto end = chrono::high_resolution_clock::now();
double timeTaken = chrono::duration_cast<chrono::nanoseconds>(end - start).count();
timeTaken *= 1e-9;
cout << "Time taken by program is : " << fixed << timeTaken << setprecision(9);
cout << " sec" << endl;
return 0;
}
<file_sep>/huffman.cpp
#include <bits/stdc++.h>
#include "huffman.h"
using namespace std;
charWithFreq::charWithFreq()
{
ch = '~';
freq = 0;
}
huffmanTreeNode::huffmanTreeNode(charWithFreq temp)
{
left = right = NULL;
this->data.ch = temp.ch;
this->data.freq = temp.freq;
}
charWithCode::charWithCode(char x, string str)
{
this->ch = x;
this->code = str;
}
bool freqOrder(charWithFreq a, charWithFreq b)
{
return (a.freq > b.freq);
}
bool heapCompare::operator()(huffmanTreeNode* l, huffmanTreeNode* r)
{
return (l->data.freq > r->data.freq);
}
vector<charWithFreq> distinctCharactersAndFrequency(string sortedText)
{
//sortedText contains text in sorted manner - for unique() to work
string sortedTextCopy = sortedText;
auto ip = unique(sortedTextCopy.begin(), sortedTextCopy.end());
sortedTextCopy = string(sortedTextCopy.begin(), ip);
vector<charWithFreq> distinct;
charWithFreq temp;
for(int i = 0;i < sortedTextCopy.size();i++)
{
temp.ch = sortedTextCopy[i];
temp.freq = count(sortedText.begin(), sortedText.end(), temp.ch);
distinct.push_back(temp);
}
return distinct;
}
void formHuffmanTree(vector<charWithFreq> contentDistinct)
{
huffmanTreeNode *left, *right, *temp;
priority_queue <huffmanTreeNode*, vector<huffmanTreeNode*>, heapCompare> huffmanHeap;
for(int i = 0;i < contentDistinct.size();++i)
huffmanHeap.push(new huffmanTreeNode(contentDistinct[i]));
while(huffmanHeap.size() != 1)
{
left = huffmanHeap.top();
huffmanHeap.pop();
right = huffmanHeap.top();
huffmanHeap.pop();
charWithFreq idk;
idk.freq = left->data.freq + right->data.freq;
idk.ch = '~';
temp = new huffmanTreeNode(idk);
temp->left = left;
temp->right = right;
huffmanHeap.push(temp);
}
printCodes(huffmanHeap.top(), "");
}
void printCodes(huffmanTreeNode* root, string str)
{
ofstream codeFile("codes.dat", ios::binary | ios::out | ios::app);
if (!root)
return;
if (root->data.ch != '~')
{
if(root->data.ch != '\n')
{
cout << root->data.ch << ": " << str << endl;
charWithCode temp(root->data.ch, str);
codeFile.write((char*) &(temp), sizeof(temp));
}
else
{
cout << "\\n" << ": " << str << endl;
charWithCode temp('\n', str);
codeFile.write((char*) &(temp), sizeof(temp));
}
}
printCodes(root->left, str + "0");
printCodes(root->right, str + "1");
codeFile.close();
}
string getCode(char x, vector<charWithCode> encode)
{
for(int i = 0;i < encode.size();i++)
if(encode[i].ch == x)
return encode[i].code;
return "";
}
| 1ca7fe3ca06a503e1a28287eb3f914a151a02d04 | [
"Markdown",
"Makefile",
"C++"
] | 5 | Makefile | aswinkumar1999/Huffman-Encoder | e35cb04a594977d0bb34a16a1e4b958b333cb706 | 2cda235a596a27489caf0a3624b4c2027ea5a77a | |
refs/heads/master | <repo_name>daciocco/Neo-farma<file_sep>/articulos/logica/jquery/jqueryFooter.js
$("#btPreciosCondiciones").click(function () {
"use strict";
if (confirm('Desea que se creen las condiciones comerciales con los nuevos precios?')) {
$.ajax({
type : 'POST',
url : '/pedidos/articulos/logica/ajax/duplicar.condicion.php',
beforeSend: function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
if (result){
if (result.replace("\n","") === '1'){
$('#box_cargando').css({'display':'none'});
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('Los datos han sido procesados correctamente.');
window.location.reload(true);
} else {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
} else {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Ocurrió un error al registrar los datos. Póngase en contacto con el adminsitrador de la web");
}
},
error : function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html('Error en el proceso.');
}
});
}
});
function dac_mostrarFiltro(tipo, filtro){
"use strict";
$.ajax({
type : 'POST',
cache : false,
url : '/pedidos/articulos/logica/ajax/getFiltroArticulos.php',
data : {
tipo : tipo,
filtro : filtro
},
beforeSend : function () {
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
if (result){
var tabla = result;
document.getElementById('tablaFiltroArticulos').innerHTML = tabla;
$('#box_cargando').css({'display':'none'});
} else {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
},
});
}<file_sep>/pedidos/detalle_pedido.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$nroPedido = empty($_REQUEST['nropedido']) ? 0 : $_REQUEST['nropedido'];
$btnPrint = sprintf( "<a id=\"imprimir\" href=\"imprimir_pedido.php?nropedido=%s\" target=\"_blank\" title=\"Imprimir\" >%s</a>", $nroPedido, "<img class=\"icon-print\" />");
$btnAprobar = sprintf( "<a id=\"aprobar\" title=\"Aprobar Negociación\">%s</a>", "<img class=\"icon-proposal-approved\"/>");
$btnRechazar= sprintf( "<a id=\"rechazar\" title=\"Rechazar Negociación\">%s</a>", "<img class=\"icon-proposal-rejected\"/>"); ?>
<!DOCTYPE html>
<html>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
<script language="JavaScript" src="/pedidos/pedidos/logica/jquery/jquery.aprobar.js" type="text/javascript"></script>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "pedidos";
$_subsection= "mis_pedidos";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav> <!-- fin menu -->
<main class="cuerpo">
<div class="cbte"> <?php
if ($nroPedido) {
//Si el usuario es vendedor o es el usrid de Ernesto
if($_SESSION["_usrrol"] != "V" || $_SESSION["_usrrol"] != "17") {
$usr = NULL;
} else {
$usr = $_SESSION["_usrid"];
}
$detalles = DataManager::getPedidos($usr, NULL, $nroPedido);
if ($detalles) {
$totalFinal = 0;
foreach ($detalles as $k => $detalle) {
if ($k==0){
$empresa = $detalle["pidemp"];
$empresas = DataManager::getEmpresas();
if ($empresas) {
foreach ($empresas as $i => $emp) {
$empresaId = $emp['empid'];
if ($empresa == $empresaId){
$empNombre = $emp['empnombre'];
$empDir = $emp['empdomicilio'];
$empLocalidad = " - ".$emp['emplocalidad'];
$empCP = " - CP".$emp['empcp'];
$empTel = " - Tel: ".$emp['empcp'];
$empCorreo = $emp['empcorreo']." / ";
}
}
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
}
?>
<div class="cbte_header">
<div class="cbte_boxheader">
<?php echo $cabeceraPedido; ?>
</div> <!-- cbte_boxheader -->
<div class="cbte_boxheader">
<h1>PEDIDO WEB</h1> </br>
<?php echo $empDir; ?> <?php echo $empCP; ?> <?php echo $empLocalidad; ?> <?php echo $empTel; ?></br>
<?php echo $empCorreo; ?> www.neo-farma.com.ar</br>
IVA RESPONSABLE INSCRIPTO
</div> <!-- cbte_boxheader -->
</div> <!-- boxtitulo -->
<?php
$fechaPedido = $detalle['pfechapedido'];
$usrId = $detalle['pidusr'];
$usrNombre = DataManager::getUsuario('unombre', $usrId);
$clienteId = $detalle["pidcliente"];
$ctaId = DataManager::getCuenta('ctaid', 'ctaidcuenta', $clienteId, $empresa);
$cliNombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $clienteId, $empresa);
$_domiciliocli = DataManager::getCuenta('ctadireccion', 'ctaidcuenta', $clienteId, $empresa)." ".DataManager::getCuenta('ctadirnro', 'ctaidcuenta', $clienteId, $empresa)." ".DataManager::getCuenta('ctadirpiso', 'ctaidcuenta', $clienteId, $empresa)." ".DataManager::getCuenta('ctadirdpto', 'ctaidcuenta', $clienteId, $empresa);
$_localidadcli = DataManager::getCuenta('ctalocalidad', 'ctaidcuenta', $clienteId, $empresa);
$_codpostalcli = DataManager::getCuenta('ctacp', 'ctaidcuenta', $clienteId, $empresa);
$_condpago = $detalle["pidcondpago"];
$condicionesDePago = DataManager::getCondicionesDePago(0, 0, NULL, $_condpago);
if (count($condicionesDePago)) {
foreach ($condicionesDePago as $k => $condPago) {
$condPagoCodigo = $condPago["IdCondPago"];
$_condnombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condPago['condtipo']);
$_conddias = "(";
$_conddias .= empty($condPago['Dias1CP']) ? '0' : $condPago['Dias1CP'];
$_conddias .= empty($condPago['Dias2CP']) ? '' : ', '.$condPago['Dias2CP'];
$_conddias .= empty($condPago['Dias3CP']) ? '' : ', '.$condPago['Dias3CP'];
$_conddias .= empty($condPago['Dias4CP']) ? '' : ', '.$condPago['Dias4CP'];
$_conddias .= empty($condPago['Dias5CP']) ? '' : ', '.$condPago['Dias5CP'];
$_conddias .= " Días)";
$_conddias .= ($condPago['Porcentaje1CP'] == '0.00') ? '' : ' '.$condPago['Porcentaje1CP'].' %';
}
}
$ordenCompra = ($detalle["pordencompra"] == 0) ? '' : "Orden Compra: ".$detalle["pordencompra"];
$negociacion = $detalle["pnegociacion"];
$aprobado = $detalle["paprobado"];
$observacion = $detalle["pobservacion"];
?>
<div class="cbte_boxcontent">
<div class="cbte_box">
<?php echo $fechaPedido;?>
</div>
<div class="cbte_box">
Nro. Pedido:
<input id="nropedido" name="nropedido" value="<?php echo $nroPedido; ?>" hidden/>
<?php echo str_pad($nroPedido, 9, "0", STR_PAD_LEFT); ?>
</div>
<div class="cbte_box" align="right">
<?php echo $usrNombre;?>
</div>
</div> <!-- cbte_boxcontent -->
<div class="cbte_boxcontent">
<div class="cbte_box">
Cliente: </br>
Dirección: </br>
</div> <!-- cbte_box -->
<div class="cbte_box2">
<?php echo $clienteId." - ".$cliNombre;?></br>
<?php echo $_domiciliocli." - ".$_localidadcli." - ".$_codpostalcli; ?>
</div> <!-- cbte_box2 -->
</div> <!-- cbte_boxcontent -->
<div class="cbte_boxcontent">
<div class="cbte_box2">
Condición de Pago: <?php echo $_condpago." | ".$_condnombre." ".$_conddias;?>
</div>
<div class="cbte_box" align="right">
<?php echo $ordenCompra;?>
</div>
</div> <!-- cbte_boxcontent -->
<div class="cbte_boxcontent2">
<table>
<thead>
<tr align="left">
<th scope="col" width="10%" height="18" align="center">Código</th>
<th scope="col" width="10%" align="center">Cant</th>
<th scope="col" width="30%" align="center">Descripción</th>
<th scope="col" width="10%" align="center">Precio</th>
<th scope="col" width="10%" align="center">Bonif</th>
<th scope="col" width="10%" align="center">Dto1</th>
<th scope="col" width="10%" align="center">Dto2</th>
<th scope="col" width="10%" >Total</th>
</tr>
</thead> <?php
}
$total = 0;
$artId = $detalle['pidart'];
$laboratorio = $detalle['pidlab'];
$unidades = $detalle['pcantidad'];
$descripcion = DataManager::getArticulo('artnombre', $artId, 1, $laboratorio);
$precio = $detalle['pprecio'];
$b1 = ($detalle['pbonif1'] == 0)? '' : $detalle['pbonif1'];
$b2 = ($detalle['pbonif2'] == 0)? '' : $detalle['pbonif2'];
$bonif = ($detalle['pbonif1'] == 0)? '' : $b1." X ".$b2;
$desc1 = ($detalle['pdesc1'] == 0) ? '' : $detalle['pdesc1'];
$desc2 = ($detalle['pdesc2'] == 0) ? '' : $detalle['pdesc2'];
//**************************************//
// Calculo precio final por artículo //
$precio_f = $precio * $unidades;
if ($desc1 != ''){ $precio_f = $precio_f - ($precio_f * ($desc1/100)); }
if ($desc2 != ''){ $precio_f = $precio_f - ($precio_f * ($desc2/100)); }
$total = round($precio_f, 3);
$totalFinal += $total;
//**************************************//
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\" align=\"center\">%s</td><td align=\"center\">%s</td><td>%s</td><td align=\"right\" style=\"padding-right:15px;\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"right\" style=\"padding-right:5px;\">%s</td>", $artId, number_format($unidades,0), $descripcion, number_format(round($precio,2),2), $bonif, number_format(round($desc1,2),2), number_format(round($desc2,2),2), number_format(round($total,2),2));
echo sprintf("</tr>");
} ?>
</table>
</div> <!-- cbte_boxcontent2 -->
<div class="cbte_boxcontent2">
<div class="cbte_box2">
<?php echo $observacion;?>
</div>
<div class="cbte_box" align="right" style="font-size:18px; float: right;">
TOTAL: $ <?php echo number_format(round($totalFinal,2),2); ?>
</div>
</div> <!-- cbte_boxcontent-->
<?php
}
} ?>
<div class="bloque_1" align="center"> <?php
echo $piePedido;
echo $btnPrint;
if($_SESSION["_usrrol"]!="V"){
if($negociacion == 1 && $aprobado == 1){
echo $btnAprobar;
echo $btnRechazar;
}
}
$ruta = $_SERVER['DOCUMENT_ROOT']."/pedidos/cuentas/archivos/".$ctaId."/pedidos/".$nroPedido."/";
$data = dac_listar_directorios($ruta);
if($data){
foreach ($data as $file => $timestamp) {
//saco la extensión del archivo
$extencion = explode(".", $timestamp);
$ext = $extencion[1];
$name = explode("-", $timestamp, 4);
$archivo = trim($name[3]);
?>
<a href="<?php echo "/pedidos/cuentas/archivos/".$ctaId."/pedidos/".$nroPedido."/".$archivo; ?>" title="Orden de Compra" target="_blank"> <?php
if($ext == "pdf"){ ?>
<img id="imagen" class="icon-order-pdf"/>
<?php
} else { ?>
<img id="imagen" class="icon-order-jpg"/>
<?php
} ?>
</a> <?php
}
} ?>
</div>
</div> <!-- cbte -->
</main> <!-- CUERPO -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/noticias/lista.php
<?php
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/noticias/' : $_REQUEST['backURL'];
$_LPP = 20;
$_total = DataManager::getNumeroFilasTotales('TNoticia', 0);
$_paginas = ceil($_total/$_LPP);
$_pag = isset($_REQUEST['pag']) ? min(max(1,$_REQUEST['pag']),$_paginas) : 1;
$_GOFirst = sprintf("<a class=\"icon-go-first\" href=\"%s?pag=%d\"></a>", $backURL, 1);
$_GOPrev = sprintf("<a class=\"icon-go-previous\" href=\"%s?pag=%d\"></a>", $backURL, $_pag-1);
$_GONext = sprintf("<a class=\"icon-go-next\" href=\"%s?pag=%d\"></a>", $backURL, $_pag+1);
$_GOLast = sprintf("<a class=\"icon-go-last\" href=\"%s?pag=%d\"></a>", $backURL, $_paginas);
$btnNuevo = sprintf( "<a href=\"editar.php\" title=\"Nuevo\"><img class=\"icon-new\"/></a>");
?>
<div class="box_body">
<div class="barra">
<div class="bloque_5">
<h1>Noticias</h1>
</div>
<div class="bloque_7">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn" type="text" value="tblNoticias" hidden/>
</div>
<div class="bloque_7">
<?php echo $btnNuevo; ?>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super" >
<table id="tblNoticias">
<thead>
<tr>
<th scope="col" width="20%" height="18">Titular</th>
<th scope="col" width="10%">Fecha Publicación</th>
<th scope="col" width="55%">Descripción</th>
<th scope="colgroup" colspan="3" width="15%" align="center">Acciones</th>
</tr>
</thead>
<?php
$_noticias = DataManager::getNoticias($_pag,$_LPP);
$_max = count($_noticias);
for( $k=0; $k < $_LPP; $k++ ){
if ($k < $_max){
$_noticia = $_noticias[$k];
$fecha = explode(" ", $_noticia["ntfecha"]);
list($ano, $mes, $dia) = explode("-", $fecha[0]);
$_fecha = $dia."-".$mes."-".$ano;
$_titulo = $_noticia["nttitulo"];
$_descripcion = substr($_noticia["ntdescripcion"], 0, 100)."...";
$_status = ($_noticia['ntactiva']) ? "<img class=\"icon-status-active\" title=\"desactivar\"/>" : "<img class=\"icon-status-inactive\" title=\"Activar\"/>";
$_editar = sprintf( "<a href=\"editar.php?idnt=%d&backURL=%s\" title=\"editar noticia\">%s</a>", $_noticia['idnt'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit\" />");
$_borrar = sprintf( "<a href=\"logica/changestatus.php?idnt=%d&backURL=%s&pag=%s\" title=\"borrar noticia\">%s</a>", $_noticia['idnt'], $_SERVER['PHP_SELF'], $_pag, $_status);
$_eliminar = sprintf ("<a href=\"logica/eliminar.noticia.php?idnt=%d&backURL=%s\" title=\"eliminar noticia\" onclick=\"return confirm('¿Está Seguro que desea ELIMINAR LA NOTICIA?')\"> <img class=\"icon-delete\"/></a>", $_noticia['idnt'], $_SERVER['PHP_SELF'], "eliminar");
} else {
$_fecha = " ";
$_titulo = " ";
$_editar = " ";
$_borrar = " ";
$_eliminar = " ";
$_descripcion = " ";
}
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_titulo, $_fecha, $_descripcion, $_editar, $_borrar, $_eliminar);
echo sprintf("</tr>");
} ?>
</table>
</div> <!-- Fin listar -->
<?php
if ( $_paginas > 1 ) {
$_First = ($_pag > 1) ? $_GOFirst : " ";
$_Prev = ($_pag > 1) ? $_GOPrev : " ";
$_Last = ($_pag < $_paginas) ? $_GOLast : " ";
$_Next = ($_pag < $_paginas) ? $_GONext : " ";
echo("<table class=\"paginador\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
echo sprintf("<td height=\"16\">Mostrando página %d de %d</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td>", $_pag, $_paginas, $_First, $_Prev, $_Next, $_Last);
echo("</tr></table>");
} ?>
</div> <!-- Fin datos -->
<file_sep>/relevamiento/relevar/lista.php
<?php
$btAccion = sprintf("<input type=\"submit\" id=\"btsend\" name=\"_accion\" value=\"Guardar\"/>");
?>
<link rel="stylesheet" type="text/css" href="../../js/jquery-ui-1.11.4/jquery-ui.structure.css"/>
<link rel="stylesheet" type="text/css" href="../../js/jquery-ui-1.11.4/jquery-ui.theme.css"/>
<div class="box_body">
<?php
$_origenid = empty($_REQUEST['origenid']) ? 0 : $_REQUEST['origenid'];
$_origen = empty($_REQUEST['origen']) ? '' : $_REQUEST['origen'];
$_nroRel = empty($_REQUEST['nroRel']) ? 0 : $_REQUEST['nroRel'];
$empresa = empty($_REQUEST['empresa']) ? 0 : $_REQUEST['empresa'];
$_procorreo = DataManager::getCuenta('ctacorreo', 'ctaid', $_origenid, $empresa);
$_protelefono = DataManager::getCuenta('ctatelefono', 'ctaid', $_origenid, $empresa);
// ENCUETAS //
$_relevamiento = DataManager::getRelevamiento($_nroRel, 1);
if (count($_relevamiento)) { ?>
<form id="fm_relevar" method="post">
<input type="text" id="origenid" name="origenid" hidden="hidden" value="<?php echo $_origenid; ?>">
<input type="text" id="origen" name="origen" hidden="hidden" value="<?php echo $_origen; ?>">
<input type="text" id="nrorel" name="nrorel" hidden="hidden" value="<?php echo $_nroRel; ?>">
<input type="text" id="telefono" name="telefono" hidden="hidden" value="<?php echo $_protelefono; ?>">
<input type="text" id="email" name="email" hidden="hidden" value="<?php echo $_procorreo; ?>">
<fieldset>
<legend>Relevamiento</legend>
<?php
foreach ($_relevamiento as $k => $_rel) {
$_relid = $_rel["relid"];
$_relpregorden = $_rel["relpregorden"];
$_relpregunta = $_rel["relpregunta"];
$_reltiporesp = $_rel["reltiporesp"];
//Consulto si ya existe el relevamiento hecho para poner las respuestas.
$_respuesta = '';
$_resid = '';
$_respuestas = DataManager::getRespuesta( $_origenid, $_origen, $_relid, 1);
if($_respuestas){
foreach ($_respuestas as $j => $_res) {
$_resid = $_res["resid"];
$_respuesta = $_res["respuesta1"];
}
} ?>
<div class="bloque_1">
<h4> <?php echo ($k+1).") ".$_relpregunta; ?> </h4>
</div>
<input type="text" name="resid<?php echo $k; ?>" id="resid<?php echo $k; ?>" value="<?php echo $_resid; ?>" hidden="hidden">
<?php
switch ($_reltiporesp){
case 'sino': ?>
<div class="bloque_8">
<input type="radio" name="sino<?php echo $k; ?>" value="1" <?php if($_respuesta == 1) { echo "checked='checked'";} ?>>Si
</div>
<div class="bloque_8">
<input type="radio" name="sino<?php echo $k; ?>" value="2" <?php if($_respuesta == 2) { echo "checked='checked'";} ?>>No
</div> <hr><?php
break;
case 'cant': ?>
<div class="bloque_8">
<input type="text" name="cant<?php echo $k; ?>" id="cant<?php echo $k; ?>" maxlength="4" max="1000" min="0" value="<?php echo $_respuesta; ?>">
</div> <?php
break;
case 'abierto': ?>
<div class="bloque_1">
<textarea id="respuesta<?php echo $k; ?>" name="respuesta<?php echo $k; ?>" onKeyUp="javascript:dac_LimitaCaracteres(event, 'respuesta', 200);" onKeyDown="javascript:dac_LimitaCaracteres(event, 'respuesta', 200);" /><?php echo $_respuesta; ?></textarea>
</div> <?php
break;
default: ?>
<div class="bloque_1">
Error en el tipo de respuesta.
</div>
<?php
break;
} ?>
<?php
} ?>
<div id="relevar" class="bloque_4">
<label >Resultado</label>
<select id="resultado_arg" name="resultado_arg">
<option value="0" selected></option>
<option value="1" >Enviar información y volver a llamar</option>
<!--option value="2" >Enviar información inicial</option-->
<option value="3" >No le interesa</option>
<option value="4" >Venta Transfer</option>
<option value="5" >Volver a llamar</option>
<!--option value="6" >Volver a llamar a largo plazo</option-->
</select>
</div>
<div class="bloque_7">
<br>
<?php echo $btAccion; ?>
</div>
<div id="mensajesAlertas" class="bloque_1">
<div id="alertas">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
</div> <!-- Fin mensajesAlertas -->
</fieldset>
</form> <?php
} ?>
<div id="dialogo" style="display:none;"></div>
<div id="reprogramar" style="display:none;"></div>
<div id="enviarmail" style="display:none;"></div>
</div> <!-- Fin datos -->
<hr>
<script type="text/javascript" src="jquery/jquery.enviar.js"></script>
<script type="text/javascript" src="../../js/jquery-ui-1.11.4/jquery-ui.js"></script>
<script>
$(window).resize(function(e){
$("#enviarmail").dialog("close");
$("#enviarmail").dialog("open");
$("#reprogramar").dialog("close");
$("#reprogramar").dialog("open");
$("#dialogo").dialog("close");
$("#dialogo").dialog("open");
});
</script>
<script>
$("#resultado_arg").change(function(){
$("#dialogo").empty();
$("#dialogo").dialog({
modal: true, title: 'Mensaje', zIndex: 100, autoOpen: true,
resizable: false,
width: 380,
height: 200,
});
$("#dialogo").dialog( "option", "title", 'Registro de Acciones');
var origen = $('#origen').val();
var idorigen = $('#origenid').val();
var nroRel = $('#nrorel').val();
var telefono = $('#telefono').val();
var email = $('#email').val();
var resultado = $( "#resultado_arg" ).val();
switch(resultado){
case '0': $("#dialogo").dialog("close"); break;
case '1':
//Enviar información y reprogramar llamada
$( "#dialogo" ).dialog({
buttons: {
Aceptar : function () {
//Enviar Información
$( "#alertas" ).remove();
dac_sendMail(1, email, "Informaci\u00f3n GEZZI");
// REPROGRAMAR LLAMADA
//dac_reprogramar(origen, idorigen, nroRel, 'enviar información', telefono);
$(this).dialog("close");
},
Cerrar : function () {
$(this).dialog("close");
}
},
});
var contenido = '<h3>\u00BFRegistrar la llamada como "Enviar informaci\u00f3n"?</h3>';
$(contenido).appendTo('#dialogo');
break;
case '3':
//No le interesa y ¿desactivar prospecto?
$("#dialogo").dialog("close");
dac_reprogramar(origen, idorigen, nroRel, 'no le interesa', telefono);
/*$( "#dialogo" ).dialog({
buttons: {
Aceptar : function () {
//dac_registrarLlamada(origen, idorigen, nroRel, telefono, 'contesta', 'no le interesa', '');
// REPROGRAMAR LLAMADA
//dac_reprogramar(origen, idorigen, nroRel, 'contesta', telefono);
//dac_registrarLlamada(origen, idorigen, nroRel, telefono2, contesta, 'rellamar', descripcion2);
//parent.window.close();
//$(this).dialog("close");
},
Cerrar : function () {
$(this).dialog("close");
}
},
});
var contenido = '<h3>\u00BFRegistrar la llamada como "No le interesa"?</h3>';
$(contenido).appendTo('#dialogo'); */
//aca abría que desactivar el prospecto???? y registrar volver a llamar a largo plazó??
break;
case '4':
//Venta Transfer
$("#btsend").click();
$("#dialogo").dialog("close");
href = window.location.origin+'/pedidos/transfer/editar.php';
window.open(href,'_blank');
break;
case '5':
//Volver a llamar - Reprograma llamada
$("#dialogo").dialog("close");
dac_reprogramar(origen, idorigen, nroRel, 'volver a llamar', telefono);
/*
$( "#dialogo" ).dialog({
buttons: {
Aceptar : function () {
// REPROGRAMAR LLAMADA
dac_reprogramar(origen, idorigen, nroRel, 'volver a llamar', telefono);
},
Cerrar : function () {
$(this).dialog("close");
}
},
});
var contenido = '<h3>\u00BFRegistrar la llamada como "Volver a llamar"?</h3>';
$(contenido).appendTo('#dialogo'); */
break;
default: $("#dialogo").dialog("close"); break;
}
});
function dac_sendMail(empresa, email, asunto){
//Php co ajax para envío de email
$("#enviarmail").empty();
$("#enviarmail").dialog({
modal: true,
title: 'Mensaje',
zIndex: 100,
autoOpen: true,
resizable: false,
width: 380,
height: 560,
});
$("#enviarmail").dialog( "option", "title", 'Redactar Correo');
$("#enviarmail").dialog({
buttons: {
Enviar : function () {
//Bloquear los campòs del correo
//Enviar Correo vía AJAX
dac_sendForm('#fm_correo', '/pedidos/js/ajax/send.email.php');
var valorDiv = $("#box_confirmacion").text();
//if(valorDiv == "Los datos fueron enviados") { alert("A");
// } else { alert("B"); }
// $(this).dialog("close");
},
Cerrar : function () {
//Desbloquear los campòs del correo
$( "#alertas" ).remove();
$(alertas).appendTo('#mensajesAlertas');
$(this).dialog("close");
}
},
});
var contenido = '<form id="fm_correo" name="fm_correo" class="fm_popup" method="post" enctype="multipart/form-data">';
contenido += '<input type="text" name="idemp" value="'+empresa+'" hidden="hidden">';
contenido += '<div class="bloque_1">Para:</div><div class="bloque_1"><input type="text" name="email" value="'+email+'"> </div>';
contenido += '<div class="bloque_1">Asunto:</div><div class="bloque_1"><input type="text" name="asunto" value="'+asunto+'"></div>';
contenido += '<div class="bloque_1">Adjunto/s:</div><div class="bloque_1"><input name="multifile[]" type="file" multiple="multiple" class="file"/></div>';
contenido += '<div class="bloque_1">Mensaje:</div><div class="bloque_1"><textarea id="mensaje" name="mensaje" type="text"></textarea>';
contenido += '</form>';
var alertas = '<div id="alertas">';
alertas += '<fieldset id="box_error" class="msg_error">';
alertas += '<div id="msg_error"></div>';
alertas += '</fieldset>';
alertas += '<fieldset id="box_cargando" class="msg_informacion">';
alertas += '<div id="msg_cargando"></div>';
alertas += '</fieldset>';
alertas += '<fieldset id="box_confirmacion" class="msg_confirmacion">';
alertas += '<div id="msg_confirmacion"></div>';
alertas += '</fieldset>';
alertas += '</div>';
contenido += alertas;
$(contenido).appendTo('#enviarmail');
}
</script>
<file_sep>/condicion/logica/ajax/duplicar.condicion.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$arrayIdCond= empty($_POST['condid']) ? 0 : $_POST['condid'];
$backURL = '/pedidos/condicion/';
if(!$arrayIdCond) {
echo "Seleccione condición para modificar."; exit;
}
//si no es array, lo convierte
if(!is_array($arrayIdCond)){
$arrayIdCond = array($arrayIdCond);
}
//Inicio
$dtInicio = new DateTime("now");
if($dtInicio->format("m") == 12){
$ano = $dtInicio->format("Y") + 1;
}
$ano = $dtInicio->format("Y");
$mes = $dtInicio->format("m") + 1;
$dia = "01";
$dtInicio->setDate($ano , $mes , $dia);
//FIN
$dtFin = clone $dtInicio;
$dia = date( 't', strtotime( $dtFin->format("Y-m-d")));
$dtFin->setDate($ano , $mes , $dia);
foreach ($arrayIdCond as $j => $condId) {
//Consulto los datos de dicha condición comercial para duplcar
//$condicion = DataManager::getCondicion($condId);
$condicion = DataManager::getCondiciones(0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $condId);
if(count($condicion) != 1){
echo "Error al consultar la condición."; exit;
}
//--------------------------
// Lee y Duplica Condición
if ($condId) {
$condObject = DataManager::newObjectOfClass('TCondicionComercial', $condId);
$condIdEmp = $condObject->__get('Empresa');
$condIdLab = $condObject->__get('Laboratorio');
$condCuentas = $condObject->__get('Cuentas');
$condNombre = $condObject->__get('Nombre');
$condTipo = $condObject->__get('Tipo');
$condCondPago = $condObject->__get('CondicionPago');
$condcCantMin = $condObject->__get('CantidadMinima');
$condMinRef = $condObject->__get('MinimoReferencias');
$condMinMon = $condObject->__get('MinimoMonto');
$condObservacion= $condObject->__get('Observacion');
$habitualCant = $condObject->__get('Cantidad');
$habitualBonif1 = $condObject->__get('Bonif1');
$habitualBonif2 = $condObject->__get('Bonif2');
$habitualDesc1 = $condObject->__get('Desc1');
$habitualDesc2 = $condObject->__get('Desc2');
$condLista = $condObject->__get('Lista');
//-------------------------
// CREO condición nueva
$condObjectDup = DataManager::newObjectOfClass('TCondicionComercial');
$condObjectDup->__set('Empresa' , $condIdEmp);
$condObjectDup->__set('Laboratorio' , $condIdLab);
$condObjectDup->__set('Cuentas' , $condCuentas);
$condObjectDup->__set('Nombre' , $condNombre);
$condObjectDup->__set('Tipo' , $condTipo);
$condObjectDup->__set('CondicionPago' , $condCondPago);
$condObjectDup->__set('CantidadMinima' , $condcCantMin);
$condObjectDup->__set('MinimoReferencias' , $condMinRef);
$condObjectDup->__set('MinimoMonto' , $condMinMon);
$condObjectDup->__set('FechaInicio' , $dtInicio->format("Y-m-d"));
$condObjectDup->__set('FechaFin' , $dtFin->format("Y-m-d"));
$condObjectDup->__set('Observacion' , $condObservacion);
$condObjectDup->__set('Cantidad' , $habitualCant);
$condObjectDup->__set('Bonif1' , $habitualBonif1);
$condObjectDup->__set('Bonif2' , $habitualBonif2);
$condObjectDup->__set('Desc1' , $habitualDesc1);
$condObjectDup->__set('Desc2' , $habitualDesc2);
$condObjectDup->__set('UsrUpdate' , $_SESSION["_usrid"]);
$condObjectDup->__set('LastUpdate' , date("Y-m-d"));
$condObjectDup->__set('ID' , $condObjectDup->__newID());
$condObjectDup->__set('Activa' , 0); //Inactivo para modificar antes de activar
$condObjectDup->__set('Lista' , $condLista);
DataManagerHiper::_getConnection('Hiper');
$ID = DataManager::insertSimpleObject($condObjectDup);
DataManagerHiper::insertSimpleObject($condObjectDup, $ID);
//---------------------
// cargo artículos
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
foreach ($articulosCond as $k => $detArt) {
$detIdart = $detArt['cartidart'];
$detPrecio = $detArt["cartprecio"];
$detDigitado= $detArt["cartpreciodigitado"];
$detCantMin = empty($detArt['cartcantmin']) ? 0 : $detArt['cartcantmin'];
$detOAM = $detArt["cartoam"];
$detOferta = $detArt["cartoferta"];
//--------------------------------
// Duplico Detalle de Artículo
$condArtObject = DataManager::newObjectOfClass('TCondicionComercialArt');
$condArtObject->__set('Condicion' , $ID);
$condArtObject->__set('Articulo' , $detIdart);
$condArtObject->__set('Precio' , $detPrecio);
$condArtObject->__set('Digitado' , $detDigitado);
$condArtObject->__set('CantidadMinima' , $detCantMin);
$condArtObject->__set('OAM' , $detOAM);
$condArtObject->__set('Oferta' , $detOferta);
$condArtObject->__set('Activo' , 0);
$condArtObject->__set('ID' , $condArtObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDArt = DataManager::insertSimpleObject($condArtObject);
DataManagerHiper::insertSimpleObject($condArtObject, $IDArt);
//------------------------------------
// Creo Detalle de Bonificaciones
$articulosBonif = DataManager::getCondicionBonificaciones($condId, $detIdart);
if (count($articulosBonif)) {
foreach ($articulosBonif as $j => $artBonif) {
$artBonifCant = empty($artBonif['cbcant']) ? 0 : $artBonif['cbcant'];
$artBonifB1 = empty($artBonif['cbbonif1']) ? 0 : $artBonif['cbbonif1'];
$artBonifB2 = empty($artBonif['cbbonif2']) ? 0 : $artBonif['cbbonif2'];
$artBonifD1 = empty($artBonif['cbdesc1']) ? 0 : $artBonif['cbdesc1'];
$artBonifD2 = empty($artBonif['cbdesc2']) ? 0 : $artBonif['cbdesc2'];
$condArtBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif');
$condArtBonifObject->__set('Condicion' , $ID);
$condArtBonifObject->__set('Articulo' , $detIdart);
$condArtBonifObject->__set('Cantidad' , $artBonifCant);
$condArtBonifObject->__set('Bonif1' , $artBonifB1);
$condArtBonifObject->__set('Bonif2' , $artBonifB2);
$condArtBonifObject->__set('Desc1' , $artBonifD1);
$condArtBonifObject->__set('Desc2' , $artBonifD2);
$condArtBonifObject->__set('Activo' , 0);
$condArtBonifObject->__set('ID' , $condArtBonifObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDArtBonif = DataManager::insertSimpleObject($condArtBonifObject);
DataManagerHiper::insertSimpleObject($condArtBonifObject, $IDArtBonif);
}
}
}
}
// Registro MOVIMIENTO
$movimiento = 'DUPLICA_ID_'.$condId;
dac_registrarMovimiento($movimiento, "INSERT", 'TCondicionComercial', $condId);
} else {
echo "No se encuentran datos de Condición."; exit;
}
}
echo "1"; exit;
header('Location: '.$backURL);
?><file_sep>/rendicion/logica/ajax/update.recibo.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$_chequeid = empty($_REQUEST['chequeid']) ? 0 : $_REQUEST['chequeid'];
$_factid = empty($_REQUEST['factid']) ? 0 : $_REQUEST['factid'];
$_recid = empty($_REQUEST['recid']) ? 0 : $_REQUEST['recid'];
$_rendid = empty($_REQUEST['rendid']) ? 0 : $_REQUEST['rendid'];
//*******************************************//
$_factNumber = (isset($_GET['factNumber'])) ? $_GET['factNumber'] : NULL;
$_cheqNumber = (isset($_GET['rowNumber'])) ? $_GET['rowNumber'] : NULL;
$_observacion = (isset($_GET['observacion'])) ? $_GET['observacion'] : NULL;
$_diferencia = (isset($_GET['diferencia'])) ? $_GET['diferencia'] : NULL;
$_nro_rendicion = (isset($_GET['nro_rendicion'])) ? $_GET['nro_rendicion']: NULL;
$_nro_tal = (isset($_GET['nro_tal'])) ? $_GET['nro_tal'] : NULL;
$_nro_rec = (isset($_GET['nro_rec'])) ? $_GET['nro_rec'] : NULL;
//*******************************************//
$_nro_fact = json_decode(str_replace ('\"','"', $_GET['nrofactObject']), true);
$_fecha_fact = json_decode(str_replace ('\"','"', $_GET['fechaObj']), true);
$_nombrecli = json_decode(str_replace ('\"','"', $_GET['nombrecliObj']), true);
$_importe_dto = json_decode(str_replace ('\"','"', $_GET['importe_dtoObj']), true);
$_importe_neto = json_decode(str_replace ('\"','"', $_GET['importe_netoObj']), true);
$_importe_bruto = json_decode(str_replace ('\"','"', $_GET['importe_brutoObj']), true);
$_pago_efectivo = json_decode(str_replace ('\"','"', $_GET['pago_efectObj']), true);
$_pago_transfer = json_decode(str_replace ('\"','"', $_GET['pago_transfObj']), true);
$_pago_retencion= json_decode(str_replace ('\"','"', $_GET['pago_retenObj']), true);
$_bco_nombre = json_decode(str_replace ('\"','"', $_GET['bco_nombreObj']), true);
$_bco_nrocheque = json_decode(str_replace ('\"','"', $_GET['bco_nrochequeObj']), true);
$_bco_fecha = json_decode(str_replace ('\"','"', $_GET['bco_fechaObj']), true);
$_bco_importe = json_decode(str_replace ('\"','"', $_GET['bco_importeObj']), true);
$nocheque = 0;
$_nva_rendicion = 0;
//---------------------------------------
//Controlo rendición activa (NO ENVIADA)
//---------------------------------------
$_rendicion = DataManager::getRendicion($_SESSION["_usrid"], $_nro_rendicion);
if (count($_rendicion)) {
foreach ($_rendicion as $k => $_rend){
$_rend = $_rendicion[$k];
$_rendActiva= $_rend['rendactiva'];
}
if($_rendActiva != 1){
echo "No se pueden enviar los datos con el Nro. de Rendición ".$_nro_rendicion." ya que fue enviado anteriormente."; exit;
}
} else {
//Si no existen datos, es que el nro de rendición no existe, por lo tanto es nueva
$_nva_rendicion = 1;
}
//-----------------------------
//Controlo campo de c/factura
//-----------------------------
for($i = 0; $i < $_factNumber; $i++) {
//list($codigo, $nombre) = explode('-', $_nombrecli[$i]);
$_nro_fact[$i] = trim($_nro_fact[$i]);
if (empty($_nro_fact[$i])){
echo "Debe completar el Nro DE FACTURA de la Factura ".($i+1);
exit;}
$_fecha_fact[$i] = trim($_fecha_fact[$i]);
if (empty($_fecha_fact[$i])){
echo "Debe completar correctamente la FECHA de la Factura ".($i+1);
exit;}
if ($_nombrecli[$i] == "Seleccione Cliente..." ){
echo "Debe completar correctamente el NOMBRE DE CLIENTE de la Factura ".($i+1);
exit;}
$_importe_bruto[$i] = trim($_importe_bruto[$i]);
if (empty($_importe_bruto[$i]) or $_importe_bruto[$i] <= 0){
echo "Debe completar correctamente el TOTAL A PAGAR de la Factura ".($i+1);
exit;}
}
//******************************
//Controlo campo de c/cheques.
//******************************
//Si es un solo cheque (lleno o vacío)
if ($_cheqNumber == 1) {
$_bco_nrocheque[0] = trim($_bco_nrocheque[0]);
$_bco_fecha[0] = trim($_bco_fecha[0]);
$_bco_importe[0] = trim($_bco_importe[0]);
if ($_bco_nombre[0] == "Seleccione Banco..." && empty($_bco_nrocheque[0]) && empty($_bco_fecha[0]) && empty($_bco_importe[0])){
$nocheque = 1;
//Si no hay cheques, controlo ingresos de las facturas
for ($i = 0; $i < $_factNumber; $i++){
//Controla que haya alguna forma de pago en cada factura (ya que no se pagó con ningún cheque)
$pagoTransfer = (empty($_pago_transfer[$i])) ? 0 : $_pago_transfer[$i];
$pagoRetencion = (empty($_pago_retencion[$i])) ? 0 : $_pago_retencion[$i];
$pagoEfectivo = (empty($_pago_efectivo[$i])) ? 0 : $_pago_efectivo[$i];
$_pagofact = $pagoEfectivo + $pagoTransfer + $pagoRetencion[$i];
if ($_pagofact == 0 || empty($_pagofact)){
echo "Debe completar correctamente alguna FORMA DE PAGO para la factura ".($i+1); exit;}
}
} else {
if ($_bco_nombre[0] == "Seleccione Banco..." || empty($_bco_nrocheque[0]) || empty($_bco_fecha[0]) || $_bco_importe[0] == ""){
echo "Debe completar correctamente todos los CAMPOS DEL CHEQUE 1"; exit;}
}
} else {
//Si son varios cheques
for ($i = 0; $i < $_cheqNumber; $i++){
$_bco_nrocheque[$i] = trim($_bco_nrocheque[$i]);
$_bco_fecha[$i] = trim($_bco_fecha[$i]);
$_bco_importe[$i] = trim($_bco_importe[$i]);
//controla campos vacíos de cheques
if ($_bco_nombre[$i] == "Seleccione Banco..." || empty($_bco_nrocheque[$i]) || empty($_bco_fecha[$i]) || empty($_bco_importe[$i])){
echo "Debe completar correctamente todos los CAMPOS DEL CHEQUE ".($i+1); exit;}
}
}
//-------------------------------
//Controlo diferencia del recibo
//-------------------------------
if ($_diferencia != "" && $_diferencia != 0){
$observ_longitud = strlen(trim($_observacion, ' '));
if($observ_longitud == 0){
echo "Debe completar correctamente el motivo de la DIFERENCIA."; exit;
}
}
//----------------
// PARA GUARDAR
//----------------
//-----------
// cheques
//-----------
if ($nocheque == 0){ // si hay cheque
unset($_IDcheque);
for($i = 0; $i < $_cheqNumber; $i++){
$date = $_bco_fecha[$i];
list($dia, $mes, $ano) = explode('-', str_replace('/', '-', $date));
$fechacheq = $ano."-".$mes."-".$dia;
$_chequeobject = ($_chequeid) ? DataManager::newObjectOfClass('TCheques', $_chequeid) : DataManager::newObjectOfClass('TCheques');
$_chequeobject->__set('Banco', $_bco_nombre[$i]);
$_chequeobject->__set('Numero', $_bco_nrocheque[$i]);
$_chequeobject->__set('Fecha', $fechacheq);
$_chequeobject->__set('Importe',$_bco_importe[$i]);
if ($_chequeid) {
$ID = DataManager::updateSimpleObject($_chequeobject);
$_IDcheque[] = $_chequeid;
} else {
$_chequeobject->__set('ID', $_chequeobject->__newID());
$_IDcheque[] = DataManager::insertSimpleObject($_chequeobject);
}
}
}
//------------------//
// facturas
//------------------//
unset($_IDfactura);
for($i = 0; $i < $_factNumber; $i++){
list($codigo, $nombre) = explode('-', $_nombrecli[$i]);
$date = $_fecha_fact[$i];
list($dia, $mes, $ano) = explode('-', str_replace('/', '-', $date));
$fechafact = $ano."-".$mes."-".$dia;
$pagoTransfer = (empty($_pago_transfer[$i])) ? 0 : $_pago_transfer[$i];
$importeDesc = (empty($_importe_dto[$i])) ? 0 : $_importe_dto[$i];
$pagoRetencion = (empty($_pago_retencion[$i])) ? 0 : $_pago_retencion[$i];
$pagoEfectivo = (empty($_pago_efectivo[$i])) ? 0 : $_pago_efectivo[$i];
$_facturaobject = ($_factid) ? DataManager::newObjectOfClass('TFacturas', $_factid) : DataManager::newObjectOfClass('TFacturas');
$_facturaobject->__set('Numero', $_nro_fact[$i]);
$_facturaobject->__set('Cliente', $codigo);
$_facturaobject->__set('Fecha', $fechafact);
$_facturaobject->__set('Bruto', $_importe_bruto[$i]);
$_facturaobject->__set('Descuento', $importeDesc);
$_facturaobject->__set('Neto', $_importe_neto[$i]);
$_facturaobject->__set('Efectivo', $pagoEfectivo);
$_facturaobject->__set('Transfer', $pagoTransfer);
$_facturaobject->__set('Retencion', $pagoRetencion);
if ($_factid) {
$ID = DataManager::updateSimpleObject($_facturaobject);
$_IDfactura[] = $_factid;
} else {
$_facturaobject->__set('ID', $_facturaobject->__newID());
$_IDfactura[] = DataManager::insertSimpleObject($_facturaobject);
}
}
//--------------
// fact_cheq
//--------------
if ($nocheque == 0){ // si hay cheque
for($i = 0; $i < $_factNumber; $i++){
for($j = 0; $j < $_cheqNumber; $j++){
$_campos = 'factid, cheqid';
$_values = $_IDfactura[$i].",".$_IDcheque[$j];
DataManager::insertToTable('fact_cheq', $_campos, $_values);
}
}
}
//----------
// Recibo
//----------
$_reciboobject = ($_recid) ? DataManager::newObjectOfClass('TRecibos', $_recid) : DataManager::newObjectOfClass('TRecibos');
$_reciboobject->__set('Numero' , $_nro_rec);
$_reciboobject->__set('Talonario' , $_nro_tal);
$_reciboobject->__set('Observacion' , $_observacion);
$_reciboobject->__set('Diferencia' , $_diferencia);
if ($_recid) {
DataManager::updateSimpleObject($_reciboobject);
$_IDrecibo = $_recid;
} else {
$_reciboobject->__set('ID', $_reciboobject->__newID());
$_IDrecibo = DataManager::insertSimpleObject($_reciboobject);
}
//-------------
// rec_fact
//-------------
for($i = 0; $i < $_factNumber; $i++){
$_campos = 'recid, factid';
$_values = $_IDrecibo.",".$_IDfactura[$i];
DataManager::insertToTable('rec_fact', $_campos, $_values);
}
//-------------
// rendicion
//-------------
$rendObject = ($_nva_rendicion == 0) ? DataManager::newObjectOfClass('TRendicion', $_rendid) : DataManager::newObjectOfClass('TRendicion');
$rendObject->__set('Numero' , $_nro_rendicion);
$rendObject->__set('IdUsr' , $_SESSION["_usrid"]);
$rendObject->__set('NombreUsr' , $_SESSION["_usrname"]);
$rendObject->__set('Activa' , 1);
//Si el $_nro_rendicion es nuevo, deberá crearse una nueva rendición
if ($_nva_rendicion == 0) {
DataManager::updateSimpleObject($rendObject);
$_IDrendicion = $_rendid;
} else {
$rendObject->__set('Retencion' , '0.00');
$rendObject->__set('Deposito' , '0.00');
$rendObject->__set('Envio' , date("2001-01-01"));
$rendObject->__set('Fecha' , date("Y-m-d"));
$rendObject->__set('ID' , $rendObject->__newID());
$_IDrendicion = DataManager::insertSimpleObject($rendObject);
}
//-------------
// rend_rec
//-------------
$_campos = 'rendid, recid';
$_values = $_IDrendicion.",".$_IDrecibo;
DataManager::insertToTable('rend_rec', $_campos, $_values);
echo "1";
?><file_sep>/proveedores/logica/eliminar.proveedor.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
//require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$provId = empty($_REQUEST['provid']) ? 0 : $_REQUEST['provid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/proveedores/': $_REQUEST['backURL'];
if ($provId) {
//Elimina documentación del proveedor
$dir = $_SERVER['DOCUMENT_ROOT']."/pedidos/login/registrarme/archivos/proveedor/".$provId;
dac_deleteDirectorio($dir);
//Elimina Contactos del Proveedor?? // Los contactos podrían seguir estando por el tema de CRM
//Elimina proveedor
$_cliobject = DataManager::newObjectOfClass('TProveedor', $provId);
$provIdProv = $_cliobject->__get('Proveedor', $provId);
$_cliobject->__set('ID', $provId );
DataManager::deleteSimpleObject($_cliobject);
//**********************//
// Registro MOVIMIENTO //
//**********************//
$movimiento = 'PROVEEDOR_'.$provId."-".$provIdProv;
$movTipo = 'DELETE';
dac_registrarMovimiento($movimiento, $movTipo, "TProveedor", $provId);
}
header('Location: '.$backURL.'?pag='.$_pag);
?><file_sep>/articulos/logica/json/getFamilia.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
$idEmpresa = $_GET['idEmpresa'];
$datosJSON;
$familias = DataManager::getCodFamilias(0,0,$idEmpresa);
if (count($familias)) {
foreach ($familias as $k => $flia) {
$idFlia = $flia["IdFamilia"];
$nombreFlia = $flia["Nombre"];
$datosJSON[] = $idFlia."-".$nombreFlia;
}
}
/*una vez tenemos un array con los datos los mandamos por json a la web*/
header('Content-type: application/json');
echo json_encode($datosJSON);
?><file_sep>/planificacion/logica/jquery/jqueryAdmin.js
function dac_Anular_Planificacion(){
"use strict";
var fecha_anular = document.getElementById("f_fecha_anular").value;
var vendedor = document.getElementById("vendedor").value;
if(confirm("Desea anular el env\u00edo de la planificaci\u00f3n?")){
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/planificacion/logica/ajax/anular.planificado.php',
data:{ vendedor : vendedor,
fecha_anular : fecha_anular
},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
$('#box_cargando').css({'display':'none'});
if (resultado){
$('#box_error').css({'display':'block'});
$("#msg_error").html(resultado);
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al intentar anular la Planificaci\u00f3n.");
}
});
}
}
function dac_Anular_Parte(){
"use strict";
var fecha_anular = document.getElementById("f_fecha_anular_parte").value;
var vendedor = document.getElementById("vendedor2").value;
if(confirm("Desea anular el env\u00edo del parte?")){
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/planificacion/logica/ajax/anular.parte.php',
data:{ vendedor : vendedor,
fecha_anular : fecha_anular
},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
$('#box_cargando').css({'display':'none'});
if (resultado){
$('#box_error').css({'display':'block'});
$("#msg_error").html(resultado);
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al intentar anular el Parte.");
}
});
}
}
<file_sep>/condicion/logica/jquery/jquery.process.cond.js
$(document).ready(function() {
$( "#btsend" ).click(function () {
var condid = $('input[name="condid"]:text').val();
var empselect = $('select[name="empselect"]').val();
var labselect = $('select[name="labselect"]').val();
var tiposelect = $('select[name="tiposelect"]').val();
var nombre = $('input[name="nombre"]:text').val();
var condpago = $('input[name="condpago"]:text').val();
var minMonto = $('input[name="minMonto"]:text').val();
var cantMinima = $('input[name="cantMinima"]:text').val();
var minReferencias = $('input[name="minReferencias"]:text').val();
var fechaInicio = $('input[name="fechaInicio"]:text').val();
var fechaFin = $('input[name="fechaFin"]:text').val();
var observacion = $('textarea[name="observacion"]').val();
var habitualCant = $('input[name="habitualCant"]:text').val();
var habitualBonif1 = $('input[name="habitualBonif1"]:text').val();
var habitualBonif2 = $('input[name="habitualBonif2"]:text').val();
var habitualDesc1 = $('input[name="habitualDesc1"]:text').val();
var habitualDesc2 = $('input[name="habitualDesc2"]:text').val();
var cuentaid; //= new Array();
var condpagoid;
var condidart = []; //= new Array();
var condprecioart = []; //= new Array();
var condpreciodigit = []; //= new Array();
var condcantmin = []; //= new Array();
var condoferta = []; //= new Array();
$('input[name="cuentaid[]"]:text').each(function() {
cuentaid = (cuentaid) ? cuentaid+","+$(this).val() : $(this).val();
});
$('input[name="condpagoid[]"]:text').each(function() {
condpagoid = (condpagoid) ? condpagoid+","+$(this).val() : $(this).val();
});
$('input[name="condprecioart[]"]:text').each(function(i) { condprecioart[i] = $(this).val();});
$('input[name="condpreciodigit[]"]:text').each(function(i) { condpreciodigit[i]= $(this).val();});
$('input[name="condcantmin[]"]:text').each(function(i) { condcantmin[i] = $(this).val();});
$('select[name="condoferta[]"]').each(function(i) { condoferta[i] = $(this).val();});
var condcant = '';
var condbonif1 = '';
var condbonif2 = '';
var conddesc1 = '';
var conddesc2 = '';
//al recorrer el foreach de artículos, cargo sus bonificaciones?
$('input[name="condidart[]"]:text').each(function(i) {
condidart[i] = $(this).val();
$('input[name="condcant'+condidart[i]+'[]"]:text').each(function(j) {
condcant = (j === 0) ? condcant+$(this).val() : condcant+"-"+$(this).val();
});
$('input[name="condbonif1'+condidart[i]+'[]"]:text').each(function(j) {
condbonif1 = (j === 0) ? condbonif1+$(this).val() : condbonif1+"-"+$(this).val();
});
$('input[name="condbonif2'+condidart[i]+'[]"]:text').each(function(j) {
condbonif2 = (j === 0) ? condbonif2+$(this).val() : condbonif2+"-"+$(this).val();
});
$('input[name="conddesc1'+condidart[i]+'[]"]:text').each(function(j) {
conddesc1 = (j === 0) ? conddesc1+$(this).val() : conddesc1+"-"+$(this).val();
});
$('input[name="conddesc2'+condidart[i]+'[]"]:text').each(function(j) {
conddesc2 = (j === 0) ? conddesc2+$(this).val() : conddesc2+"-"+$(this).val();
});
condcant = condcant + '|';
condbonif1 = condbonif1 + '|';
condbonif2 = condbonif2 + '|';
conddesc1 = conddesc1 + '|';
conddesc2 = conddesc2 + '|';
});
dac_enviar();
function dac_enviar(){
$.ajax({
type: 'POST',
url: '/pedidos/condicion/logica/update.condicion.php',
data: {
condid : condid,
empselect : empselect,
labselect : labselect,
tiposelect : tiposelect,
nombre : nombre,
condpago : condpago,
minMonto : minMonto,
cantMinima : cantMinima,
minReferencias:minReferencias,
fechaInicio : fechaInicio,
fechaFin : fechaFin,
observacion : observacion,
habitualCant : habitualCant,
habitualBonif1 : habitualBonif1,
habitualBonif2 : habitualBonif2,
habitualDesc1 : habitualDesc1,
habitualDesc2 : habitualDesc2,
cuentaid : cuentaid,
condpagoid : condpagoid,
condidart : condidart,
condprecioart: condprecioart,
condpreciodigit:condpreciodigit,
condcantmin : condcantmin,
condoferta : condoferta,
condcant : condcant,
condbonif1 : condbonif1,
condbonif2 : condbonif2,
conddesc1 : conddesc1,
conddesc2 : conddesc2
},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
$("#btsend").hide(100);
},
success: function(result) {
if (result){
$('#box_cargando').css({'display':'none'});
if (result.replace("\n","") === '1'){
//Confirmación
var scrolltohere = "#box_confirmacion";
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('Los datos fueron registrados');
window.location.reload(true);
} else {
//El pedido No cumple Condiciones
var scrolltohere = "#box_error";
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
if(result === "Invalido"){
window.location = "/pedidos/login/index.php";
}
}
$('html,body').animate({
scrollTop: $(scrolltohere).offset().top
}, 2000);
$("#btsend").show(100);
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error en el proceso");
$("#btsend").show(100);
},
});
}
});
});<file_sep>/cadenas/lista.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
exit;
} ?>
<script type="text/javascript" language="JavaScript" src="/pedidos/cadenas/logica/jquery/scriptCadenas.js"></script>
<div class="box_body">
<div class="bloque_1" align="center">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<form id="fmCadena" name="fmCadena" method="post">
<input type="text" id="cadid" name="cadid" hidden="hidden">
<fieldset>
<legend>Datos de cadena</legend>
<div class="bloque_5">
<label for="empresa">Empresa</label>
<select id="empresa" name="empresa" onchange="javascript:dac_changeEmpresa(this.value);"> <?php
$empresas = DataManager::getEmpresas(1);
if (count($empresas)) {
foreach ($empresas as $k => $emp) {
$idEmp = $emp["empid"];
$nombreEmp = $emp["empnombre"];
if ($idEmp == 1){ ?>
<option id="<?php echo $idEmp; ?>" value="<?php echo $idEmp; ?>" selected><?php echo $nombreEmp; ?></option><?php
} else { ?>
<option id="<?php echo $idEmp; ?>" value="<?php echo $idEmp; ?>"><?php echo $nombreEmp; ?></option><?php
}
}
}
echo "<script>";
echo "dac_changeEmpresa(1);";
echo "</script>";
?>
</select>
</div>
<div class="bloque_9">
<br>
<a title="Nueva Cadena" onClick="dac_changeEmpresa(empresa.value)">
<img class="icon-new"/>
</a>
</div>
<div class="bloque_9">
<br>
<?php $urlSend = '/pedidos/cadenas/logica/update.cadena.php';?>
<a id="btnSend" title="Enviar">
<img class="icon-send" onclick="javascript:dac_sendForm(fmCadena, '<?php echo $urlSend;?>');"/>
</a>
</div>
<hr>
<div class="bloque_8">
<label for="cadena">Cadena</label>
<input type="text" id="cadena" name="cadena" readonly>
</div>
<div class="bloque_2">
<label for="id">Nombre</label>
<input type="text" id="nombre" name="nombre" class="text-uppercase">
</div>
</fieldset>
<fieldset>
<legend>Cuentas Relacionadas</legend>
<div id="cuenta_relacionada"></div>
</fieldset>
</form>
</div> <!-- Fin box body -->
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Cadenas</h1>
</div>
<div class="bloque_5" style="float: right">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn" type="text" value="tblCadenas" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<div id='tablacadenas'></div>
</div> <!-- Fin lista -->
<div class="barra">
<div class="bloque_5">
<h2>Cuentas</h2>
</div>
<div class="bloque_5" style="float: right">
<input id="txtBuscar2" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn2" type="text" value="tblCuentas" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<div id='tablacuentas'></div>
</div> <!-- Fin listar -->
</div> <!-- Fin box_seccion -->
<hr><file_sep>/pedidos/editar.cadena.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$usrAsignado = (isset($_POST['pwusrasignado']))? $_POST['pwusrasignado'] : NULL;
$usrAsigName = DataManager::getUsuario('unombre', $usrAsignado);
$empresa = (isset($_POST['empselect'])) ? $_POST['empselect'] : NULL;
$laboratorio = (isset($_POST['labselect'])) ? $_POST['labselect'] : NULL;
$idCuenta = (isset($_POST['pwidcta'])) ? $_POST['pwidcta'] : NULL;
$nombreCuenta = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $idCuenta, $empresa);
$nroOrden = (isset($_POST['pworden'])) ? $_POST['pworden'] : NULL;
$condPago = (isset($_POST['condselect'])) ? $_POST['condselect'] : NULL;
$observacion = (isset($_POST['pwobservacion']))? $_POST['pwobservacion'] : NULL;
//***********************//
$idCondComercial= (isset($_POST['pwidcondcomercial']))? $_POST['pwidcondcomercial'] : NULL;
//***********************//
$articulosIdArt = (isset($_POST['pwidart'])) ? $_POST['pwidart'] : NULL;
for($i=0;$i<count($articulosIdArt);$i++){
$articulosNombre[] = DataManager::getArticulo('artnombre', $articulosIdArt[$i], $empresa, $laboratorio);
}
$articulosCant = (isset($_POST['pwcant'])) ? $_POST['pwcant'] : NULL;
$articulosPrecio= (isset($_POST['pwprecioart'])) ? $_POST['pwprecioart'] : NULL;
$articulosB1 = (isset($_POST['pwbonif1'])) ? $_POST['pwbonif1'] : NULL;
$articulosB2 = (isset($_POST['pwbonif2'])) ? $_POST['pwbonif2'] : NULL;
$articulosD1 = (isset($_POST['pwdesc1'])) ? $_POST['pwdesc1'] : NULL;
$articulosD2 = (isset($_POST['pwdesc2'])) ? $_POST['pwdesc2'] : NULL;
$cadena = (isset($_POST['cadena'])) ? $_POST['cadena'] : NULL;
//----------------------------------
//SE AGREGA ARTICULO PROMOCIONAL OBLIGATORIO A LAS SIGUIENTES CUENTAS CON
//se aplica aquí y en generar.pedido.php.php
//categoría sea <> 1 (distintas de droguerías) AND
$categoria = DataManager::getCuenta('ctacategoriacomercial', 'ctaidcuenta', $idCuenta, $empresa);
//empresa == 1 AND
//$idCondComercial <> de ListaEspecial DR AHORRO, FARMACITY, FARMACITY 2
// originalmente $idCondComercial != 1764 && $idCondComercial != 1765 && $idCondComercial != 1761
$condBonificar = 0;
$condiciones = DataManager::getCondiciones(0, 0, 1, $empresa, $laboratorio, NULL, NULL, NULL, NULL, $idCondComercial);
if (count($condiciones) > 0) {
foreach ($condiciones as $i => $cond) {
$condTipo = $cond['condtipo'];
$condNombre = $cond['condnombre'];
if($condTipo == 'ListaEspecial' && ($condNombre == 'DR AHORRO' || $condNombre == 'FARMACITY' || $condNombre == 'FARMACITY 2')){
$condBonificar = 1;
}
}
} ?>
<!DOCTYPE html>
<html lang='es'>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php"; ?>
<script language="JavaScript" src="/pedidos/pedidos/logica/jquery/jquery.js" type="text/javascript"></script>
<script>
/* Carga Datos de Cuentas al Pedido */
function dac_cargarCuentaCadena(idcli, nombre, observacion, fijo) {
"use strict";
var campo = '<fieldset id="cta'+idcli+'">';
if(fijo === 0){
campo += '<div class="bloque_9"><br><input id="btmenos" type="button" value="-" onClick="dac_eliminarCuentaCadena('+idcli+')"></div>';
}
campo += '<div class="bloque_8"> ';
campo += ' <label for="pwidcta">Cuenta</label>';
campo += ' <input type="text" name="pwidcta[]" value="'+idcli+'" readonly/>';
campo += '</div>';
campo += '<div class="bloque_3">';
campo += ' <label>Razón social</label>';
campo += ' <input type="text" value="'+nombre+'" readonly/>';
campo += '</div>';
campo += '<div class="bloque_4">';
campo += ' <label>Observación</label> ';
campo += ' <textarea type="text" name="pwobservacion[]" maxlength="200" >'+observacion+'</textarea>';
campo += '</div> ';
campo += '<div class="bloque_7">';
campo += ' <label for="pworden">Nro Orden</label>';
campo += ' <input type="text" name="pworden[]" maxlength="10"/>';
campo += '</div>';
campo += '<div class="bloque_7">';
campo += ' <input name="file[]" class="file" type="file">';
campo += '</div>';
campo += '</fieldset>';
campo += '<fieldset id="art'+idcli+'">';
campo += ' <legend>Artículos</legend>';
var idArticulos=<?php echo json_encode($articulosIdArt);?>;
var nombresArt=<?php echo json_encode($articulosNombre);?>;
var preciosArt=<?php echo json_encode($articulosPrecio);?>;
var desc1=<?php echo json_encode($articulosD1);?>;
var desc2=<?php echo json_encode($articulosD2);?>;
for(var i=0;i<idArticulos.length;i++){
campo += '<div id="rut'+idcli+'-'+idArticulos[i]+'">';
campo += '<input name="pwidart'+idcli+'[]" type="text" value="'+idArticulos[i]+'" hidden/>';
campo += '<div class="bloque_9"><input id="btmenos" type="button" value="-" onClick="dac_eliminarArt('+idcli+', '+idArticulos[i]+')" style="background-color:#ba140c;"></div>';
campo += '<div class="bloque_2"><strong> Artículo '+idArticulos[i]+ '</strong></br>'+nombresArt[i]+'</div>';
campo += '<div class="bloque_8"><strong> Cantidad </strong> <input name="pwcant'+idcli+'[]" type="text" maxlength="5"/></div>';
campo += '<div class="bloque_8"><strong> Precio </strong> <input type="text" name="pwprecioart'+idcli+'[]" value="'+preciosArt[i]+'" readonly /> </div>';
campo += '<div class="bloque_8"><strong>Bonifica</strong> <input name="pwbonif1'+idcli+'[]" type="text" maxlength="5"/></div>';
campo += '<div class="bloque_8"><strong>Desc 1 </strong> <input type="text" name="pwdesc1'+idcli+'[]" value="'+desc1[i]+'" readonly/></div>';
campo += '<div class="bloque_8"><strong>Desc 2 </strong> <input type="text" name="pwdesc2'+idcli+'[]" value="'+desc2[i]+'" readonly/></div>';
campo += '</div><hr>';
};
campo += '</fieldset>';
$("#fmPedidoWebCadena").append(campo);
}
/****************************/
/* Elimina Cuenta */
function dac_eliminarCuentaCadena(idcli){
"use strict";
var elemento = document.getElementById('cta'+idcli);
elemento.parentNode.removeChild(elemento);
var elemento = document.getElementById('art'+idcli);
elemento.parentNode.removeChild(elemento);
}
/********************************/
/* Elimina un Artículo */
function dac_eliminarArt(idcli, idArt){
"use strict";
var elemento = document.getElementById('rut'+idcli+'-'+idArt);
elemento.parentNode.removeChild(elemento);
}
</script>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "pedidos";
$_subsection = "nuevo_pedido";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<div class="box_body">
<form id="fmPedidoWebCadena" name="fmPedidoWebCadena" method="post">
<input type="text" name="pwestado" value="<?php echo $estado; ?>" hidden="hidden"/>
<input type="text" name="pwidcondcomercial" value="<?php echo $idCondComercial; ?>" hidden="hidden"/>
<input type="hidden" name="pwidart" value='<?php echo serialize($articulosIdArt) ?>'/>
<input type="hidden" name="pwprecioart" value='<?php echo serialize($articulosPrecio) ?>'/>
<input type="hidden" name="pwcant" value='<?php echo serialize($articulosCant) ?>'/>
<input type="hidden" name="pwbonif1" value='<?php echo serialize($articulosB1) ?>'/>
<input type="hidden" name="pwbonif2" value='<?php echo serialize($articulosB2) ?>'/>
<input type="hidden" name="pwdesc1" value='<?php echo serialize($articulosD1) ?>'/>
<input type="hidden" name="pwdesc2" value='<?php echo serialize($articulosD2) ?>'/>
<fieldset>
<legend>Pedido CADENA</legend>
<div class="bloque_1" align="right">
<a id="btsendPedidoCadena" title="Enviar">
<img class="icon-send" />
</a>
</div>
<div class="bloque_1" align="center">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
<fieldset id='box_observacion' class="msg_alerta">
<div id="msg_atencion" align="center"></div>
</fieldset>
</div>
<div class="bloque_5">
<label for="pwusrasignado">Asignado a</label>
<input type="text" name="pwusrasignado" id="pwusrasignado" value="<?php echo $usrAsignado; ?>" hidden/>
<input type="text" value="<?php echo $usrAsigName; ?>" readonly/>
</div>
<div class="bloque_5">
<label for="empselect">Empresa</label>
<select id="empselect" name="empselect"> <?php
$empresas = DataManager::getEmpresas(1);
if (count($empresas)) {
foreach ($empresas as $k => $emp) {
$idEmp = $emp["empid"];
$nombreEmp = $emp["empnombre"];
if ($idEmp == $empresa){ ?>
<option id="<?php echo $idEmp; ?>" value="<?php echo $idEmp; ?>" selected><?php echo $nombreEmp; ?></option><?php
}
}
} ?>
</select>
</div>
<div class="bloque_5">
<label for="labselect">Laboratorio</label>
<select name="labselect" id="labselect"><?php
$laboratorios = DataManager::getLaboratorios();
if (count($laboratorios)) {
foreach ($laboratorios as $k => $lab) {
$idLab = $lab["idLab"];
$descripcion = $lab["Descripcion"];
if ($idLab == $laboratorio){ ?>
<option id="<?php echo $idLab; ?>" value="<?php echo $idLab; ?>" selected><?php echo $descripcion; ?></option><?php
}
}
} ?>
</select>
</div>
<div class="bloque_5">
<label>Condición de pago</label>
<select name="condselect" id="condselect"> <?php
$condicionesPago = DataManager::getCondicionesDePago(0, 0, 1);
if (count($condicionesPago)) {
foreach ($condicionesPago as $k => $cond) {
$idCond = $cond['condid'];
$condCodigo = $cond['IdCondPago'];
$condNombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $cond['condtipo']);
$condDias = "(";
$condDias .= empty($cond['Dias1CP']) ? '0' : $cond['Dias1CP'];
$condDias .= empty($cond['Dias2CP']) ? '' : ', '.$cond['Dias2CP'];
$condDias .= empty($cond['Dias3CP']) ? '' : ', '.$cond['Dias3CP'];
$condDias .= empty($cond['Dias4CP']) ? '' : ', '.$cond['Dias4CP'];
$condDias .= empty($cond['Dias5CP']) ? '' : ', '.$cond['Dias5CP'];
$condDias .= " Días)";
$condDias .= ($condPago['Porcentaje1CP'] == '0.00') ? '' : ' '.$condPago['Porcentaje1CP'].' %';
$condPorc = ($cond['Porcentaje1CP']== '0.00') ? '' : $cond['Porcentaje1CP'];
//Descarto la opción FLETERO
if(trim($condNombre) != "FLETERO"){
if($condPago == $condCodigo){ ?>
<option id="<?php echo $idCond; ?>" value="<?php echo $condCodigo; ?>" selected><?php echo $condNombre." - ".$condDias." - [".$condPorc."%]"; ?></option><?php
}
}
}
} ?>
</select>
</div>
</fieldset>
</form>
</div> <!-- FIN box_body-->
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Cuentas Cadenas</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn" type="text" value="tblTablaCta" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista"> <?php
$cuentasCadena = DataManager::getCuentasCadena($empresa, NULL, $idCuenta);
if(count($cuentasCadena)){
foreach ($cuentasCadena as $k => $ctaCad) {
$ctaIdCadena = $ctaCad["IdCadena"];
}
$cuentas = DataManager::getCuentasCadena($empresa, $ctaIdCadena, NULL);
if (count($cuentas)) {
echo '<table id="tblTablaCta" style="table-layout:fixed;">';
echo '<thead><tr align="left"><th>Cuenta</th><th>Nombre</th><th>Localidad</th></tr></thead>';
echo '<tbody>';
foreach ($cuentas as $k => $cta) {
$idCuentaCad = $cta["IdCliente"];
$nombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $idCuentaCad, $empresa);
$idLoc = DataManager::getCuenta('ctaidloc', 'ctaidcuenta', $idCuentaCad, $empresa);
$localidad = (empty($idLoc) || $idLoc == 0) ? DataManager::getCuenta('ctalocalidad', 'ctaidcuenta', $idCuentaCad, $empresa) : DataManager::getLocalidad('locnombre', $idLoc);
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class=".$clase." onclick=\"javascript:dac_cargarCuentaCadena('$idCuentaCad', '$nombre', '$observacion', 0)\" style=\"cursor:pointer\"><td>".$idCuentaCad."</td><td>".$nombre."</td><td>".$localidad."</td></tr>";
if($idCuentaCad == $idCuenta) {
echo "<script>";
echo "javascript:dac_cargarCuentaCadena('$idCuentaCad', '$nombre', '$observacion', 1)";
echo "</script>";
}
}
echo '</tbody></table>';
}
} else {
echo '<table><tr><td align="center">No hay registros activos.</td></tr></table>';
} ?>
</div> <!-- Fin lista -->
</div> <!-- FIN box_seccion-->
<hr>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html>
<file_sep>/articulos/logica/ajax/getArticulo.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G") {
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
$empresa = (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
$activos = (isset($_POST['activos'])) ? $_POST['activos'] : NULL;
$laboratorio= (isset($_POST['laboratorio']))? $_POST['laboratorio']: NULL;
$pag = (isset($_POST['pag'])) ? $_POST['pag'] : NULL;
$LPP = (isset($_POST['rows'])) ? $_POST['rows'] : NULL;
//------------------------------------
$articulos = DataManager::getArticulos($pag, $LPP, '', $activos, $laboratorio, $empresa);
$rows = count($articulos);
echo "<table id=\"tblArticulos\" style=\"table-layout:fixed;\">";
if (count($articulos)) {
echo "<thead><tr align=\"left\"><th width=\"10%\">Art</th><th width=\"45%\">Nombre</th><th width=\"15%\">Precio</th><th align=\"center\" colspan=\"3\" width=\"30%\" >Acciones</th></tr></thead>";
echo "<tbody>";
for( $k=0; $k < $LPP; $k++ ) {
if ($k < $rows) {
$art = $articulos[$k];
$id = $art['artid'];
$idArt = $art['artidart'];
$nombre = $art['artnombre'];
$precio = $art['artpreciolista'];
$editar = sprintf( "onclick=\"window.open('editar.php?artid=%d')\" style=\"cursor:pointer;\"",$id);
$status = ($art['artactivo']) ? "<a title=\"Activo\" onclick=\"javascript:dac_changeStatus('/pedidos/articulos/logica/changestatus.php', $id, $pag)\"> <img class=\"icon-status-active\"/></a>" : "<a title=\"Inactivo\" onclick=\"javascript:dac_changeStatus('/pedidos/articulos/logica/changestatus.php', $id, $pag)\"> <img class=\"icon-status-inactive\" /></a>";
$statusStock = ($art['artstock']) ? "<a title=\"Stock Activo\" onclick=\"javascript:dac_changeStatus('/pedidos/articulos/logica/changestock.php', $id, $pag)\"> <img class=\"icon-status-active\" /></a>" : "<a title=\"Stock Inactivo\" onclick=\"javascript:dac_changeStatus('/pedidos/articulos/logica/changestock.php', $id, $pag)\"> <img class=\"icon-status-inactive\" /></a>";
$eliminar = sprintf ("<a href=\"logica/eliminar.articulo.php?artid=%d\" title=\"eliminar articulo\" onclick=\"return confirm('¿Está Seguro que desea ELIMINAR LA ARTÍCULO?')\"> <img class=\"icon-delete\"/></a>", $id, "Eliminar");
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class=".$clase.">";
echo "<td ".$editar.">".$idArt."</td><td ".$editar.">".$nombre."</td><td ".$editar.">".$precio."</td><td align=\"center\">".$statusStock."</td><td align=\"center\">".$status."</td><td align=\"center\">".$eliminar."</td>";
echo "</tr>";
}
}
} else {
echo "<tbody>";
echo "<thead><tr><th colspan=\"6\" align=\"center\">No hay registros relacionadas</th></tr></thead>"; exit;
}
echo "</tbody></table>";
?><file_sep>/js/provincias/getLocalidades.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php");
/*Me traigo el codigo Provincia seleccionado, el codigo provincia es la referencia a cada Provincia de la BBDD*/
$codigoProvincia = $_GET['codigoProvincia'];
$datosJSON;
$_localidades = DataManager::getLocalidades();
if (count($_localidades)) {
foreach ($_localidades as $k => $_loc) {
if ($codigoProvincia == $_loc["locidprov"]){
$datosJSON[] = $_loc["locnombre"];
}
}
}
/*una vez tenemos un array con los datos los mandamos por json a la web*/
header('Content-type: application/json');
echo json_encode($datosJSON);
?><file_sep>/pedidos/logica/jquery/jquery.aprobar.js
$(document).ready(function() {
"use strict";
$("#aprobar").click(function () { // desencadenar evento cuando se hace clic en el botón
dac_aprobarPedido(0);
// prevenir botón redireccionamiento a nueva página
return false;
});
$("#rechazar").click(function () { // desencadenar evento cuando se hace clic en el botón
dac_aprobarPedido(2);
// prevenir botón redireccionamiento a nueva página
return false;
});
//--------------------------------
$("#aprobarPropuesta").click(function () {
dac_aprobarPropuesta(2);
return false;
});
$("#rechazarPropuesta").click(function () {
dac_aprobarPropuesta(3);
return false;
});
//--------------------------------
function dac_aprobarPedido(estado) {
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
var nropedido = $('input[name="nropedido"]:text').val();
$.ajax({
type: "POST",
url: "/pedidos/pedidos/logica/ajax/aprobar.pedido.php",
data: { nropedido : nropedido,
estado : estado },
beforeSend: function(){
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success: function(result) {
if (result){
$('#box_cargando').css({'display':'none'});
if(result.replace("\n","") === '1'){
$('#box_error').css({'display':'block'});
$("#msg_error").html("El pedido ha sido autorizado");
window.close();
} else {
if(result.replace("\n","") === '2'){
$('#box_error').css({'display':'block'});
$("#msg_error").html("El pedido fue rechazado");
window.close();
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
}
}
},
error : function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error en el proceso.");
}
});
}
//-------------------------------
function dac_aprobarPropuesta(estado) {
var propuesta = $('input[name="propuesta"]:text').val();
$.ajax({
type: "POST",
url: "/pedidos/pedidos/logica/ajax/aprobar.propuesta.php",
data: { propuesta : propuesta,
estado : estado
},
beforeSend: function(){
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success: function(result) {
if (result){
$('#box_cargando').css({'display':'none'});
if(result.replace("\n","") === '1'){
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html("Proceso finalizado.");
parent.history.back();
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
}
},
error : function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error en el proceso.");
}
});
}
});<file_sep>/cuentas/logica/ajax/getFiltroCuentas.php
<?php
//Matar sesión para probar como hacer que se cierre bien!!!
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
$usrZonas = isset($_SESSION["_usrzonas"]) ? $_SESSION["_usrzonas"] : '';
$field = (isset($_POST['tipo'])) ? $_POST['tipo'] : NULL;
$filtro = (isset($_POST['filtro'])) ? $_POST['filtro'] : '';
if(empty($filtro)){
echo "Debe indicar un texto para filtrar la búsqueda"; exit;
} else {
$filtro = '%'.$filtro.'%';
}
if(empty($usrZonas)){
echo "No dispone de zonas asignadas para consultar cuentas"; exit;
}
//------------------------------
$cuentas = DataManager::getCuentaAll('*', $field, $filtro, NULL, $usrZonas);
echo "<table id=\"tblFiltroCuentas\" style=\"table-layout:fixed;\">";
if (count($cuentas)) {
echo "<thead><tr align=\"left\"><th>Emp</th><th>Tipo</th><th>Cuenta</th><th>Nombre</th><th>Cuit</th></tr></thead>";
echo "<tbody>";
foreach ($cuentas as $k => $cuenta) {
$id = $cuenta['ctaid'];
$idCuenta = $cuenta['ctaidcuenta'];
$tipo = $cuenta['ctatipo'];
$idEmpresa = $cuenta['ctaidempresa'];
$empActiva = DataManager::getEmpresa('empactiva', $idEmpresa);
if($empActiva){
$empresa = substr(DataManager::getEmpresa('empnombre', $idEmpresa), 0, 3);
$cuit = $cuenta['ctacuit'];
$nombre = $cuenta['ctanombre'];
$_editar = sprintf( "onclick=\"window.open('editar.php?ctaid=%d')\" style=\"cursor:pointer;\"",$id);
$_status = ($cuenta['ctaactiva']) ? "<img class=\"icon-status-active\" title=\"Activa\" style=\"cursor:pointer;\" onclick=\"javascript:dac_changeStatus('/pedidos/cuentas/logica/changestatus.php', $id)\"/>" : "<img class=\"icon-status-inactive\" title=\"Inactiva\" onclick=\"javascript:dac_changeStatus('/pedidos/cuentas/logica/changestatus.php', $id)\"/>";
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class=".$clase.">";
echo "<td ".$_editar.">".$empresa."</td><td ".$_editar.">".$tipo."</td><td ".$_editar.">".$idCuenta."</td><td ".$_editar.">".$nombre."</td><td ".$_editar.">".$cuit."</td><td align=\"center\">".$_status."</td>";
echo "</tr>";
}
}
} else {
echo "<tbody>";
echo "<thead><tr><th colspan=\"5\" align=\"center\">No hay registros relacionadas</th></tr></thead>"; exit;
}
echo "</tbody></table>";
?><file_sep>/includes/PHPExcel/PHPDacExcel.php
<?php
/**
* Version 1.1
* Updated: 26 Dec 2010
*/
include_once 'PHPExcel.php';
class PHPDacExcel {
/**
* Converts an excel to array
* @param unknown_type $filename
*/
static function xls2array($filename) {
$objReader = new PHPExcel_Reader_Excel5 ();
$objReader->setReadDataOnly ( true );
$obj = $objReader->load ( $filename );
$cells = $obj->getActiveSheet ()->getCellCollection ();
$coords = array ();
foreach ( $cells as $cell ) {
$value = $obj->getActiveSheet ()->getCell ( $cell )->getValue ();
$coord = PHPExcel_Cell::coordinateFromString ( $cell );
$col = $coord [1] - 1;
$row = PHPExcel_Cell::columnIndexFromString ( $coord [0] ) - 1;
$coords [$col] [$row] = $value;
}
return $coords;
}
/**
* Converts an excel to array
* @param unknown_type $filename
*/
static function csv2array($filename, $delimiter=";") {
$result = array();
//echo "arranca";
if ($content = file_get_contents($filename) ){
//echo "open";
$rows = explode("\r\n", $content);
foreach ($rows as $row) {
//echo "row|";
$cells = explode($delimiter, $row);
if ( is_array($cells) && count($cells) > 1 ) {
$result[] = $cells;
}
}
}
//var_dump($result) ;
return $result ;
}
/**
*
* Converts Array to SQL INSERT statement
*
* @param array $array
* @param array $columns - Column map (null to avoid certain columns)
* @param string $table - Name of the table to be inserted
* @param array $parameters - associative array of key-values
*/
static function array2sql($array, $columns, $table, $parameters = array()) {
extract($parameters);// $limit, $start
if (!isset($start)) $start = 0 ;
$sql = "INSERT into $table (" . implode ( ",", array_filter ( $columns, 'is_string' ) ) . ") VALUES ";
$i = 0 ;
foreach ( $array as $row_num => $row ) {
$i++;
if ( $i <= $start) continue;
if ( isset($limit) && $i > $start + $limit) break;
$sql .= "(";
foreach ( $row as $col_num => $cell ) {
if (isset($columns [$col_num])) {
$sql .= "'$cell',";
}
}
$sql = substr ( $sql, 0, - 1 );
$sql .= "),";
}
$sql= substr($sql, 0, -1);
return $sql;
}
static function xls2sql($filename, $columns, $table, $parameters) {
return self::array2sql(self::xls2array($filename), $columns, $table, $parameters);
}
}<file_sep>/juegos/SlotMachine/jquery/jquery.ventana.js
//Carga la ventana
$(document).ready(function() {
"use strict";
$('#abrir-slotmachine').click(function(){
$('#slotmachine').fadeIn('slow');
$('#slotmachine').css({
'width': '100%',
'height': '100%',
'left': ($(window).width() / 2 - $(slotmachine).width() / 2) + 'px',
'top': ($(window).height() / 2 - $(slotmachine).height() / 2) + 'px'
});
$('#juego').fadeIn('slow');
return false;
});
$('#cerrar-slotmachine').click(function(){
$('#slotmachine').fadeOut('slow');
return false;
});
//**********************************//
$(window).resize();
});
$(window).resize(function () {
"use strict";
$('#slotmachine').css({
'width': '100%',
'height': '100%',
'left': ($(window).width() / 2 - $(slotmachine).width() / 2) + 'px',
'top': ($(window).height() / 2 - $(slotmachine).height() / 2) + 'px'
});
});
<file_sep>/pedidos/logica/ajax/update.pedido.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$usrAsignado = (isset($_POST['pwusrasignado'])) ? $_POST['pwusrasignado'] : NULL;
$empresa = (isset($_POST['empselect'])) ? $_POST['empselect'] : NULL;
$laboratorio = (isset($_POST['labselect'])) ? $_POST['labselect'] : NULL;
$idCuenta = (isset($_POST['pwidcta'])) ? $_POST['pwidcta'] : NULL;
$nroOrden = (isset($_POST['pworden'])) ? $_POST['pworden'] : NULL;
$condPago = (isset($_POST['condselect'])) ? $_POST['condselect'] : NULL;
$observacion = (isset($_POST['pwobservacion'])) ? $_POST['pwobservacion'] : NULL;
$idCondComercial= (isset($_POST['pwidcondcomercial']))? $_POST['pwidcondcomercial'] : NULL;
$propuesta = (isset($_POST['pwpropuesta'])) ? $_POST['pwpropuesta'] : NULL;
$idPropuesta = (isset($_POST['pwidpropuesta'])) ? $_POST['pwidpropuesta'] : NULL;
$estado = (isset($_POST['pwestado'])) ? $_POST['pwestado'] : NULL; //estado de la propuesta
$articulosIdArt = (isset($_POST['pwidart'])) ? $_POST['pwidart'] : NULL;
$articulosCant = (isset($_POST['pwcant'])) ? $_POST['pwcant'] : NULL;
$articulosPrecio= (isset($_POST['pwprecioart'])) ? $_POST['pwprecioart'] : NULL;
$articulosB1 = (isset($_POST['pwbonif1'])) ? $_POST['pwbonif1'] : NULL;
$articulosB2 = (isset($_POST['pwbonif2'])) ? $_POST['pwbonif2'] : NULL;
$articulosD1 = (isset($_POST['pwdesc1'])) ? $_POST['pwdesc1'] : NULL;
$articulosD2 = (isset($_POST['pwdesc2'])) ? $_POST['pwdesc2'] : NULL;
$tipoPedido = (isset($_POST['pwtipo'])) ? $_POST['pwtipo'] : NULL;
$lista = (isset($_POST['pwlista'])) ? $_POST['pwlista'] : 0;
//-----------------------//
// Controles Generales //
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/pedidos/logica/ajax/controlPedido.php" );
//-----------------------------------------------------------------------//
// Estados de un PEDIDO
//-Un pedido con $idCondComercial, pasará directo como CIERRE
//-Si es PROPUESTA: pasa por PROPUESTA - PENDIENTE - APROBADO/RECHAZADO - CIERRE
//-Si es APROBADO: podrá: CIERRE (pedido enviado) - ELIMINAR (eliminará el pedido pero no los registros de estados de las propuestas) - EDITAR (volviendo a PENDIENTE)
//-Si es RECHAZADO podrá: ELIMINAR o EDITAR (volviendo a pasar a PENDIENTE)
if($propuesta) {
//Si es una propuesta, NO SE GRABA UN NÚMERO DE PEDIDO, se crea una PROPUESTA
switch($estado){
case '0': //CERRADA
//Ya fue emitida como pedido (pre-facturada).
echo "La propuesta fue CERRADA, no puede modificarla. Realice un nuevo pedido."; exit;
break;
case '1':
//PENDIENTE
//Si se envía estando PENDIENTE, significaría que se realizaron cambios,
//por lo que habría que pasar la propuesta a Rechazada y se crearía una nueva,
//pendiente a aprobar.
//Pasa la propuesta actual a RECHAZADA y de INSERTA UNA NUEVA PROPUESTA
$propuestaObject = DataManager::newObjectOfClass('TPropuesta', $idPropuesta);
$propuestaObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$propuestaObject->__set('LastUpdate' , date("Y-m-d H:i:s"));
$propuestaObject->__set('FechaCierre' , date("2001-01-01"));
$propuestaObject->__set('Estado' , 3); //Pasa a RECHAZADA
$propuestaObject->__set('Activa' , 0);
DataManager::updateSimpleObject($propuestaObject);
//Cargo el ESTADO de la propuesta RECHAZADA
$estadoObject = DataManager::newObjectOfClass('TEstado');
$estadoObject->__set('Origen' , 'TPropuesta');
$estadoObject->__set('IDOrigen' , $idPropuesta);
$estadoObject->__set('Fecha' , date("Y-m-d H:i:s"));
$estadoObject->__set('UsrCreate', $_SESSION["_usrid"]);
$estadoObject->__set('Estado' , 3);
$estadoObject->__set('Nombre' , 'Pendiente');
$estadoObject->__set('ID' , $estadoObject->__newID());
$IDEst = DataManager::insertSimpleObject($estadoObject);
if(empty($IDEst)){
echo "No se grabó correctamente el estado de la propuesta."; exit;
}
//-------------------------//
//CREA UNA PROPUESTA NUEVA
$propuestaObject = DataManager::newObjectOfClass('TPropuesta');
$propuestaObject->__set('Nombre' , 'Pedido');
$propuestaObject->__set('Tipo' , 'Venta');
$propuestaObject->__set('Estado' , 1);
$propuestaObject->__set('Cuenta' , $idCuenta);
$propuestaObject->__set('Empresa' , $empresa);
$propuestaObject->__set('Laboratorio' , $laboratorio);
$propuestaObject->__set('Fecha' , date("Y-m-d H:i:s"));
$propuestaObject->__set('FechaCierre' , date("2001-01-01"));
$observacion = substr($observacion, 0, 250);
$propuestaObject->__set('Observacion' , $observacion);
$propuestaObject->__set('UsrCreate' , $_SESSION["_usrid"]);
$propuestaObject->__set('UsrAsignado' , $usrAsignado);
$propuestaObject->__set('LastUpdate' , date("Y-m-d H:i:s"));
$propuestaObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$propuestaObject->__set('Activa' , 1); //Queda activo porque aún no está APROBADA
$propuestaObject->__set('ID' , $propuestaObject->__newID());
$IDProp = DataManager::insertSimpleObject($propuestaObject);
if(empty($IDProp)){
echo "No se grabó correctamente la propuesta."; exit;
}
for($i = 0; $i < count($articulosIdArt); $i++){
$cant = $articulosCant[$i];
$idArt = $articulosIdArt[$i];
$b1 = empty($articulosB1[$i]) ? 0 : $articulosB1[$i];
$b2 = empty($articulosB2[$i]) ? 0 : $articulosB2[$i];
$d1 = empty($articulosD1[$i]) ? 0 : $articulosD1[$i];
$d2 = empty($articulosD2[$i]) ? 0 : $articulosD2[$i];
$precio = empty($articulosPrecio[$i]) ? 0 : $articulosPrecio[$i];
$propDetalleObject = DataManager::newObjectOfClass('TPropuestaDetalle');
$propDetalleObject->__set('IDPropuesta' , $IDProp);
$propDetalleObject->__set('CondicionPago' , $condPago);
$propDetalleObject->__set('IDArt' , $idArt);
$propDetalleObject->__set('Cantidad' , $cant);
$propDetalleObject->__set('Precio' , $precio);
$propDetalleObject->__set('Bonificacion1' , $b1);
$propDetalleObject->__set('Bonificacion2' , $b2);
$propDetalleObject->__set('Descuento1' , $d1);
$propDetalleObject->__set('Descuento2' , $d2);
$propDetalleObject->__set('Estado' , 1);
$propDetalleObject->__set('Fecha' , date("Y-m-d H:i:s"));
$propDetalleObject->__set('Activo' , 1);
$propDetalleObject->__set('ID' , $propDetalleObject->__newID());
$IDProrDet = DataManager::insertSimpleObject($propDetalleObject);
if(empty($IDProrDet)){
echo "No se grabaron correctamente los artículos."; exit;
}
}
//Cargo el ESTADO de la propuesta PENDIENTE
$estadoObject = DataManager::newObjectOfClass('TEstado');
$estadoObject->__set('Origen' , 'TPropuesta');
$estadoObject->__set('IDOrigen' , $IDProp);
$estadoObject->__set('Fecha' , date("Y-m-d H:i:s"));
$estadoObject->__set('UsrCreate', $_SESSION["_usrid"]);
$estadoObject->__set('Estado' , 1); //pendiente
$estadoObject->__set('Nombre' , 'Pendiente');
$estadoObject->__set('ID' , $estadoObject->__newID());
$IDEst = DataManager::insertSimpleObject($estadoObject);
if(empty($IDEst)){
echo "No se grabó correctamente el estado de la propuesta."; exit;
}
echo "1"; exit; //echo "queda PENDIENTE de Aprobar/Rechazar.";
break;
case '2': //APROBADO
//Si la propuesta está aprobada, consulta y carga los datos del pedido y cambia el estado a CERRADA
$propuestaObject= DataManager::newObjectOfClass('TPropuesta', $idPropuesta);
$idCuenta = $propuestaObject->__get('Cuenta');
$empresa = $propuestaObject->__get('Empresa');
$laboratorio = $propuestaObject->__get('Laboratorio');
$usrAsignado = $propuestaObject->__get('UsrAsignado');
$observacion = "PROPUESTA ".$idPropuesta.": ".$observacion;
$observacion = substr($observacion, 0, 250);
$propuestaObject->__set('Observacion' , $observacion);
$propuestaObject->__set('FechaCierre' , date("Y-m-d H:i:s"));
$propuestaObject->__set('Estado' , 0);
$propuestaObject->__set('Activa' , 0);
//Queda activo porque aún no está APROBADA
DataManager::updateSimpleObject($propuestaObject);
//Cargo el ESTADO de la propuesta a CERRADA
$estadoObject = DataManager::newObjectOfClass('TEstado');
$estadoObject->__set('Origen' , 'TPropuesta');
$estadoObject->__set('IDOrigen' , $idPropuesta);
$estadoObject->__set('Fecha' , date("Y-m-d H:i:s"));
$estadoObject->__set('UsrCreate', $_SESSION["_usrid"]);
$estadoObject->__set('Estado' , 0); //cerrado
$estadoObject->__set('Nombre' , 'Cerrado');
$estadoObject->__set('ID' , $estadoObject->__newID());
$IDEst = DataManager::insertSimpleObject($estadoObject);
if(empty($IDEst)){
echo "No se grabó correctamente el CIERRE de la propuesta."; exit;
}
$detalles = DataManager::getPropuestaDetalle($idPropuesta);
if ($detalles) {
unset($articulosIdArt, $articulosCant, $articulosPrecio, $articulosB1, $articulosB2, $articulosD1, $articulosD2);
foreach ($detalles as $j => $det) {
$condPago = $det["pdcondpago"];
$articulosIdArt[] = $det['pdidart'];
$articulosCant[] = $det['pdcantidad'];
$articulosPrecio[] = round($det['pdprecio'], 3);
$articulosB1[] = ($det['pdbonif1'] == 0) ? '' : $det['pdbonif1'];
$articulosB2[] = ($det['pdbonif2'] == 0) ? '' : $det['pdbonif2'];
$articulosD1[] = ($det['pddesc1'] == 0) ? '' : $det['pddesc1'];
$articulosD2[] = ($det['pddesc2'] == 0) ? '' : $det['pddesc2'];
}
}
break;
case '3': //RECHAZADA
//Si el pedido fue RECHAZADO deberá crear una nueva propuesta.
echo "La propuesta ya fue RECHAZADA. Cree una nueva propuesta si lo desea."; exit;
break;
default:
//CREA PROPUESTA
//Al inicio $estado no está definico, por lo que se crea la propuesta
$propuestaObject = DataManager::newObjectOfClass('TPropuesta');
$propuestaObject->__set('Nombre' , 'Pedido');
$propuestaObject->__set('Tipo' , 'Venta');
$propuestaObject->__set('Estado' , 1);
$propuestaObject->__set('Cuenta' , $idCuenta);
$propuestaObject->__set('Empresa' , $empresa);
$propuestaObject->__set('Laboratorio' , $laboratorio);
$propuestaObject->__set('Fecha' , date("Y-m-d H:i:s"));
$propuestaObject->__set('FechaCierre' , date("2001-01-01"));
$observacion = substr($observacion, 0, 250);
$propuestaObject->__set('Observacion' , $observacion);
$propuestaObject->__set('UsrCreate' , $_SESSION["_usrid"]);
$propuestaObject->__set('UsrAsignado' , $usrAsignado);
$propuestaObject->__set('LastUpdate' , date("Y-m-d H:i:s"));
$propuestaObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$propuestaObject->__set('Activa' , 1); //Queda activo porque aún no está APROBADA
$propuestaObject->__set('ID' , $propuestaObject->__newID());
$IDProp = DataManager::insertSimpleObject($propuestaObject);
if(empty($IDProp)){
echo "No se grabó correctamente la propuesta."; exit;
}
for($i = 0; $i < count($articulosIdArt); $i++){
$cant = $articulosCant[$i];
$idArt = $articulosIdArt[$i];
$b1 = empty($articulosB1[$i]) ? 0 : $articulosB1[$i];
$b2 = empty($articulosB2[$i]) ? 0 : $articulosB2[$i];
$d1 = empty($articulosD1[$i]) ? 0 : $articulosD1[$i];
$d2 = empty($articulosD2[$i]) ? 0 : $articulosD2[$i];
$precio = empty($articulosPrecio[$i]) ? 0 : $articulosPrecio[$i];
$propDetalleObject = DataManager::newObjectOfClass('TPropuestaDetalle');
$propDetalleObject->__set('IDPropuesta' , $IDProp);
$propDetalleObject->__set('CondicionPago' , $condPago);
$propDetalleObject->__set('IDArt' , $idArt);
$propDetalleObject->__set('Cantidad' , $cant);
$propDetalleObject->__set('Precio' , $precio);
$propDetalleObject->__set('Bonificacion1' , $b1);
$propDetalleObject->__set('Bonificacion2' , $b2);
$propDetalleObject->__set('Descuento1' , $d1);
$propDetalleObject->__set('Descuento2' , $d2);
$propDetalleObject->__set('Estado' , 1);
$propDetalleObject->__set('Fecha' , date("Y-m-d H:i:s"));
$propDetalleObject->__set('Activo' , 1);
$propDetalleObject->__set('ID' , $propDetalleObject->__newID());
$IDProrDet = DataManager::insertSimpleObject($propDetalleObject);
if(empty($IDProrDet)){
echo "No se grabaron correctamente los artículos."; exit;
}
}
//Cargo el ESTADO de la propuesta PENDIENTE
$estadoObject = DataManager::newObjectOfClass('TEstado');
$estadoObject->__set('Origen' , 'TPropuesta');
$estadoObject->__set('IDOrigen' , $IDProp);
$estadoObject->__set('Fecha' , date("Y-m-d H:i:s"));
$estadoObject->__set('UsrCreate', $_SESSION["_usrid"]);
$estadoObject->__set('Estado' , 1); //pendiente
$estadoObject->__set('Nombre' , 'Pendiente');
$estadoObject->__set('ID' , $estadoObject->__newID());
$IDEst = DataManager::insertSimpleObject($estadoObject);
if(empty($IDEst)){
echo "No se grabó correctamente el estado de la propuesta."; exit;
}
echo "1"; exit;//echo "Propuesta creada"; exit;
break;
}
} else {
$estado = 0; //CERRADO
}
//-------------------//
// Generar Pedido //
require($_SERVER['DOCUMENT_ROOT']."/pedidos/pedidos/logica/ajax/generarPedido.php" );
echo "1"; exit; ?><file_sep>/relevamiento/lista.php
<div class="box_body"> <!-- datos -->
<?php
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/relevamiento/': $_REQUEST['backURL'];
$_LPP = 1000;
$_total = DataManager::getNumeroFilasTotales('TRelevamiento', 0);
$_paginas = ceil($_total/$_LPP);
$_pag = isset($_REQUEST['pag']) ? min(max(1,$_REQUEST['pag']),$_paginas) : 1;
$_GOFirst = sprintf("<a class=\"icon-go-first\" href=\"%s?pag=%d\"></a>", $backURL, 1);
$_GOPrev = sprintf("<a class=\"icon-go-previous\" href=\"%s?pag=%d\"></a>", $backURL, $_pag-1);
$_GONext = sprintf("<a class=\"icon-go-next\" href=\"%s?pag=%d\"></a>", $backURL, $_pag+1);
$_GOLast = sprintf("<a class=\"icon-go-last\" href=\"%s?pag=%d\"></a>", $backURL, $_paginas);
$btnNuevo = sprintf( "<a href=\"editar.php\" title=\"Nuevo\"><img class=\"icon-new\"/></a>");
?>
<div class="barra">
<div class="bloque_5">
<h1>Relevamiento</h1>
</div>
<div class="bloque_5">
<?php echo $btnNuevo; ?>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblRelevamientos">
<thead>
<tr>
<th scope="col" align="left" height="18">Relev</th>
<th scope="col" align="left" >Orden</th>
<th scope="col" align="left" >Pregunta</th>
<th scope="col" align="left" >Tipo Respuesta</th>
<th scope="colgroup" colspan="3" align="center" width="15">Acciones</th>
</tr>
</thead>
<?php
$_relevamientos = DataManager::getRelevamientos($_pag, $_LPP, NULL);
$_max = count($_relevamientos); // la última página vendrá incompleta
for( $k=0; $k < $_LPP; $k++ ) {
if ($k < $_max) {
$_rel = $_relevamientos[$k];
$_relid = $_rel['relid'];
$_nrorel = $_rel['relidrel'];
$_orden = $_rel['relpregorden'];
$_direccion = $_rel['relpregunta'];
$_etiporesp = $_rel['reltiporesp'];
$_status = ($_rel['relactivo']) ? "<img class=\"icon-status-active\"/>" : "<img class=\"icon-status-inactive\"/>";
$_borrar = sprintf( "<a href=\"logica/changestatus.php?relid=%d&backURL=%s&pag=%s\" title=\"Cambiar Estado\">%s</a>", $_relid, $_SERVER['PHP_SELF'], $_pag, $_status);
$_editar = sprintf( "<a href=\"editar.php?relid=%d&backURL=%s&pag=%s\" title=\"Editar Relevamiento\" target=\"_blank\">%s</a>", $_relid, $_SERVER['PHP_SELF'], $_pag, "<img class=\"icon-edit\"/>");
$_eliminar = sprintf ("<a href=\"logica/eliminar.relevamiento.php?relid=%d&backURL=%s&pag=%s\" title=\"Eliminar Relevamiento\" onclick=\"return confirm('¿Está Seguro que desea ELIMINAR EL RELEVAMIENTO?')\"> <img class=\"icon-delete\" /></a>", $_rel['relid'], $_SERVER['PHP_SELF'], $_pag, "Eliminar");
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_nrorel, $_orden, $_direccion, $_etiporesp, $_editar, $_borrar, $_eliminar);
echo sprintf("</tr>");
} else {
$_relid = " ";
$_nrorel = " ";
$_orden = " ";
$_direccion = " ";
$_etiporesp = " ";
$_editar = " ";
$_borrar = " ";
$_eliminar = " ";
}
} ?>
</table>
</div> <!-- Fin lista -->
<?php
if ( $_paginas > 1 ) {
$_First = ($_pag > 1) ? $_GOFirst : " ";
$_Prev = ($_pag > 1) ? $_GOPrev : " ";
$_Last = ($_pag < $_paginas) ? $_GOLast : " ";
$_Next = ($_pag < $_paginas) ? $_GONext : " ";
echo("<table class=\"paginador\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
echo sprintf("<td height=\"16\">Mostrando página %d de %d</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td>", $_pag, $_paginas, $_First, $_Prev, $_Next, $_Last);
echo("</tr></table>");
} ?>
</div> <!-- Fin datos -->
<file_sep>/transfer/gestion/liquidacion/logica/importar_liq.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php" );
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/PHPExcel/PHPDacExcel.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_drogueria = empty($_POST['drog']) ? 0 : $_POST['drog'];
$_fecha_liq = empty($_POST['fecha_liq']) ? 0 : $_POST['fecha_liq'];
if ($_drogueria == 0){ echo "Error en la carga de la droguería"; }
if ($_fecha_liq == 0){ echo "Error en la carga de la fecha de liquidación."; }
$_fecha_l = dac_invertirFecha($_fecha_liq);
$mensage = '';//Declaramos una variable mensaje que almacenara el resultado de las operaciones.
if ($_FILES){
foreach ($_FILES as $key){ //Iteramos el arreglo de archivos
if($key['error'] == UPLOAD_ERR_OK ){//Si el archivo se paso correctamente Continuamos
$archivo_temp = $key['tmp_name']; //Obtenemos la ruta Original del archivo
//$options = array ('start' => 1, 'limit'=>5);
//$array = PHPDacExcel::xls2sql( $archivo_temp, array ("liqid", "liqdrogid", "liqfechafact", "liqnrofact", "liqean", "liqcant", "liqunitario", "liqdescuento", "liqimportenc"), "liquidacion", $options );
//antes de importar el EXCEL debería eliminar en esa fecha y droguería, cualquier dato existente.
$_liqobject = DataManager::deleteFromLiquidacion($_drogueria, $_fecha_l, 'TL');
//Convierto el excel en un array de arrays
$arrayxls = PHPDacExcel::xls2array($archivo_temp);
for($j=1; $j < count($arrayxls); $j++){
if(count($arrayxls[$j]) != 9){
echo 'Está intentando importar un archivo con diferente cantidad de campos (deben ser 9)'; exit;
} else {
//procedo a cargar los datos
$_liqobject = DataManager::newObjectOfClass('TLiquidacion');
$_liqobject->__set('ID', $_liqobject->__newID());
$_liqobject->__set('Drogueria', $_drogueria); //$arrayxls[$j][0]
$_liqobject->__set('Tipo' , 'TL');
$_liqobject->__set('Transfer', $arrayxls[$j][1]);
// La fecha la toma en número por lo que la convierto a fecha nuevamente
$fechafact = date("Y-m-d", mktime(null, null, null, null, $arrayxls[$j][2] - '36494', null, null));
$_liqobject->__set('FechaFact', $fechafact);
$_liqobject->__set('NroFact', $arrayxls[$j][3]);
$_liqobject->__set('EAN', str_replace(" ", "", $arrayxls[$j][4]));
$_liqobject->__set('Cantidad', $arrayxls[$j][5]);
$_liqobject->__set('Unitario', $arrayxls[$j][6]);
//Buscar y Reemplazar el símbolo % por vacío
$_liqobject->__set('Descuento', str_replace("%", "", $arrayxls[$j][7]));
$_liqobject->__set('ImporteNC', $arrayxls[$j][8]);
$_liqobject->__set('Fecha', $_fecha_l);
$_liqobject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$_liqobject->__set('LastUpdate' , date("Y-m-d H:m:s"));
$ID = DataManager::insertSimpleObject($_liqobject);
}
}
}
if ($key['error']==''){ //Si no existio ningun error, retornamos un mensaje por cada archivo subido
$mensage .= 'Archivo Subido correctamente con '.(count($arrayxls)-1).' registros';
} else {
//if ($key['error']!=''){//Si existio algún error retornamos un el error por cada archivo.
$mensage .= '-> No se pudo subir el archivo debido al siguiente Error: \n'.$key['error'];
}
}
} else { $mensage .= 'Debe seleccionar algún archivo para enviar.'; }
echo $mensage;// Regresamos los mensajes generados al cliente
?><file_sep>/planificacion/logica/ajax/duplicar.planificacion.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//*******************************************
$_fecha_origen = (isset($_POST['fecha_origen'])) ? $_POST['fecha_origen'] : NULL;
$_fecha_destino = (isset($_POST['fecha_destino'])) ? $_POST['fecha_destino'] : NULL;
//*************************************************
//Controles
//*************************************************
if (empty($_fecha_destino)){
echo "Debe seleccionar una fecha de destino"; exit;
}
$_planificado_destino = DataManager::getDetallePlanificacion($_fecha_destino, $_SESSION["_usrid"]);
if (count($_planificado_destino) > 0){
echo "Imposible duplicar. Ya existen datos en la fecha ".$_fecha_destino." de destino indicada"; exit;
}
//*************************************************
//Duplicado de registros
//*************************************************
$date = $_fecha_destino;
list($día, $mes, $año) = explode('-', str_replace('/', '-', $date));
$_fecha_destino = $año."-".$mes."-".$día;
$_planificado_origen = DataManager::getDetallePlanificacion($_fecha_origen, $_SESSION["_usrid"]);
if (count($_planificado_origen)){
foreach ($_planificado_origen as $k => $_planiforig){
$_planiforig = $_planificado_origen[$k];
$_planiforigcliente = $_planiforig["planifidcliente"];
$_planiforignombre = $_planiforig["planifclinombre"];
$_planiforigdir = $_planiforig["planifclidireccion"];
/*se graba el duplicado*/
$_planifobjectdest = DataManager::newObjectOfClass('TPlanificacion');
$_planifobjectdest->__set('ID' , $_planifobjectdest->__newID());
$_planifobjectdest->__set('IDVendedor' , $_SESSION["_usrid"]);
$_planifobjectdest->__set('Fecha' , $_fecha_destino);
$_planifobjectdest->__set('Cliente' , $_planiforigcliente);
$_planifobjectdest->__set('Nombre' , $_planiforignombre);
$_planifobjectdest->__set('Direccion' , $_planiforigdir);
$_planifobjectdest->__set('Envio' , date("2001-01-01 00:00:00"));
$_planifobjectdest->__set('Activa' , '1');
$ID = DataManager::insertSimpleObject($_planifobjectdest);
if (empty($ID)) {
echo "Error de duplicado. $ID."; exit;
}
}
} else {
echo "No se verifica que haya datos para duplicar en la fecha de origen"; exit;
}
echo "Se ha duplicado la planificación";
?><file_sep>/articulos/logica/ajax/calcularPrecios.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$artId = (isset($_POST['artId'])) ? $_POST['artId'] : NULL;
$empresa = (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
$laboratorio= (isset($_POST['laboratorio'])) ? $_POST['laboratorio'] : NULL;
$iva = (isset($_POST['iva'])) ? $_POST['iva'] : NULL;
$medicinal = (isset($_POST['medicinal'])) ? $_POST['medicinal'] : NULL;
$precioVenta= (isset($_POST['precioVenta'])) ? $_POST['precioVenta'] : NULL;
$porcGanancia= (isset($_POST['porcentaje'])) ? $_POST['porcentaje'] : NULL;
if(!is_numeric($precioVenta) || $precioVenta <= 0){
echo "Debe ingresar un precio de Venta"; exit;
}
if(empty($empresa)){
echo "Seleccione empresa"; exit;
}
if(empty($laboratorio)){
echo "Seleccione laboratorio"; exit;
}
$precioLista= floatval($precioVenta)/floatval(1.450);
//----------------
if($empresa == 3){
if($medicinal == 'true'){
$precioLista= $precioLista/floatval(1.210);
}
}
$precioArt = $precioLista / floatval(1.210);
//----------------------
$dto = 0;
$porBonif = 0;
$divBonif = 0;
if($artId){
$condicionesCompra = DataManagerHiper::getCondCompra($empresa, $laboratorio, $artId);
if($condicionesCompra){
foreach ($condicionesCompra as $k => $condCompra) {
$dto = $condCompra["Descuento"];
$porBonif = $condCompra["PorBonif"];
$divBonif = $condCompra["DivBonif"];
}
}
}
$presCompra = 0;
$presVenta = 0;
if($artId){
$equivalenciaUnidades = DataManagerHiper::getEquivUnid($empresa, $laboratorio, $artId);
if($equivalenciaUnidades){
foreach ($equivalenciaUnidades as $k => $equivUnid) {
$presCompra = $equivUnid["PresCompra"];
$presVenta = $equivUnid["PresVenta"];
}
}
}
$iva1 = 0;
$empresas = DataManagerHiper::getEmpresas($empresa);
if($empresas) {
foreach ($empresas as $k => $emp) {
$iva1 = $emp["Iva1Emp"];
}
}
$ivaResult = ($iva1 / 100 ) + 1;
$precioCom = 0;
$precioRep = 0;
//Calculo con descuentos
$precioCom = $precioArt;
if($dto <> 0){
$desc = ($precioArt * $dto) / 100;
$precioCom = $precioCom - $desc;
}
if($porBonif <> 0) { $precioCom = $precioCom * $porBonif; }
if($divBonif <> 0) { $precioCom = $precioCom / $divBonif; }
if($presVenta <> 0) { $precioCom = $precioCom / $presCompra;}
if($presCompra <> 0){ $precioCom = $precioCom * $presVenta; }
//---------------------------
if($iva == 'true') {
$precioCom = $precioCom * $ivaResult;
} else {
$precioLista= $precioLista / floatval(1.210);
}
if($medicinal == 'false'){
$precioCom = $precioCom / floatval(1.210);
$precioLista= $precioLista / floatval(1.210);
}
//porcentaje de ganancia
if(!empty($porcGanancia) && $porcGanancia <> "0.00"){
$porcGanancia= ($porcGanancia / 100) + 1;
$precioLista = $precioCom * $porcGanancia;
/*$porcGanancia = ($artGanancia / 100) + 1;
$artPrecioVenta = $artPrecioVenta / $porcGanancia;*/
}
$precioRep = $precioCom;
/*
if($empresa == 3){
$precioLista = $precioLista / floatval(1.210);
$precioCom = $precioCom / floatval(1.210);
$precioRep = $precioRep / floatval(1.210);
$precioArt = $precioArt / floatval(1.210);
}*/
$precioLista = number_format($precioLista,3,'.','');
$precioCom = number_format($precioCom,3,'.','');
$precioRep = number_format($precioRep,3,'.','');
$precioArt = number_format($precioArt,3,'.','');
echo "$precioLista/$precioCom/$precioRep/$precioArt"; exit;
?><file_sep>/agenda/ajax/setEvents.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
exit;
}
$eventData = (isset($_POST['eventData']))? $_POST['eventData'] : NULL;
$restringido = (empty($eventData['constraint']) ? NULL : $eventData['constraint']);
if(empty($eventData)){
echo "No se pudo cargar el evento"; exit;
}
if(empty($eventData['title'])){
echo "Indique motivo del evento."; exit;
}
if(empty($eventData['color'])){
$eventData['color'] = '3A87AD';
} else {
$eventData['color'] = str_replace("#", "", $eventData['color']);
}
$fechaI = explode( ' ', $eventData['start'] );
list($mesIni, $diaIni, $anoIni) = explode( '/', $fechaI[0]);
$fechaF = explode( ' ', $eventData['end'] );
list($mesFin, $diaFin, $anoFin) = explode( '/', $fechaF[0]);
$fechaInicio = new DateTime($anoIni."-".$mesIni."-".$diaIni." ".$fechaI[1]);
$fechaFin = new DateTime($anoFin."-".$mesFin."-".$diaFin." ".$fechaF[1]);
if($mesIni=="00" || $diaIni=="00" || $anoIni=="0000"){
echo "Indique fecha de Inicio correcta"; exit;
}
if($mesFin=="00" || $diaFin=="00" || $anoFin=="0000"){
echo "Indique fecha de Fin correcta"; exit;
}
if($fechaInicio >= $fechaFin){
echo "La fecha y hora de Fin debe ser menor a la Inicial."; exit;
}
$eventObject = ($eventData['id']) ? DataManager::newObjectOfClass('TAgenda', $eventData['id']) : DataManager::newObjectOfClass('TAgenda');
$eventObject->__set('IdUsr' , $_SESSION["_usrid"]);
$eventObject->__set('StartDate' , $fechaInicio->format("Y-m-d H:i:s"));
$eventObject->__set('EndDate' , $fechaFin->format("Y-m-d H:i:s"));
$eventObject->__set('Color' , $eventData['color']);
$eventObject->__set('Title' , $eventData['title']);
$eventObject->__set('Texto' , $eventData['texto']);
$eventObject->__set('Url' , (empty($eventData['url'])) ? '' : $eventData['url'] );
$eventObject->__set('Restringido' , $restringido);
$eventObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$eventObject->__set('LastUpdate' , date("Y-m-d H:i:s"));
$eventObject->__set('Activa' , 1);
if($eventData['id']){
$ID = DataManager::updateSimpleObject($eventObject);
} else {
$eventObject->__set('ID' , $eventObject->__newID());
$ID = DataManager::insertSimpleObject($eventObject);
}
echo $ID; exit;
?><file_sep>/informes/logica/exportar.tablacuentas.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=TablaCuentas-".date('d-m-y').".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos .::</TITLE>
<head></head>
<body>
<table border="0"> <?php
//consultar todas las zonas
$zonas = DataManager::getZonas();
if (count($zonas)) {
$stringZona = "'0'";
foreach ($zonas as $k => $zon) {
$nroZona = $zon["zzona"];
$stringZona = $stringZona.", '".$nroZona."'";
}
}
$registros = DataManager::getCuentas(0, 0, NULL, NULL, NULL, $stringZona, NULL);
if (count($registros)) {
$names = array_keys($registros[0]); ?>
<thead>
<tr> <?php
foreach ($names as $j => $name) {
?><td scope="col" ><?php echo $name; ?></td><?php
} ?>
</tr>
</thead> <?php
foreach ($registros as $k => $registro) {
echo sprintf("<tr align=\"left\">");
foreach ($names as $j => $name) {
switch($j){
case 13:
echo sprintf("<td style=\"mso-number-format:'@';\">%s</td>", $registro[$name]);
break;
case 24:
case 25:
case 48:
case 51:
echo sprintf("<td style=\"mso-number-format:'yyyy-mm-dd hh:mm:ss';\">%s</td>", $registro[$name]);
break;
default:
echo sprintf("<td >%s</td>", $registro[$name]);
break;
}
}
echo sprintf("</tr>");
}
} ?>
</table>
</body>
</html>
<file_sep>/pedidos/logica/ajax/controlCadena.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$usrAsignado = (isset($_POST['pwusrasignado'])) ? $_POST['pwusrasignado'] : NULL;
$empresa = (isset($_POST['empselect'])) ? $_POST['empselect'] : NULL;
$laboratorio = (isset($_POST['labselect'])) ? $_POST['labselect'] : NULL;
$idCuenta = (isset($_POST['pwidcta'])) ? $_POST['pwidcta'] : NULL;
$nroOrden = (isset($_POST['pworden'])) ? $_POST['pworden'] : NULL;
$condPago = (isset($_POST['condselect'])) ? $_POST['condselect'] : NULL;
$observacion = (isset($_POST['pwobservacion'])) ? $_POST['pwobservacion'] : NULL;
$idCondComercial= (isset($_POST['pwidcondcomercial']))? $_POST['pwidcondcomercial'] : NULL;
$propuesta = (isset($_POST['pwpropuesta'])) ? $_POST['pwpropuesta'] : NULL;
$idPropuesta = (isset($_POST['pwidpropuesta'])) ? $_POST['pwidpropuesta'] : NULL;
$estado = (isset($_POST['pwestado'])) ? $_POST['pwestado'] : NULL; //estado de la propuesta
$articulosIdArt = (isset($_POST['pwidart'])) ? $_POST['pwidart'] : NULL;
$articulosCant = (isset($_POST['pwcant'])) ? $_POST['pwcant'] : NULL;
$articulosPrecio= (isset($_POST['pwprecioart'])) ? $_POST['pwprecioart'] : NULL;
$articulosB1 = (isset($_POST['pwbonif1'])) ? $_POST['pwbonif1'] : NULL;
$articulosB2 = (isset($_POST['pwbonif2'])) ? $_POST['pwbonif2'] : NULL;
$articulosD1 = (isset($_POST['pwdesc1'])) ? $_POST['pwdesc1'] : NULL;
$articulosD2 = (isset($_POST['pwdesc2'])) ? $_POST['pwdesc2'] : NULL;
$tipoPedido = (isset($_POST['pwtipo'])) ? $_POST['pwtipo'] : NULL;
$lista = (isset($_POST['pwlista'])) ? $_POST['pwlista'] : 0;
//-----------------------//
// Controles Generales //
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/pedidos/logica/ajax/controlPedido.php" );
//Que cuenta pertenezca a una cadena
$cuentasCad = DataManager::getCuentasCadena($empresa, NULL, $idCuenta);
if (count($cuentasCad)) {
foreach ($cuentasCad as $j => $ctaCad) {
$idCadenaCad = $ctaCad['IdCadena'];
$tipoCadena = $ctaCad['TipoCadena'];
}
} else {
echo "La cuenta no corresponde a una cadena registrada."; exit;
}
echo "1"; exit;<file_sep>/proveedores/logica/update.proveedor.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$_provid = empty($_REQUEST['provid']) ? 0 : $_REQUEST['provid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/proveedores/': $_REQUEST['backURL'];
$_idempresa = $_POST['idempresa'];
$_idproveedor = $_POST['idproveedor'];
$_nombre = $_POST['nombre'];
$_direccion = $_POST['direccion'];
$_idprov = $_POST['idprovincia'];
$_idloc = $_POST['idloc'];
$_cp = $_POST['cp'];
$_cuit = $_POST['cuit'];
$_nroIBB = $_POST['nroIBB'];
$_correo = $_POST['correo'];
$_telefono = $_POST['telefono'];
$_observacion = $_POST['observacion'];
$_activo = $_POST['activo'];
$_SESSION['s_empresa'] = $_idempresa;
$_SESSION['s_idproveedor'] = $_idproveedor;
$_SESSION['s_nombre'] = $_nombre;
$_SESSION['s_direccion'] = $_direccion;
$_SESSION['s_provincia'] = $_idprov;
$_SESSION['s_localidad'] = $_idloc;
$_SESSION['s_cp'] = $_cp;
$_SESSION['s_cuit'] = $_cuit;
$_SESSION['s_nroIBB'] = $_nroIBB;
$_SESSION['s_correo'] = $_correo;
$_SESSION['s_telefono'] = $_telefono;
$_SESSION['s_observacion'] = $_observacion;
$_SESSION['s_activo'] = $_activo;
if (empty($_idempresa) || !is_numeric($_idempresa)) {
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 1);
header('Location:' . $_goURL);
exit;
}
if (empty($_idproveedor) || !is_numeric($_idproveedor)) {
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 2);
header('Location:' . $_goURL);
exit;
}
if (empty($_nombre)) {
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 3);
header('Location:' . $_goURL);
exit;
}
if (empty($_direccion)) {
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 4);
header('Location:' . $_goURL);
exit;
}
if (empty($_idprov) || !is_numeric($_idprov)) {
if($_idprov != 0){
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 5);
header('Location:' . $_goURL);
exit;
}
}
if (empty($_idloc)) { //|| !is_numeric($_idloc)
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 6);
header('Location:' . $_goURL);
exit;
}
if (!is_numeric($_cp)) {
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 7);
header('Location:' . $_goURL);
exit;
}
if (!dac_validarCuit($_cuit)) {
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 8);
header('Location:' . $_goURL);
exit;
}
$_cuit = dac_corregirCuit($_cuit);
//Si proveedor se está por registrar, controla que cuit no exista.
if($_activo == 3){
$_proveedores = DataManager::getProveedores(NULL, NULL, $_idempresa, NULL);
if($_proveedores){
foreach ($_proveedores as $k => $_prov) {
$_activoprov = $_prov['provactivo'];
if($_activoprov != 3){
$_cuitprov = dac_corregirCuit($_prov['provcuit']);
if($_cuitprov == $_cuit){
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 14);
header('Location:' . $_goURL);
exit;
}
}
}
foreach ($_proveedores as $k => $_prov){
$_activoprov = $_prov['provactivo'];
if($_activoprov != 3){
$_idempresaprov = $_prov['providempresa'];
$_providprov = $_prov['providprov'];
if(($_idempresaprov == $_idempresa) && ($_providprov == $_idproveedor)){
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 15);
header('Location:' . $_goURL);
exit;
}
}
}
}
}
if (empty($_correo) || !preg_match( "/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,4})$/", $_correo )) {
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 9);
header('Location:' . $_goURL);
exit;
}
if (empty($_telefono)) {
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 10);
header('Location:' . $_goURL);
exit;
}
$_provobject = ($_provid) ? DataManager::newObjectOfClass('TProveedor', $_provid) : DataManager::newObjectOfClass('TProveedor');
$_provobject->__set('Empresa', $_idempresa);
$_provobject->__set('Proveedor', $_idproveedor);
$_provobject->__set('Nombre', $_nombre);
$_provobject->__set('Direccion', $_direccion);
$_provobject->__set('Provincia', $_idprov);
$_provobject->__set('Localidad', $_idloc);
$_provobject->__set('CP', $_cp);
$_provobject->__set('Cuit', $_cuit);
$_provobject->__set('NroIBB', $_nroIBB);
$_provobject->__set('Email', $_correo);
$_provobject->__set('Telefono', $_telefono);
$_provobject->__set('Observacion', $_observacion);
if ($_provid) {
//Modifica Cliente
$ID = DataManager::updateSimpleObject($_provobject);
} else {
//Nuevo Proveedor
//***************************************//
//Controlo si ya existe proveedor en empresa
$_proveedor = DataManager::getProveedor('providprov', $_idproveedor, $_idempresa);
if ($_proveedor) {
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 2);
header('Location:' . $_goURL);
exit;
}
//***************************************//
$_provobject->__set('ID', $_provobject->__newID());
$_provobject->__set('Activo', 1);
$ID = DataManager::insertSimpleObject($_provobject);
}
unset($_SESSION['s_empresa']);
unset($_SESSION['s_idproveedor']);
unset($_SESSION['s_nombre']);
unset($_SESSION['s_direccion']);
unset($_SESSION['s_provincia']);
unset($_SESSION['s_localidad']);
unset($_SESSION['s_cp']);
unset($_SESSION['s_cuit']);
unset($_SESSION['s_nroIBB']);
unset($_SESSION['s_correo']);
unset($_SESSION['s_telefono']);
unset($_SESSION['s_observacion']);
unset($_SESSION['s_activo']);
header('Location:' . $backURL.'?pag='.$_pag);
?><file_sep>/includes/class/class.rendicion.php
<?php
require_once('class.PropertyObject.php');
class TRendicion extends PropertyObject {
protected $_tablename = 'rendicion';
protected $_fieldid = 'rendid';
protected $_fieldactivo = 'rendactiva';
protected $_timestamp = 0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'rendid'; //Relación con tabla "rend_rec" para IDRecibo
$this->propertyTable['Fecha'] = 'rendfecha';
$this->propertyTable['Numero'] = 'rendnumero';
$this->propertyTable['IdUsr'] = 'rendidusr'; //Relación con tabla "talonario_idusr" para NroTalonario
$this->propertyTable['NombreUsr'] = 'rendnombreusr';
$this->propertyTable['Retencion'] = 'rendretencion';
$this->propertyTable['Deposito'] = 'renddeposito';
$this->propertyTable['Envio'] = 'rendfechaenvio';
$this->propertyTable['Activa'] = 'rendactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function Autenticado() {
return $this->_autenticado;
}
public function __newID() {
// Devuelve '#petid' para el alta de un nuevo registro
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/transfer/gestion/abmtransferdrog/logica/update.abm.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_mes = (isset($_POST['mes_abm'])) ? $_POST['mes_abm'] : NULL;
$_anio = (isset($_POST['anio_abm'])) ? $_POST['anio_abm'] : NULL;
$_drogid = (isset($_POST['drogid'])) ? $_POST['drogid'] : NULL;
//Arrays
$_idabm = (isset($_POST['idabm'])) ? $_POST['idabm'] : NULL;
$_selectArt = (isset($_POST['art'])) ? $_POST['art'] : NULL;
$_descuento = (isset($_POST['desc'])) ? $_POST['desc'] : NULL;
$_plazo = (isset($_POST['plazoid'])) ? $_POST['plazoid'] : NULL;
$_difcompens= (isset($_POST['difcompens']))? $_POST['difcompens']: NULL;
/*****************/
//Control de Datos
/*****************/
if(empty($_drogid) || $_drogid==0){
echo "Debe seleccionar una droguería ".$_drogid; exit;
}
//Saco el valor de cada artículo y controlo que haya seleccionado uno
if(count($_selectArt)){
for($i=0; $i<count($_selectArt); $i++){
if(empty($_selectArt[$i])){
echo "Debe indicar un artículo en la fila ".($i+1); exit;
} /*else {
echo "asd: ".$_selectArt[$i]; exit;
list($_id, $_art) = explode(' - ', $_selectArt[$i]);
$_idart[] = $_id;
}*/
//Controlar que no haya repetido artículos
for($j=0; $j<count($_selectArt); $j++){
if($_selectArt[$i] == $_selectArt[$j]){
if($i != $j){
echo "El artículo ".$_selectArt[$i]." de la fila ".($i+1)." está repetido en la fila ".($j+1); exit;
}
}
}
//Realiza control de descuento
if(empty($_descuento[$i]) || !is_numeric($_descuento[$i])){
echo "Debe indicar un descuento correcto en la fila ".($i+1). " artículo ".$_selectArt[$i]; exit;
}
//Realiza control de plazos
if(empty($_plazo[$i]) || !is_numeric($_plazo[$i])){
echo "Debe indicar un plazo correcto en la fila ".($i+1). " artículo ".$_selectArt[$i]; exit;
}
//Realiza control de compensacion
if(empty($_difcompens[$i]) || !is_numeric($_difcompens[$i])){
echo "Debe indicar una diferencia de compensación correcta en la fila ".($i+1). " artículo ".$_selectArt[$i]; exit;
}
}
} else {
echo "Debe cargar algún artículo en el ABM."; exit;
}
//borro los registros que están en la ddbb y ya no están en la tabla
$_abms = DataManager::getDetalleAbm($_mes, $_anio, $_drogid, 'TD');
if ($_abms) {
foreach ($_abms as $k => $_abm){
$_abm = $_abms[$k];
$_abmID = $_abm['abmid'];
//busco artículo que no esté en la tabla
$encontrado = 0;
$i = 0;
while(($i<count($_selectArt)) && ($encontrado == 0)){
if(($_abmID == $_idabm[$i])){ $encontrado = 1; }
$i++;
}
if ($encontrado == 0){ //borrar de la ddbb $_abmID
$_abmobject = DataManager::newObjectOfClass('TAbm', $_abmID);
$_abmobject->__set('ID', $_abmID );
$ID = DataManager::deleteSimpleObject($_abmobject);
}
}
}
//Recorro nuevamente cada registro para grabar y/o insertar los nuevos registros de abm
//update para los que tengan IDabm e insert para los que no
$_activa = 0;
$movimiento = 'ERROR';
$movTipo = '';
for($i=0; $i<count($_selectArt); $i++){
$_abmid = empty($_idabm[$i]) ? 0 : $_idabm[$i];
$_abmobject = ($_abmid) ? DataManager::newObjectOfClass('TAbm', $_abmid) : DataManager::newObjectOfClass('TAbm');
$_abmobject->__set('Drogueria', $_drogid);
$_abmobject->__set('Articulo', $_selectArt[$i]);
$_abmobject->__set('Tipo', 'TD');
$_abmobject->__set('Mes', $_mes);
$_abmobject->__set('Anio', $_anio);
$_abmobject->__set('Descuento', $_descuento[$i]);
$_abmobject->__set('Plazo', $_plazo[$i]);
$_abmobject->__set('Diferencia', $_difcompens[$i]);
if($_abmobject->__get('Activo') == 1){ $_activa = 1;}
if ($_abmid) { //UPDATE ABM
$ID = DataManager::updateSimpleObject($_abmobject);
$movimiento = 'ABM_TD_DROG_'.$_drogid."_".$_mes."-".$_anio;
$movTipo = 'UPDATE';
} else { //INSERT ABM
if ($_activa == 1){ $_abmobject->__set('Activo', 1); }
$_abmobject->__set('ID', $_abmobject->__newID());
$ID = DataManager::insertSimpleObject($_abmobject);
$movimiento = 'ABM_TD_DROG_'.$_drogid."_".$_mes."-".$_anio;
$movTipo = 'INSERT';
}
}
//**********************//
//Registro de movimiento//
//**********************//
dac_registrarMovimiento($movimiento, $movTipo, "TAbm");
echo "1";
?><file_sep>/includes/class/class.proveedor.php
<?php
require_once('class.PropertyObject.php');
class TProveedor extends PropertyObject {
protected $_tablename = 'proveedor';
protected $_fieldid = 'provid';
protected $_fieldactivo = 'provactivo';
protected $_timestamp = 0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'provid';
$this->propertyTable['Empresa'] = 'providempresa';
$this->propertyTable['Proveedor'] = 'providprov';
$this->propertyTable['Login'] = 'provlogin';
$this->propertyTable['Clave'] = 'provclave';
$this->propertyTable['Web'] = 'provweb';
$this->propertyTable['Nombre'] = 'provnombre';
$this->propertyTable['Direccion'] = 'provdireccion';
$this->propertyTable['Provincia'] = 'providprovincia';
$this->propertyTable['Localidad'] = 'providloc';
$this->propertyTable['CP'] = 'provcp';
$this->propertyTable['Cuit'] = 'provcuit';
$this->propertyTable['NroIBB'] = 'provnroIBB';
$this->propertyTable['Telefono'] = 'provtelefono';
$this->propertyTable['Email'] = 'provcorreo';
$this->propertyTable['Observacion'] = 'provobservacion';
$this->propertyTable['Activo'] = 'provactivo';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->propertyTable['ID']);
}
public function __validate() {
return true;
}
private function setAuth($_status=false) {
$this->_autenticado = $_status;
}
public function login($_pwd) {
$this->setAuth(false);
$_status = (strcmp($_pwd, $this->__get('Clave')) == 0);
$this->setAuth($_status);
return $_status;
}
}
?><file_sep>/transfer/gestion/liquidaciondrog/logica/controles.liquidacion.php
<?php
$_CtrlPSLUnit = '';
$_CtrlDescPSL = '';
$_CtrlImpNT = '';
$_Estado = '';
if(!empty($_idart)){
//**************************//
//#2 Control "PSL Unitario" == a PrecioDrog de la Bonificacion de ese mes
//**************************//
$_bonifarticulo = DataManager::getBonificacionArticulo($_idart, $_mes, $_anio);
$_preciodrog = $_bonifarticulo[0]['bonifpreciodrog'];
$_bonifiva = $_bonifarticulo[0]['bonifiva'];
if(empty($_preciodrog)){
$_CtrlPSLUnit = "#ErrorPSLUnit </br>";
} else {
if($_preciodrog != $_liqunit){
//Si diferencia es > o < a 2%. la muestre
$_porc_dif = 100 - (($_liqunit * 100) / $_preciodrog);
if ($_porc_dif < -2 || $_porc_dif > 2) {
$_CtrlPSLUnit = "$_preciodrog";
}
}
//SI EL Producto es Cosmético, le vuelvo a retirar un 21%
if($_bonifiva != 0) {
$_preciodrog = round(($_preciodrog / 1.21),2);
}
if($_drogidemp == 3) {
$_preciodrog = round(($_preciodrog / 1.21),2); //$_preciodrog - ($_preciodrog * 0.21);
}
}
//***********************************//
//#3 Control "% Desc PSL" con "% Desc" del ABM
//***********************************//
$_abmart = DataManager::getDetalleArticuloAbm($_mes, $_anio, $_drogid, $_idart, 'TD');
if(!$_abmart){
echo "IMPORTANTE: No hay ABM cargado para la fecha que intenta importar."; exit;
}
$_abmdesc = $_abmart[0]['abmdesc'];
$_abmdifcomp = $_abmart[0]['abmdifcomp']; //para el punto #4
if(empty($_abmdesc)){ $_CtrlDescPSL = "#ErrorDescPSL </br>";
} else {
//SI EL Producto es Cosmético, le vuelvo a retirar un 21%
/*if($_bonifiva != 0) {
$_preciodrog = $_preciodrog / 1.21;
}*/
if($_liqdesc < $_abmdesc){ $_CtrlDescPSL = "< $_abmdesc %</br>";
} else{
if($_liqdesc > $_abmdesc){ $_CtrlDescPSL = "> $_abmdesc %</br>";
}
}
}
//***************************//
//#4 Control "Importe NC" == Cantidad * PSL Unitario * (Desc PSL / 100)
//**************************//
//Si en TABLA BONIFICACION el ART "NO" TIENE % IVA, (Y la EMPRESA es 3), le resto el 21%
/*if($_drogidemp == 3) {
$_preciodrog = $_preciodrog / 1.21; //$_preciodrog - ($_preciodrog * 0.21);//precio/1.21
}*/
//$_liqunit PRECIO UNITARIO DE LA BONIFICACION
$_ImporteNC = round(($_liqcant * $_preciodrog * (($_abmdifcomp) / 100)), 2);
$_CtrlTotalNC += $_ImporteNC;
//Si diferencia es > o < a 2%. la muestre
//if($_ImporteNC != $_liqimportenc){ $_CtrlImpNT = $_ImporteNC; }
if($_ImporteNC){
$_porc_difNC = 100 - (($_liqimportenc * 100) / $_ImporteNC);
if ($_porc_difNC < -2 || $_porc_difNC > 2) {
$_CtrlImpNT = $_ImporteNC;
}
} else {
$_CtrlImpNT = "#Error";
}
//ESTADO DE LA LIQUIDACION
//**********************//
// CONTROLA POR ATÍCULO // las cantidades.
//**********************//
if($_liqactiva == 1){
$_Estado .= "Liquidado";
} else {
$_Estado .= "Pendiente";
}
} else {
$_Estado .= "#ErrorEAN";
}
?><file_sep>/condicion/ofertas/lista.php
<?php
$condiciones = DataManager::getCondiciones( 0, 0, 1, 1, 1, date("Y-m-d"), "'Bonificacion'");
if (count($condiciones)) {
$index = 0;
foreach ($condiciones as $j => $cond) {
$condId = $cond['condid'];
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
foreach ($articulosCond as $k => $artCond) {
$condArtOAM = $artCond["cartoam"];
if($condArtOAM == "oferta" || $condArtOAM == "altaoff" || $condArtOAM == "modifoff"){
$condArtIdArt = $artCond['cartidart'];
$condArtNombre = DataManager::getArticulo('artnombre', $condArtIdArt, 1, 1);
$condArtImagen = DataManager::getArticulo('artimagen', $condArtIdArt, 1, 1);
$imagenObject = DataManager::newObjectOfClass('TImagen', $condArtImagen);
$imagen = $imagenObject->__get('Imagen');
$img = ($imagen) ? "/pedidos/images/imagenes/".$imagen : "/pedidos/images/sin_imagen.png";
$arrayArticulos['idart'][$index] = $condArtIdArt;
$arrayArticulos['nombre'][$index] = $condArtNombre;
$arrayArticulos['imagen'][$index] = $img;
$index ++;
}
}
}
}
} ?>
<script src="/pedidos/js/jquery/html2canvas.js" type="text/javascript"></script>
<offers>
<br>
<div class="bloque_1">
<div class="section-title text-center center">
<h2>↓ Ofertas Del Mes ↓</h2>
<h3>Ofertas increibles de <?php echo strtoupper(Mes(date("m"))); ?></h3>
</div>
</div>
<div class="bloque_1" align="center">
<h3>Con la compra de los siguientes productos</h3>
</div>
<br>
<?php
if(isset($arrayArticulos)){
if(count($arrayArticulos['idart'])){
for($i = 0; $i < count($arrayArticulos['idart']); $i ++ ) {
$idArt = $arrayArticulos['idart'][$i];
$nombre = $arrayArticulos['nombre'][$i];
$imagen = $arrayArticulos['imagen'][$i];
$palabras = explode(" ", $nombre); ?>
<div class="bloque_1">
<h4><?php echo "Art. N° ".$idArt." | ".$palabras[0];?><h4>
<small><h4><?php echo $nombre; ?></h4></small>
<br>
<img src="<?php echo $imagen; ?>" class="img-responsive" alt="Oferta">
</div> <?php
}
}
} ?>
<input id="btn-Preview-Image" type="button" value="Preview" />
<a id="btn-Convert-Html2Image" href="#">Download</a>
<br/>
<h3>Preview:</h3>
<div id="previewImage"></div>
<hr>
</offers>
<script>
var element = $("#offers"); // global variable
var getCanvas; // global variable
$("#btn-Preview-Image").on('click', function () {
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
});
//----------------------
$("#btn-Convert-Html2Image").on('click', function () {
var imgageData = getCanvas.toDataURL("image/png");
// Now browser starts downloading it instead of just showing it
var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#btn-Convert-Html2Image").attr("download", "your_pic_name.png").attr("href", newData);
});
//----------------------
/*
function exportChart() {
html2canvas($('#offers'), {
useCORS: true,
allowTaint: true,
onrendered: function (canvas) {
var img = document.createElement("a");
img.href = canvas.toDataURL();
img.download = "chart.png";
img.click();
}
});
}
exportChart();
*/
</script><file_sep>/transfer/gestion/liquidaciondrog/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_drogid = empty($_REQUEST['drogid']) ? 0 : $_REQUEST['drogid'];
if(empty($_REQUEST['fecha_liquidacion'])){
$_mes = date("m"); $_anio = date("Y");
} else {
list($_mes, $_anio) = explode('-', str_replace('/', '-', $_REQUEST['fecha_liquidacion']));
}
if($_drogid){
$_importarXLS = sprintf( "<img id=\"importar\" src=\"/pedidos/images/icons/icono-importxls.png\" border=\"0\" align=\"absmiddle\" title=\"Importar Liquidacion\" style=\"float:right;\" onclick=\"javascript:dac_sendForm(fm_liquidacion_edit, '/pedidos/transfer/gestion/liquidaciondrog/logica/importar_liquidacion.php')\">");
$_exportarXLS = sprintf( "<a href=\"logica/exportar.liquidacion.php?mes=%d&anio=%d&drogid=%d&backURL=%s\" title=\"Exportar Liquidacion\">%s</a>", $_mes, $_anio, $_drogid, $_SERVER['PHP_SELF'], "<img class=\"icon-xls-export\"/>");
$_emitirNC = sprintf( "<img id=\"emitirnc\" src=\"/pedidos/images/icons/icono-emitirnc.png\" border=\"0\" align=\"absmiddle\" title=\"Emitir NC\" onclick=\"javascript:dac_sendForm(fm_liquidacion_edit, '/pedidos/transfer/gestion/liquidaciondrog/logica/update.liquidacion.php')\">");
} ?>
<form id="fm_liquidacion_edit" method="POST">
<div class="bloque_3">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<fieldset>
<div class="bloque_3">
<label for="drogid">Droguería: </label> <?php
$_droguerias = DataManager::getDrogueria('');
if (count($_droguerias)) { ?>
<select name='drogid' id='drogid' onchange="javascript:dac_chageDrogueria();">
<option value="0" selected>Seleccione Droguería...</option><?php
foreach ($_droguerias as $k => $_drogueria) {
$_drogueria = $_droguerias[$k];
$_Did = $_drogueria["drogtid"];
$_Didcliente = $_drogueria["drogtcliid"];
$_DidEmp = $_drogueria["drogtidemp"];
$_Dnombre = $_drogueria["drogtnombre"];
$_Dlocalidad = $_drogueria["drogtlocalidad"];
if($_drogid == $_Didcliente){
$_drogidemp = $_DidEmp; ?>
<option value="<?php echo $_Didcliente; ?>" selected><?php echo $_Didcliente." | ".$_Dnombre." | ".$_Dlocalidad; ?></option> <?php } else { ?>
<option value="<?php echo $_Didcliente; ?>"><?php echo $_Didcliente." | ".$_Dnombre." | ".$_Dlocalidad; ?></option> <?php }
} ?>
</select> <?php
} ?>
</div>
<div class="bloque_1">
<label for="fecha_liquidacion" >Fecha liquidación: </label>
<?php echo listar_mes_anio('fecha_liquidacion', $_anio, $_mes, 'dac_chageDrogueria()', 'width:190px; font-weight:bold; background-color:transparent;'); ?>
</div>
<div class="bloque_1"> </div>
<div class="bloque_3">
<?php echo $_importarXLS; ?>
<input type="file" name="file" id="file">
</div>
<div class="bloque_3">
<?php echo $_emitirNC; ?><?php echo $_exportarXLS; ?>
</div>
<table id="tabla_liquidacion" name="tabla_liquidacion" class="tabla_liquidacion" width="100%" border="0">
<thead>
<tr height="60px;">
<th align="center">Transfer</th>
<th align="center">Fecha Factura</th>
<th align="center">Nro. Factura</th>
<th align="center">EAN</th>
<th align="center">Artículo</th>
<th align="center">Cantidad</th>
<th align="center">PSL Unit.</th>
<th align="center">Desc. PSL</th>
<th align="center">Importe NC</th>
<th align="center">PSL Unit.</th>
<th align="center">Desc. PSL</th>
<th align="center">Importe NC</th>
<th align="center">Estado</th>
</tr>
</thead>
<tbody id="lista_liquidacion">
<?php
//******************************************//
//Consulta liquidacion del mes actual y su drogueria//
//******************************************//
$_liquidaciones = DataManager::getDetalleLiquidacion($_mes, $_anio, $_drogid, 'TD');
if ($_liquidaciones) {
foreach ($_liquidaciones as $k => $_liq) {
$_liq = $_liquidaciones[$k];
$_liqID = $_liq['liqid'];
$_liqFecha = $_liq['liqfecha'];
$_liqTransfer = $_liq['liqnrotransfer'];
$_liqFechaFact = dac_invertirFecha( $_liq['liqfechafact'] );
$_liqNroFact = $_liq['liqnrofact'];
$_liqean = str_replace(" ", "", $_liq['liqean']);
if(!empty($_liqean)){
$_articulo = DataManager::getFieldArticulo("artcodbarra", $_liqean) ;
$_nombreart = $_articulo['0']['artnombre'];
$_idart = $_articulo['0']['artidart'];
}
$_liqcant = $_liq['liqcant'];
$_liqunit = $_liq['liqunitario'];
$_liqdesc = $_liq['liqdescuento'];
$_liqimportenc = $_liq['liqimportenc'];
$_liqactiva = $_liq['liqactiva'];
$_TotalNC += $_liqimportenc;
((($k % 2) != 0)? $clase="par" : $clase="impar");
// CONTROLA las Condiciones de las Liquidaciones y Notas de Crédito//
include($_SERVER['DOCUMENT_ROOT']."/pedidos/transfer/gestion/liquidaciondrog/logica/controles.liquidacion.php");
/*****************/
?>
<tr id="lista_liquidacion<?php echo $k;?>" class="<?php echo $clase;?>" align="center">
<input id="idliquid" name="idliquid[]" type="text" value="<?php echo $_liqID;?>" hidden/>
<input id="activa" name="activa[]" type="text" value="<?php echo $_liqactiva;?>" hidden/>
<input id="fecha" name="fecha[]" type="text" value="<?php echo $_liqFecha;?>" hidden/>
<td><?php echo $_liqTransfer;?>
<input id="transfer" name="transfer[]" type="text" size="7px" value="<?php echo $_liqTransfer;?>" style="border:none; text-align:center;" readonly hidden/></td>
<td><?php echo $_liqFechaFact;?>
<input id="fechafact" name="fechafact[]" type="text" size="8px" value="<?php echo $_liqFechaFact;?>" style="border:none; text-align:center;" readonly hidden/></td>
<td><?php echo $_liqNroFact;?>
<input id="nrofact" name="nrofact[]" type="text" size="8px" value="<?php echo $_liqNroFact;?>" style="border:none; text-align:center;" readonly hidden/></td>
<td><?php echo $_liqean;?>
<input id="ean" name="ean[]" type="text" size="12px" value="<?php echo $_liqean;?>" style="border:none; text-align:center;" readonly hidden/></td>
<td><?php echo $_idart." - ".$_nombreart; ?>
<input id="idart" name="idart[]" type="text" value="<?php echo $_idart;?>" readonly hidden/>
</td>
<td><?php echo $_liqcant;?>
<input id="cant" name="cant[]" type="text" size="5px" value="<?php echo $_liqcant;?>" style="border:none; text-align:center;" readonly hidden/></td>
<td><?php echo $_liqunit;?>
<input id="unitario" name="unitario[]" type="text" size="8px" value="<?php echo $_liqunit;?>" style="border:none; text-align:center;" readonly hidden/></td>
<td><?php echo $_liqdesc;?>
<input id="desc" name="desc[]" type="text" size="8px" value="<?php echo $_liqdesc;?>" style="border:none; text-align:center;" readonly hidden/></td>
<td><?php echo $_liqimportenc;?>
<input id="importe" name="importe[]" type="text" size="8px" value="<?php echo $_liqimportenc;?>" style="border:none; text-align:center;" readonly hidden/></td>
<td width="150px" align="center" style="border-bottom:1px #CCCCCC solid; color:#ba140c; font-weight:bold;">
<?php echo $_CtrlPSLUnit;?></td>
<td width="150px" align="center" style="border-bottom:1px #CCCCCC solid; color:#ba140c; font-weight:bold;">
<?php echo $_CtrlDescPSL;?></td>
<td width="150px" align="center" style="border-bottom:1px #CCCCCC solid; color:#ba140c; font-weight:bold;">
<?php echo $_CtrlImpNT;?></td>
<td align="center">
<?php echo $_Estado; ?>
<input id="estado" name="estado[]" type="text" size="8px" value="<?php echo $_Estado; ?>" style="border:none; text-align:center;" readonly hidden/></td>
</tr> <?php
} //FIN del FOR
} else { ?>
<tr class="impar"><td colspan="13" align="center">No hay liquidaciones cargadas</td></tr><?php
}?>
</tbody>
<tfoot>
<tr>
<th colspan="7" height="30px" style="border:none; font-weight:bold;"></th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;">Total</th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;"><?php echo $_TotalNC; ?></th>
<th colspan="2" height="30px" style="border:none; font-weight:bold;"></th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;"><?php echo $_CtrlTotalNC; ?></th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;"></th>
</tr>
</tfoot>
</table>
<div hidden="hidden"><button id="btnExport" hidden="hidden"></button></div>
</fieldset>
</form>
<script type="text/javascript" src="logica/jquery/jquery.process.emitirnc.js"></script>
<script type="text/javascript">
function dac_chageDrogueria(){
var fecha = $('#fecha_liquidacion').val();
var drogueria = $('#drogid').val();
window.location = '/pedidos/transfer/gestion/liquidaciondrog/index.php?fecha_liquidacion='+fecha+'&drogid='+drogueria;
}
</script><file_sep>/condicion/logica/ajax/delete.condicion.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$arrayIdCond = empty($_POST['condid']) ? 0 : $_POST['condid'];
if(!$arrayIdCond){
echo "Seleccione condición para eliminar."; exit;
}
if(count($arrayIdCond)){
foreach ($arrayIdCond as $j => $condId) {
if ($condId) {
$condObject = DataManager::newObjectOfClass('TCondicionComercial', $condId);
$condObject->__set('ID', $condId);
DataManagerHiper::deleteSimpleObject($condObject, $condId);
DataManager::deleteSimpleObject($condObject);
//Borra los detalles de artículos
$artCondicion = DataManager::getCondicionArticulos($condId);
if (count($artCondicion)) {
foreach ($artCondicion as $k => $detArt) {
$detArt = $artCondicion[$k];
$detId = $detArt['cartid'];
$detIdArt = $detArt['cartidart'];
$artCondObject = DataManager::newObjectOfClass('TCondicionComercialArt', $detId);
$artCondObject->__set('ID', $detId);
DataManagerHiper::deleteSimpleObject($artCondObject, $detId);
DataManager::deleteSimpleObject($artCondObject);
//Borra las bonificaciones del artículo
$articulosBonif = DataManager::getCondicionBonificaciones($condId, $detIdArt);
if (count($articulosBonif)) {
foreach ($articulosBonif as $j => $artBonif) {
$IDCondBonif = $artBonif['cbid'];
$condBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif', $IDCondBonif);
$condBonifObject->__set('ID', $IDCondBonif);
DataManagerHiper::deleteSimpleObject($condBonifObject, $IDCondBonif);
DataManager::deleteSimpleObject($condBonifObject);
}
}
}
}
//------------//
// Movimiento //
$movimiento = 'DeleteCondicion';
dac_registrarMovimiento($movimiento, "DELETE", 'TCondicionComercial', $condId);
} else {
echo "Error al consultar los registros."; exit;
}
}
echo "1"; exit;
} else {
echo "Seleccione una condición."; exit;
}
echo "Error de proceso."; exit;
?><file_sep>/pedidos/print.propuesta.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$idPropuesta = empty($_REQUEST['propuesta']) ? 0 : $_REQUEST['propuesta'];
?>
<!DOCTYPE html>
<html>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php");?>
</header><!-- cabecera -->
<main class="cuerpo">
<div id="factura" align="center">
<div class="cbte" style="overflow:auto; background-color: #FFF; width: 800px;">
<?php
$propuesta = DataManager::getPropuesta($idPropuesta);
if ($propuesta) {
foreach ($propuesta as $k => $prop) {
$empresa = $prop["propidempresa"];
$laboratorio= $prop["propidlaboratorio"];
$nombreEmp = DataManager::getEmpresa('empnombre', $empresa);
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
?>
<div class="cbte_header" style="border-bottom: solid 1px #CCCCCC; color:#373435; padding:15px; height:110px;">
<?php echo $cabeceraPropuesta; ?>
</div> <!-- boxtitulo -->
<?php
$fecha = $prop['propfecha'];
$usrProp = $prop['propusr'];
$usrNombre = DataManager::getUsuario('unombre', $usrProp);
$cuenta = $prop["propidcuenta"];
$cuentaNombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $cuenta, $empresa);
$domicilio = DataManager::getCuenta('ctadireccion', 'ctaidcuenta', $cuenta, $empresa);
$idLocalidad = DataManager::getCuenta('ctaidloc', 'ctaidcuenta', $cuenta, $empresa);
$localidad = DataManager::getLocalidad('locnombre', $idLocalidad);
$cp = DataManager::getCuenta('ctacp', 'ctaidcuenta', $cuenta, $empresa);
$estado = $prop["propestado"];
$observacion = $prop["propobservacion"];
?>
<div class="cbte_boxcontent" align="left" style="font-size: 14px; background-color:#cfcfcf; padding: 5px; padding-left: 15px; padding-right: 15px; min-height: 20px; overflow: hidden;">
<div class="cbte_box" style="height: auto; line-height: 20px; float:left; width: 33%; font-weight:bold;">
<?php echo $fecha;?>
</div>
<div class="cbte_box" style="height: auto; line-height: 20px; float:left; width: 33%; font-weight:bold;">
Nro. Propuesta:
<?php echo str_pad($idPropuesta, 9, "0", STR_PAD_LEFT); ?>
</div>
<div class="cbte_box" align="right" style="height: auto; line-height: 20px; float:left; width: 33%; font-weight:bold;">
<?php echo $usrNombre;?>
</div>
</div> <!-- cbte_boxcontent -->
<div class="cbte_boxcontent" align="left" style="font-size: 14px; background-color:#cfcfcf; padding: 5px; padding-left: 15px; padding-right: 15px; min-height: 20px; overflow: hidden;">
<div class="cbte_box" style="height: auto; line-height: 20px; float:left; width: 16%;">
Cuenta: </br>
Dirección: </br>
</div> <!-- cbte_box -->
<div class="cbte_box2" style="height: auto; line-height: 20px; float:left; width: 66%;">
<?php echo $cuenta." - ".$cuentaNombre;?></br>
<?php echo $domicilio." - ".$localidad." - ".$cp; ?>
</div> <!-- cbte_box2 -->
</div> <!-- cbte_boxcontent -->
<?php
$totalFinal = 0;
$detalles = DataManager::getPropuestaDetalle($idPropuesta, 1);
if ($detalles) {
foreach ($detalles as $j => $det) {
if($j == 0){
$condIdPago = $det["pdcondpago"];
$condicionesDePago = DataManager::getCondicionesDePago(0, 0, NULL, $condIdPago);
if (count($condicionesDePago)) {
foreach ($condicionesDePago as $k => $condPago) {
$condPagoCodigo = $condPago["IdCondPago"];
$condNombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condPago['condtipo']);
$condDias = "(";
$condDias .= empty($condPago['Dias1CP']) ? '0' : $condPago['Dias1CP'];
$condDias .= empty($condPago['Dias2CP']) ? '' : ', '.$condPago['Dias2CP'];
$condDias .= empty($condPago['Dias3CP']) ? '' : ', '.$condPago['Dias3CP'];
$condDias .= empty($condPago['Dias4CP']) ? '' : ', '.$condPago['Dias4CP'];
$condDias .= empty($condPago['Dias5CP']) ? '' : ', '.$condPago['Dias5CP'];
$condDias .= " Días)";
$condDias .= ($condPago['Porcentaje1CP'] == '0.00') ? '' : ' '.$condPago['Porcentaje1CP'].' %';
$condDias .= ($condPago['Porcentaje1CP'] == '0.00') ? '' : ' '.$condPago['Porcentaje1CP'].' %';
}
}
?>
<div class="cbte_boxcontent" align="left" style="font-size: 14px; background-color: #cfcfcf; padding: 5px; padding-left: 15px; padding-right: 15px; min-height: 20px; overflow: hidden;">
<div class="cbte_box2" style="height: auto; line-height: 20px; float:left; width: 66%;"><span style=" color: #2D567F; font-weight:bold;">Condición de Pago:<?php echo $condNombre." ".$condDias;?></div>
</div> <!-- cbte_boxcontent -->
<div class="cbte_boxcontent2" style="padding: 15px; overflow:auto; height:auto;">
<table width="95%" border="0">
<thead>
<tr align="left">
<th scope="col" width="10%" align="center">Producto</th>
<th scope="col" width="10%" height="18" align="center">Art</th>
<th scope="col" width="10%" align="center">Cant</th>
<th scope="col" width="30%" align="center">Descripción</th>
<th scope="col" width="10%" align="center">Precio</th>
<th scope="col" width="10%" align="center">Bonif</th>
<th scope="col" width="10%" align="center">Dto1</th>
<th scope="col" width="10%" align="center">Dto2</th>
<th scope="col" width="10%" align="center">Total</th>
</tr>
</thead>
<?php
}
$total = 0;
$idArt = $det['pdidart'];
$unidades = $det['pdcantidad'];
$descripcion = DataManager::getArticulo('artnombre', $idArt, $empresa, $laboratorio);
$medicinal = DataManager::getArticulo('artmedicinal', $idArt, $empresa, $laboratorio);
$medicinal = ($medicinal == 'S') ? 0 : 1;
$precio = round($det['pdprecio'], 3);
$b1 = ($det['pdbonif1'] == 0) ? '' : $det['pdbonif1'];
$b2 = ($det['pdbonif2'] == 0) ? '' : $det['pdbonif2'];
$bonif = ($det['pdbonif1'] == 0) ? '' : $b1." X ".$b2;
$desc1 = ($det['pddesc1'] == 0) ? '' : $det['pddesc1'];
$desc2 = ($det['pddesc2'] == 0) ? '' : $det['pddesc2'];
$total = dac_calcularPrecio($unidades, $precio, 0, $desc1, $desc2);
$totalFinal += $total;
$artImagen = DataManager::getArticulo('artimagen', $idArt, $empresa, $laboratorio);
$imagenObject = DataManager::newObjectOfClass('TImagen', $artImagen);
$imagen = $imagenObject->__get('Imagen');
$img = ($imagen) ? "/pedidos/images/imagenes/".$imagen : "/pedidos/images/sin_imagen.png";
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\" align=\"center\"><img src=\"%s\" alt=\"Imagen\" width=\"100\"/></td><td align=\"center\">%s</td><td>%s</td><td>%s</td><td align=\"right\" style=\"padding-right:15px;\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"right\" style=\"padding-right:5px;\">%s</td>", $img, $idArt, number_format($unidades,0), $descripcion, number_format(round($precio,2),2), $bonif, number_format(round($desc1,2),2), number_format(round($desc2,2),2), number_format(round($total,2),2));
echo sprintf("</tr>");
} ?>
</table>
</div> <!-- cbte_boxcontent2 --> <?php
}
} ?>
<div class="cbte_boxcontent2" align="left" style="font-size: 14px; background-color: #cfcfcf; padding: 5px; padding-left: 15px; padding-right: 15px; min-height: 20px; overflow: hidden;">
<div class="cbte_box2" style="height: auto; line-height: 20px; float:left; width: 66%; border:1px solid #cfcfcf;"><span style=" font-weight:bold;"><?php echo $observacion;?></div>
<div class="cbte_box" align="right" style="height: auto; line-height: 20px; float:left; width: 33%; font-size:26px;"><span style=" color: #2D567F; font-weight:bold;">TOTAL: <?php echo number_format(round($totalFinal,2),2);?></div>
</div> <!-- cbte_boxcontent2 -->
<div class="cbte_boxcontent2">
<?php echo $piePropuesta; ?>
</div> <!-- cbte_boxcontent2 -->
<?php
} ?>
</div> <!-- factura contenido -->
</div> <!-- factura -->
</main> <!-- fin cuerpo -->
</body>
</html>
<?php
echo "<script>";
echo "javascript:setTimeout(function(){ dac_imprimirMuestra('factura'); }, 3000);";
echo "</script>";
?> <file_sep>/condicionpago/logica/eliminar.condicion.transfer.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag2']) ? 0 : $_REQUEST['pag2'];
$condId = empty($_REQUEST['condid'])? 0 : $_REQUEST['condid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/condicionpago/' : $_REQUEST['backURL'];
if ($condId) {
$_condobject = DataManager::newObjectOfClass('TCondiciontransfer', $condId);
$_condobject->__set('ID', $condId );
$ID = DataManager::deleteSimpleObject($_condobject);
//REGISTRA MOVIMIENTO
$movimiento = 'CONDICION_PAGO_TRANSFER';
$movTipo = 'DELETE';
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", $condId);
}
header('Location: '.$backURL.'?pag2='.$_pag);
?><file_sep>/droguerias/lista.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G") {
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
?>
<script type="text/javascript" language="JavaScript" src="/pedidos/droguerias/logica/jquery/scriptDroguerias.js"></script>
<div class="box_body">
<form id="fmDrogueria" name="fmDrogueria" method="post">
<fieldset>
<legend>Datos de droguería</legend>
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<div class="bloque_5">
<label for="empresa">Empresa</label>
<select id="empresa" name="empresa" onchange="javascript:dac_changeEmpresa(this.value);"> <?php
$empresas = DataManager::getEmpresas(1);
if (count($empresas)) {
foreach ($empresas as $k => $emp) {
$idEmp = $emp["empid"];
$nombreEmp = $emp["empnombre"];
if ($idEmp == 1){ ?>
<option id="<?php echo $idEmp; ?>" value="<?php echo $idEmp; ?>" selected><?php echo $nombreEmp; ?></option><?php
} else { ?>
<option id="<?php echo $idEmp; ?>" value="<?php echo $idEmp; ?>"><?php echo $nombreEmp; ?></option><?php
}
}
}
echo "<script>";
echo "dac_changeEmpresa(1);";
echo "</script>";
?>
</select>
</div>
<div class="bloque_9">
<br>
<a href="editar.php" title="Nueva">
<img class="icon-new"/>
</a>
</div>
<div class="bloque_9">
<br>
<a id="deleteDrog" title="Eliminar">
<img class="icon-delete"/>
</a>
</div>
<div class="bloque_9">
<br>
<?php $urlSend = '/pedidos/droguerias/logica/update.lista.php';?>
<a id="btnSend" title="Enviar">
<img class="icon-send" onclick="javascript:dac_sendForm(fmDrogueria, '<?php echo $urlSend;?>');"/>
</a>
</div>
<hr>
<div class="bloque_7">
<label for="drogid">Drogueria</label>
<input type="text" id="drogid" name="drogid" readonly>
</div>
<div class="bloque_3">
<label for="id">Nombre</label>
<input type="text" id="nombre" name="nombre" class="text-uppercase">
</div>
</fieldset>
<fieldset>
<legend>Droguerías Relacionadas</legend>
<div class="bloque_7">Localidad</div>
<div class="bloque_7">Cuenta</div>
<div class="bloque_8" align="center">TL</div>
<div class="bloque_8" align="center">TD</div>
<div class="bloque_7" id="acciones"></div>
<hr>
<div id="drogueria_relacionada"></div>
</fieldset>
</form>
</div> <!-- Fin box body -->
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Droguerías</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn" type="text" value="tblDroguerias" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<div id='tabladroguerias'></div>
</div> <!-- Fin lista -->
</div> <!-- Fin box_seccion -->
<hr>
<file_sep>/js/ajax/eliminar.archivo.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
//$_nextURL = sprintf("%s", "/pedidos/login/index.php");
//echo $_SESSION["_usrol"];
//header("Location: $_nextURL");
echo "Usuario no permitido para realizar ésta acción."; exit;
}
$direccion = empty($_REQUEST['direccion']) ? 0 : $_REQUEST['direccion'];
$dir = $_SERVER['DOCUMENT_ROOT'].$direccion;
if (!@unlink($dir)) { echo "Error al querer eliminar el archivo"; exit; }
?><file_sep>/informes/logica/exportar.tablaarticulos.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=TablaArticulos-".date('d-m-y').".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos .::</TITLE>
<head></head>
<body>
<table border="0">
<thead>
<tr>
<td scope="col" >artid</td>
<td scope="col" >artidempresa</td>
<td scope="col" >artidlab</td>
<td scope="col" >artidart</td>
<td scope="col" >artnombre</td>
<td scope="col" >artdescripcion</td>
<td scope="col" >artprecio</td>
<td scope="col" >artcodbarra</td>
<td scope="col" >artstock</td>
<td scope="col" >artmedicinal</td>
<td scope="col" >artimagen</td>
<td scope="col" >artusrupdate</td>
<td scope="col" >artlastupdate</td>
<td scope="col" >artactivo</td>
</tr>
</thead>
<?php
$articulos = DataManager::getArticulos(0, 0, '');
if (count($articulos)) {
foreach ($articulos as $k => $articulo) {
$artid = $articulo['artid'];
$artidempresa = $articulo['artidempresa'];
$artidlab = $articulo['artidlab'];
$artidart = $articulo['artidart'];
$artnombre = $articulo['artnombre'];
$artdescripcion = $articulo['artdescripcion'];
$artprecio = $articulo['artprecio'];
$artcodbarra = $articulo['artcodbarra'];
$artstock = $articulo['artstock'];
$artmedicinal = $articulo['artmedicinal'];
$artimagen = $articulo['artimagen'];
$artusrupdate = $articulo['artusrupdate'];
$artlastupdate = $articulo['artlastupdate'];
$artactivo = $articulo['artactivo'];
echo sprintf("<tr align=\"left\">");
echo sprintf("<td >%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>", $artid, $artidempresa, $artidlab, $artidart, $artnombre, $artdescripcion, $artprecio, $artcodbarra, $artstock, $artmedicinal, $artimagen, $artusrupdate, $artlastupdate, $artactivo);
echo sprintf("</tr>");
}
} ?>
</table>
</body>
</html>
<file_sep>/condicion/logica/ajax/setFechaCondiciones.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$startDate = empty($_POST['startDate'])? 0 : $_POST['startDate'];
$endDate = empty($_POST['endDate']) ? 0 : $_POST['endDate'];
$arrayIdCond= empty($_POST['editSelected']) ? 0 : $_POST['editSelected'];
if(!$arrayIdCond) {
echo "Seleccione condición para modificar."; exit;
}
//si no es array, lo convierte
if(!is_array($arrayIdCond)){
$arrayIdCond = array($arrayIdCond);
}
if(empty($startDate) || empty($endDate)){
echo "Debe ingresar una fecha a modificar."; exit;
}
//CONTROLAR echo "La fecha de inicio debe ser menor a la fecha de fin"; exit;
//Inicio
$startDate = new DateTime($startDate);
$endDate = new DateTime($endDate);
if($startDate >= $endDate){
echo "La fecha de inicio debe ser inferior a la de fin."; exit;
}
foreach ($arrayIdCond as $j => $condId) {
//Consulto los datos de dicha condición comercial para modificar
$condicion = DataManager::getCondiciones(0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $condId);
if(count($condicion) != 1){
echo "Error al consultar el registro."; exit;
}
//----------------
// Lee Condición //
if ($condId) {
$condObject = DataManager::newObjectOfClass('TCondicionComercial', $condId);
$condObject->__set('FechaInicio' , $startDate->format("Y-m-d"));
$condObject->__set('FechaFin' , $endDate->format("Y-m-d"));
DataManagerHiper::updateSimpleObject($condObject, $condId);
DataManager::updateSimpleObject($condObject);
// MOVIMIENTO
$movimiento = 'FECHAS_INICIO_'.$startDate->format("Y-m-d")."_Y_FIN_".$endDate->format("Y-m-d");
dac_registrarMovimiento($movimiento, "UPDATE", 'TCondicionComercial', $condId);
} else {
echo "No se encuentran registros."; exit;
}
}
echo '1'; exit;
?><file_sep>/includes/class/class.recibos.php
<?php
require_once('class.PropertyObject.php');
class TRecibos extends PropertyObject {
protected $_tablename = 'recibos';
protected $_fieldid = 'recid';
//protected $_fieldactivo = 'cheqactivo';
protected $_timestamp = 0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'recid'; //Relación con tabla "rec_fact" para IDFactura
$this->propertyTable['Numero'] = 'recnro';
$this->propertyTable['Talonario'] = 'rectalonario';//Relación con tabla "talonario_idusr" para saber de que IDUsr es
$this->propertyTable['Observacion'] = 'recobservacion';
$this->propertyTable['Diferencia'] = 'recdiferencia';
//$this->propertyTable['Activa'] = 'cheqactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
/*
public function Autenticado() {
return $this->_autenticado;
}*/
public function __newID() {
// Devuelve '#petid' para el alta de un nuevo registro
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/transfer/gestion/liquidaciondrog/logica/importar_liquidacion.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php" );
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/PHPExcel/PHPDacExcel.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_drogueria = empty($_POST['drogid']) ? 0 : $_POST['drogid'];
$_fecha_liq = empty($_POST['fecha_liquidacion']) ? 0 : "01-".$_POST['fecha_liquidacion'];
if ($_drogueria == 0){ echo "No se cargó correctamente la droguería"; exit; }
if ($_fecha_liq == 0){ echo "No se cargó correctamente la fecha de liquidación."; exit; }
$_fecha_l = dac_invertirFecha($_fecha_liq);
$mensage = '';
if ($_FILES){
foreach ($_FILES as $key){ //Iteramos el arreglo de archivos
if($key['error'] == UPLOAD_ERR_OK ){//Si el archivo se paso correctamente Continuamos
//Controlo extención
$file_name = $key['name'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
if($ext == "xls"){
//antes de importar el EXCEL debería eliminar en esa fecha y droguería, cualquier dato existente.
$_liqobject = DataManager::deleteFromLiquidacion($_drogueria, $_fecha_l, 'TD');
$archivo_temp = $key['tmp_name']; //Obtenemos la ruta Original del archivo
//Convierto el excel en un array de arrays
$arrayxls = PHPDacExcel::xls2array($archivo_temp);
for($j=1; $j < count($arrayxls); $j++){
if(count($arrayxls[$j]) != 12){
echo 'Está intentando importar un archivo con diferente cantidad de campos (deben ser 12 columnas)'; exit;
} else {
//procedo a cargar los datos
$_liqobject = DataManager::newObjectOfClass('TLiquidacion');
$_liqobject->__set('ID' , $_liqobject->__newID());
$_liqobject->__set('Drogueria' , $_drogueria); //$arrayxls[$j][0]
$_liqobject->__set('Tipo' , 'TD');
$_liqobject->__set('Transfer' , $arrayxls[$j][1]);
// La fecha la toma en número por lo que la convierto a fecha nuevamente
$fechafact = date("Y-m-d", mktime(null, null, null, null, $arrayxls[$j][2] - '36494', null, null));
$_liqobject->__set('FechaFact' , $fechafact);
$_liqobject->__set('NroFact' , $arrayxls[$j][3]);
$_liqobject->__set('EAN' , str_replace(" ", "", $arrayxls[$j][4]));
$_liqobject->__set('Cantidad' , $arrayxls[$j][5]);
$_liqobject->__set('Unitario' , $arrayxls[$j][6]);
//Buscar y Reemplazar el símbolo % por vacío.
$_liqobject->__set('Descuento' , str_replace("%", "", $arrayxls[$j][7]));
$_liqobject->__set('ImporteNC' , $arrayxls[$j][8]);
$_liqobject->__set('Cliente' , $arrayxls[$j][9]);
$_liqobject->__set('RasonSocial', $arrayxls[$j][10]);
$_liqobject->__set('Cuit' , $arrayxls[$j][11]);
$_liqobject->__set('Fecha' , $_fecha_l);
$_liqobject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$_liqobject->__set('LastUpdate' , date("Y-m-d H:m:s"));
$ID = DataManager::insertSimpleObject($_liqobject);
}
}
} else {
echo "Debe importar un archivo Excel con extensión .xls (versión 97-2003)"; exit;
}
}
if ($key['error']==''){ //Si no existio ningun error, retornamos un mensaje por cada archivo subido
$mensage .= 'Archivo Subido correctamente con '.(count($arrayxls)-1).' registros';
} else {
//if ($key['error']!=''){//Si existio algún error retornamos un el error por cada archivo.
$mensage .= '-> No se pudo subir el archivo debido al siguiente Error: \n'.$key['error'];
}
}
} else { $mensage .= 'Debe seleccionar algún archivo para enviar.'; }
echo $mensage;// Regresamos los mensajes generados al cliente
?><file_sep>/condicion/lista.php
<div class="box_body">
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<div class="barra">
<div class="bloque_7">
<select id="empselect" name="empselect"><?php
$empresas = DataManager::getEmpresas(1);
if (count($empresas)) {
foreach ($empresas as $k => $emp) {
$idemp = $emp["empid"];
$nombreEmp = $emp["empnombre"];
?><option id="<?php echo $idemp; ?>" value="<?php echo $idemp; ?>"><?php echo $nombreEmp; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<select id="tiposelect" name="tiposelect">
<option value="0">Tipos</option>
<option value="Bonificacion">Bonificaciones</option>
<option value="Pack">Packs</option>
<option value="ListaEspecial">Listas Especiales</option>
<option value="CondicionEspecial">Condiciones Especiales</option>
</select>
</div>
<div class="bloque_7">
<select id="actselect" name="actselect">
<option id="" value="" >Todos</option>
<option id="1" value="1" >Activos</option>
<option id="0" value="0" >Inactivos</option>
</select>
</div>
<div class="bloque_7">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar por Página"/>
<input id="txtBuscarEn" type="text" value="tblCondiciones" hidden/>
</div>
<?php
if ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="M"){
$btnNuevo = sprintf( "<a href=\"editar.php\" title=\"Nuevo\"><img class=\"icon-new\"/></a>");
$btnStatus = sprintf( "<a title=\"Cambiar Estado\"><img class=\"icon-status-pending\" onclick=\"javascript:dac_ModificarSelect('status')\"/></a>");
$btnDuplicar= sprintf( "<a title=\"Duplicar\"><img class=\"icon-copy-to-all\" onclick=\"javascript:dac_ModificarSelect('duplicate')\"/></a>");
$btnPrecio = sprintf( "<a title=\"Modificar Precios\"><img class=\"icon-price\" onclick=\"javascript:dac_ModificarSelect('price')\"/></a>");
$btnEliminar= sprintf( "<a title=\"Eliminar\"><img class=\"icon-delete\" onclick=\"javascript:dac_eliminarCondicion()\" /></a>"); ?>
<div class="bloque_1">
<?php echo $btnNuevo; ?>
<?php echo $btnStatus; ?>
<?php echo $btnDuplicar; ?>
<?php echo $btnPrecio; ?>
<?php echo $btnEliminar; ?>
</div>
<?php
} ?>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<form id='frmCondicion' method='post'>
<div id='tablaCondiciones'></div>
</form>
</div> <!-- Fin listar -->
<div class="barra">
<div class="bloque_1" style="text-align: right;">
<!-- paginador de jquery -->
<paginator></paginator>
<input id="totalRows" hidden="hidden">
</div>
<hr>
</div> <!-- Fin barra -->
</div> <!-- Fin box_cuerpo -->
<div class="box_seccion"> <?php
if ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="M"){
?>
<fieldset>
<legend>Modificar Datos</legend>
<div class="bloque_6">
<input id="startDate" name="startDate" type="text" placeholder="INICIO" readonly/>
</div>
<div class="bloque_6">
<input id="endDate" name="endDate" type="text" placeholder="FIN" readonly/>
</div>
<div class="bloque_7">
<input type="button" id="btnEdit" value="Editar" title="Editar"/>
</div>
</fieldset>
<?php } ?>
</div> <!-- Fin box_seccion -->
<hr>
<script src="logica/jquery/jqueryFooter.js"></script>
<script src="/pedidos/js/jquery/jquery.paging.js"></script>
<script>
//#######################################
// PAGING DACIOCCO
//#######################################
//Funcion que devuelve cantidad de Filas
function dac_filas(callback) {
var empresa = $('#empselect').val(),
tipo = $('#tiposelect').val(),
activos = $('#actselect').val();
$.ajax({
type : "POST",
cache : false,
url : '/pedidos/condicion/logica/ajax/getFilasCondiciones.php',
data: { empselect : empresa,
tiposelect : tipo,
actselect : activos
},
success : function(totalRows){
if(totalRows){
$("#totalRows").val(totalRows);
callback(totalRows);
}
},
});
}
//---------------------------------------
//Cantidad de filas por página
var rows = 25;
//Setea datos de acceso a datos vía AJAX
var data = { //los indices deben ser iguales a los id de los select
empselect : $('#empselect').val(),
actselect : $('#actselect').val(),
tiposelect : $('#tiposelect').val()
};
var url = 'logica/ajax/getCondiciones.php';
var tableName = 'tablaCondiciones';
var selectChange= ['tiposelect', 'empselect', 'actselect'];
//---------------------------------------
//Llamada a función generadora del paginado
dac_filas(function(totalRows) {
$("paginator").paging(rows, totalRows, data, url, tableName, selectChange);
});
</script><file_sep>/usuarios/password/logica/update.password.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="P" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_uid = $_SESSION["_usrid"]; //empty($_REQUEST['uid']) ? 0 : $_REQUEST['uid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/index.php': $_REQUEST['backURL'];
$empresa = empty($_SESSION["_usridemp"]) ? 1 : $_SESSION["_usridemp"];
$_empresas = DataManager::getEmpresas(1);
if (count($_empresas)) {
foreach ($_empresas as $k => $_emp) {
if ($empresa == $_emp['empid']){
$_nombreemp = $_emp["empnombre"];
}
}
}
$_nombre = $_SESSION["_usrname"];
$_usuario = $_POST['uusuario'];
$_password = $_POST['upassword'];
$_newpassword = $_POST['<PASSWORD>password'];
$_newpasswordbis = $_POST['<PASSWORD>'];
$_SESSION['s_usuario'] = $_usuario;
$_SESSION['s_password'] = $_password;
$_SESSION['s_newpassword'] = $_newpassword;
$_SESSION['s_newpasswordbis'] = $_newpasswordbis;
//Consulta si existe el usuario en cualquiera de las tablas con posibilidad de usuario
$_ID = DataManager::getIDByField('TUsuario', 'ulogin', $_usuario);
if ($_ID > 0) {
$_usrobject = DataManager::newObjectOfClass('TUsuario', $_ID);
} else {
$_ID = DataManager::getIDByField('TProveedor', 'provlogin', $_usuario);
if ($_ID > 0) {
$_usrobject = DataManager::newObjectOfClass('TProveedor', $_ID);
}
}
//$_ID = DataManager::getIDByField('TUsuario', 'ulogin', $_usuario);
if ($_ID > 0) {
//$_usrobject = DataManager::newObjectOfClass('TUsuario', $_ID);
if (empty($_password) || $_password == "") {
$_goURL = sprintf("/pedidos/usuarios/password/index.php?sms=%d", 2);
header('Location:' . $_goURL);
exit;
}
//echo "1-".md5($_password);
//echo "2-".$_usrobject->login(md5($_password));
if ($_usrobject->login(md5($_password))) {
if (empty($_newpassword)) {
$_goURL = sprintf("/pedidos/usuarios/password/index.php?sms=%d", 4);
header('Location:' . $_goURL);
exit;
}
if (empty($_newpasswordbis)) {
$_goURL = sprintf("/pedidos/usuarios/password/index.php?sms=%d", 5);
header('Location:' . $_goURL);
exit;
}
if ((0 != strcmp($_newpassword, $_newpasswordbis))) {
$_goURL = sprintf("/pedidos/usuarios/password/index.php?sms=%d", 6);
header('Location:' . $_goURL);
exit;
} else {
$_email = $_usrobject->__get('Email');
if (!preg_match( "/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,4})$/", $_email )) {
$_goURL = sprintf("/pedidos/usuarios/password/index.php?sms=%d", 7);
header('Location:' . $_goURL);
exit;
}
//Si ya existe una clave, la lee de la ddbb cifrada y al querer grabar la vuelve a cifrar dando errores.
//Por eso mismo hago el siguiente control previo.
//echo "3-".strlen($_password) <= 15;
/*********************************/
//$_usrobject = DataManager::newObjectOfClass('TUsuario', $_ID);
$_usrobject->__set('Clave', md5($_newpassword));
$ID = DataManager::updateSimpleObject($_usrobject);
/*********************************/
//ENVIAR MAIL AL USUARIO NOTIFICANDO LA NUEVA CLAVE
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = "<EMAIL>";
$mail->FromName = "InfoWeb GEZZI";
$mail->Subject = 'Solicitud de Cambio de Clave.';
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
$_total = '
<html>
<head>
<title>Cambio de clave</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 90%;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 0px;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>
<body>
<div align="center">
<table width="600" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Notificación de <strong>NUEVA CLAVE DE ACCESO</strong><br />
<div />
</td >
</tr>
<tr bgcolor="#597D92">
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight: bold;">
<strong>Estos son sus datos de solicitud</strong>
</div>
</td>
</tr>
<tr>
<td height="95" valign="top">
<div class="texto">
<table width="600px" style="border:1px solid #597D92">
<tr>
<th rowspan="2" align="left" width="250">
Usuario:<br />
Clave:
</th>
<th rowspan="2" align="left" width="450">
'.$_usuario.'<br />
'.$_newpassword.'
</th>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con la empresa al 4555-3366 de Lunes a Viernes de 10 a 17 horas.
</font>
<div style="color:#000000; font-size:12px;">
<strong>No responda a éste mail.</br></br>
</div>
</div>
</td>
</tr>
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo" align="left">
Gracias por confiar en '.$_nombreemp.'<br/>
Le Saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
';
$mail->msgHTML($_total);
$mail->AddAddress($_email, 'InfoWeb GEZZI');
$mail->AddAddress("<EMAIL>", 'InfoWeb GEZZI');
/************************************/
unset($_SESSION['s_usuario']);
unset($_SESSION['s_password']);
unset($_SESSION['s_newpassword']);
unset($_SESSION['s_newpasswordbis']);
/**********************************/
if(!$mail->Send()) {
echo 'Fallo en el envío del correo.';
} else {
$_goURL = sprintf("/pedidos/usuarios/password/index.php?sms=%d", 8);
header('Location:'.$_goURL); exit;
}
exit;
}
} else {
$_goURL = sprintf("/pedidos/usuarios/password/index.php?sms=%d", 3);
header('Location:' . $_goURL);
exit;
}
} else {
$_goURL = sprintf("/pedidos/usuarios/password/index.php?sms=%d", 1);
header('Location:' . $_goURL);
exit;
}
header('Location: '.$backURL);
?><file_sep>/cuentas/logica/jquery/jqueryHeader.js
//-----------------------------------------//
// Crea Div de Cuenta Transfer relacionada //
var nextCuentaTransfer = 0;
function dac_cargarCuentaTransferRelacionada2(id, idCta, idCuenta, nombre, nroClienteTransfer){
"use strict";
nextCuentaTransfer++;
var campo = '<div id="rutcuenta'+nextCuentaTransfer+'">';
campo +='<div class="bloque_8"><input id="btmenos" class="btmenos" type="button" value=" - " onClick="dac_deleteCuentaTransferRelacionada2('+id+', '+nextCuentaTransfer+')"></div >';
campo +='<div class="bloque_8"><input id="cuentaIdTransfer'+nextCuentaTransfer+'" name="cuentaIdTransfer[]" type="text" maxlength="10" placeholder="Transfer" value="'+nroClienteTransfer+'"/></div >';
campo +='<input id="cuentaId'+nextCuentaTransfer+'" name="cuentaId[]" type="text" value='+idCta+' hidden/>';
campo += '<div class="bloque_8"> '+idCuenta+'</div><div class="bloque_4">'+nombre.substring(0,25)+'</div>';
campo += '<hr>';
campo +='</div>';
$("#detalle_cuenta2").append(campo);
}
// Botón eliminar para quitar un div de artículos
function dac_deleteCuentaTransferRelacionada2(id, nextCuentaTransfer){
"use strict";
var elemento = document.getElementById('rutcuenta'+nextCuentaTransfer);
elemento.parentNode.removeChild(elemento);
}
function dac_cuentaTransferRelacionada() {
"use strict";
$("#detalle_cuenta2").empty();
$('#box_cargando3').css({'display':'block'});
$.ajax({
type : 'POST',
cache : false,
url : '/pedidos/cuentas/logica/jquery/cargar.cuentasTransferRelacionada.php',
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
$('#box_cargando3').css({'display':'block'});
$("#msg_cargando3").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
$('#box_cargando').css({'display':'none'});
if (resultado){
$('#tablaCuentasTransfer2').html(resultado);
$('#box_cargando3').css({'display':'none'});
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_cargando3').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al intentar consultar los registros.");
},
});
}
function dac_changeEmpresa(idEmpresa){
"use strict";
$.getJSON('/pedidos/js/ajax/getCadena.php?idEmpresa='+idEmpresa, function(datos) {
var idCadenas = datos;
$('#cadena').find('option').remove();
$('#cadena').append("<option value='0' selected></option>");
$.each( idCadenas, function( key, value ) {
var arr = value.split('-');
var cadena = document.getElementById('cadena').value;
if(arr[0] === cadena){
$('#cadena').append("<option value='" + arr[0] + "' selected>" + arr[1] + "</option>");
} else {
$('#cadena').append("<option value='" + arr[0] + "'>" + arr[1] + "</option>");
}
});
});
}
function dac_changeLocalidad(localidad){
"use strict";
var idProvincia = $('#provincia').val();
$.getJSON('/pedidos/js/provincias/getLocalidad.php?idProvincia='+idProvincia, function(datos) {
var localidades = datos;
$('#localidad').find('option').remove();
$.each( localidades, function( key, value ) {
var arr = value.split('-');
if(arr[0] === localidad) {
$('#localidad').append("<option value='" + arr[0] + "' selected>" + arr[1] + "</option>");
} else {
$('#localidad').append("<option value='" + arr[0] + "'>" + arr[1] + "</option>");
}
});
});
if(idProvincia !== '1'){
var codigosPostales;
$.getJSON('/pedidos/js/provincias/getCodigoPostal.php?idLocalidad='+localidad, function(datos) {
codigosPostales = datos;
$('#codigopostal').val("");
$.each( codigosPostales, function( key, value ) {
$('#codigopostal').val(value);
});
});
}
}
function dac_ShowPdf(archivo){
"use strict";
$("#pdf_ampliado").empty();
var campo = '<iframe src=\"https://docs.google.com/gview?url='+archivo+'&embedded=true\" style=\"width:650px; min-height:260px; height:90%;\" frameborder=\"0\"></iframe>';
$("#pdf_ampliado").append(campo);
$('#pdf_ampliado').fadeIn('slow');
$('#pdf_ampliado').css({
'width': '100%',
'height': '100%',
'left': ($(window).width() / 2 - $(img_ampliada).width() / 2) + 'px',
'top': ($(window).height() / 2 - $(img_ampliada).height() / 2) + 'px'
});
//document.getElementById("pdf_ampliado").src = src;
$(window).resize();
return false;
}
function dac_ClosePdfZoom(){
"use strict";
$('#pdf_ampliado').fadeOut('slow');
return false;
}
//previene que se pueda hacer Enter en observaciones
$(document).ready(function() {
"use strict";
$('textarea').keypress(function(event) {
if (event.keyCode === 13) {
event.preventDefault();
}
});
//-------------
//Definir Lista de Precios disponible segun Categoría comercial seleccionada.
$("#categoriaComer").change(function () {
var idCatComerc = $('#categoriaComer option:selected').val();
var empresa = $("#empselect").val();
var listaPrecios;
$.getJSON('/pedidos/cuentas/logica/jquery/getListaPrecios.php?idCatComerc='+idCatComerc+'&empresa='+empresa, function(datos) {
listaPrecios = datos;
$('#listaPrecio').find('option').remove();
$.each( listaPrecios, function( key, value ) {
var arr = value.split('|');
$('#listaPrecio').append("<option value='" + arr[0] + "'>" + arr[1] + "</option>");
});
});
});
//---------------------
});<file_sep>/condicionpago/editar_transfer.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_condid = empty($_REQUEST['condid']) ? 0 : $_REQUEST['condid'];
$_sms = empty($_GET['sms']) ? 0 : $_GET['sms'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/condicionpago/': $_REQUEST['backURL'];
if ($_sms) {
$_condcodigo = isset($_SESSION['s_codigo']) ? $_SESSION['s_codigo'] : '';
$_condnombre = isset($_SESSION['s_nombre']) ? $_SESSION['s_nombre'] : '';
$_conddias = isset($_SESSION['s_dias']) ? $_SESSION['s_dias'] : '';
$_condporcentaje= isset($_SESSION['s_porcentaje']) ? $_SESSION['s_porcentaje'] : '';
switch ($_sms) {
case 1: $_info = "El código es obligatorio"; break;
case 2: $_info = "El nombre es obligatorio."; break;
case 3: $_info = "La condición de pago ya existe."; break;
} // mensaje de error
}
if ($_condid) {
if (!$_sms) {
$_condcion = DataManager::newObjectOfClass('TCondiciontransfer', $_condid);
$_condcodigo = $_condcion->__get('Codigo');
$_condnombre = $_condcion->__get('Nombre');
$_conddias = $_condcion->__get('Dias');
$_condporcentaje= $_condcion->__get('Porcentaje');
}
$_button = sprintf("<input type=\"submit\" id=\"btsend\" name=\"_condicion\" value=\"Enviar\"/>");
$_action = "logica/update.condicion.transfer.php?backURL=".$backURL;
} else {
if (!$_sms) {
$_condcodigo = "";
$_condnombre = "";
$_conddias = "";
$_condporcentaje= "";
}
$_button = sprintf("<input type=\"submit\" id=\"btsend\" name=\"_condicion\" value=\"Enviar\"/>");
$_action = sprintf("logica/update.condicion.transfer.php?uid=%d&backURL=", $_condid, $backURL);
}
?>
<!DOCTYPE>
<html lang="es">
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "condiciones_pago";
$_subsection = "nueva_condicion_transfer";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<div class="box_body">
<div class="bloque_1"> <?php
if ($_sms) { ?>
<div class="bloque_1" align="center">
<fieldset id='box_error' class="msg_error" style="display:block">
<div id="msg_error"><?php echo $_info;?></div>
</fieldset>
</div> <?php
} ?>
</div>
<form id="fm_condicion_edit" name="fm_condicion_edit" method="post" action="<?php echo $_action;?>">
<fieldset>
<legend>Condición</legend>
<div class="bloque_1">
<fieldset id='box_observacion' class="msg_alerta" style="display:block">
<div id="msg_atencion">Importante: los días deberán cargarse en enteros separados por comas (como en el ejemplo) sin caracteres adicionales.</div>
</fieldset>
</div>
<div class="bloque_8">
<label for="condcodigo">Código *</label>
<input name="condcodigo" id="condcodigo" type="text" maxlength="5" value="<?php echo @$_condcodigo;?>"/>
</div>
<div class="bloque_4">
<label for="condnombre">Condición*</label>
<input name="condnombre" id="condnombre" type="text" maxlength="50" value="<?php echo @$_condnombre;?>"/>
</div>
<div class="bloque_8">
<label for="conddias">Días</label>
<input name="conddias" id="conddias" type="text" maxlength="50" value="<?php echo @$_conddias;?>" placeholder="30, 60, 90"/>
</div>
<div class="bloque_8">
<label for="condporcentaje">Porcentaje</label>
<input name="condporcentaje" id="condporcentaje" type="text" maxlength="1" value="<?php echo @$_condporcentaje;?>"/>
</div>
<input type="hidden" name="condid" value="<?php echo @$_condid;?>"/>
<div class="bloque_7"> <?php echo $_button; ?> </div>
</fieldset>
</form>
</div> <!-- FIN box_body -->
<hr>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/pedidos/pendientes/lista.php
<div class="box_body"> <!-- datos -->
<?php if ($_SESSION["_usrrol"] == "A" || $_SESSION["_usrrol"] == "M" || $_SESSION["_usrrol"] == "V" || $_SESSION["_usrrol"] == "G"){ ?>
<div class="barra">
<div class="bloque_1">
<h1>Mis Pendientes</h1>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblPendientes">
<thead>
<tr>
<td scope="col" width="20%" height="18">Fecha</td>
<td scope="col" width="20%">Pedido</td>
<td scope="col" width="50%">Cliente</td>
<td scope="col" width="10%" align="center">Acciones</td>
</tr>
</thead>
<?php
$_pedidos_recientes = DataManager::getPedidos($_SESSION["_usrid"], 1, NULL, NULL, NULL, NULL);
if ($_pedidos_recientes){
$_nro = 0;
$_fila = 0;
foreach ($_pedidos_recientes as $k => $_pedidoRec) {
$fecha = $_pedidoRec["pfechapedido"];
$_nropedido = $_pedidoRec["pidpedido"];
$_idemp = $_pedidoRec["pidemp"];
$_cliente = $_pedidoRec["pidcliente"];
$_nombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $_cliente, $_idemp);
if($_nro != $_nropedido) {
$_eliminar = sprintf ("<a href=\"../logica/eliminar.pedido.php?nropedido=%d&backURL=%s\" title=\"Eliminar\" onclick=\"return confirm('¿Está Seguro que desea ELIMINAR EL PEDIDO?')\"> <img class=\"icon-delete\"/> </a>", $_nropedido, $_SERVER['PHP_SELF'], "eliminar");
$_fila = $_fila + 1;
echo sprintf("<tr class=\"%s\" onclick=\"window.open('../detalle_pedido.php?nropedido=%s')\" style=\"cursor:pointer;\" target=\"_blank\" title=\"Detalle\">", ((($_fila % 2) == 0)? "par" : "impar"), $_nropedido);
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td>", $fecha, $_nropedido, $_nombre, $_eliminar);
echo sprintf("</tr>");
}
$_nro = $_nropedido;
}
} else {
?>
<tr>
<td scope="colgroup" colspan="3" height="25" align="center">No hay pedidos pendientes</td>
</tr>
<?php
}
?>
</table>
</div> <!-- Fin lista -->
<?php } ?>
<?php if ($_SESSION["_usrrol"] == "A" || $_SESSION["_usrrol"] == "M" || $_SESSION["_usrrol"] == "G" ){ ?>
<div class="barra">
<div class="bloque_5">
<h1>Pendientes</h1>
</div>
<?php if ($_SESSION["_usrrol"]!= "G"){ ?>
<div class="bloque_5" align="right">
<a href="../logica/exportar.pendientes.php" title="Exportar pendientes">
<img class="icon-xls-export"/>
</a>
</div>
<?php } ?>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblPendientes">
<thead>
<tr>
<td scope="col" width="20%" height="18">Fecha</td>
<td scope="col" width="20%">Pedido</td>
<td scope="col" width="50%">Cliente</td>
</tr>
</thead>
<?php
$_pedidos_recientes = DataManager::getPedidos(NULL, 1);
if ($_pedidos_recientes){
$_nro = 0;
$_fila = 0;
foreach ($_pedidos_recientes as $k => $_pedidoRec) {
$fecha = $_pedidoRec["pfechapedido"];
$_nropedido = $_pedidoRec["pidpedido"];
$_idemp = $_pedidoRec["pidemp"];
$_cliente = $_pedidoRec["pidcliente"];
$_nombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $_cliente, $_idemp);
if($_nro != $_nropedido) {
$_fila = $_fila + 1;
echo sprintf("<tr class=\"%s\" onclick=\"window.open('../detalle_pedido.php?nropedido=%s')\" style=\"cursor:pointer;\" target=\"_blank\" title=\"Detalle\">", ((($_fila % 2) == 0)? "par" : "impar"), $_nropedido);
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td>", $fecha, $_nropedido, $_nombre);
echo sprintf("</tr>");
}
$_nro = $_nropedido;
}
} else {
?>
<tr>
<td scope="colgroup" colspan="3" height="25" align="center">No hay pedidos pendientes</td>
</tr>
<?php
}
?>
</table>
</div> <!-- Fin lista -->
<?php } ?>
</div> <!-- Fin datos -->
<div class="box_seccion">
<div class="barra">
<h1>Estado de Pedidos</h1>
</div>
<div class="temas2">
<a href="http://clientes.cruzdelsur.com/" target="_blank">
<div class="box_mini2">
Web <br> Cruz Del Sur
</div> <!-- box_mini -->
</a>
<a href="javascript:dac_exportar(6);">
<div class="box_mini2">
Listados <br> Cartas de Porte
</div> <!-- box_mini -->
</a>
</div>
<div class="temas2">
<a href="https://neo-farma.com.ar/pedidos/informes/archivos/PedidosPendientes.xls" >
<div class="box_mini2">
Seguimiento Pedidos <br> <p>Neo-farma</p>
</div>
</a>
<a href="https://neo-farma.com.ar/pedidos/informes/archivosgezzi/PedidosPendientes.xls" >
<div class="box_mini2">
Seguimiento Pedidos <br> <p>Gezzi</p>
</div>
</a>
</div>
</div>
<hr>
<hr>
<script type="text/javascript">
function dac_exportar(nro){
switch (nro){
case 6:
if (confirm("ATENCI\u00d3N: Se proceder\u00e1 a descargar un archivo por cada una de las zonas que le corresponda. Si no consigue hacerlo, p\u00f3ngase en contacto con el administrador de la web. Si no encuentra el archivo descargado, busque en la carpeta descargas de la PC. \u00A1Gracias!")) {
<?php
$zona = explode(', ', $_SESSION["_usrzonas"]);
for($i = 0; $i < count($zona); $i++){
$_archivo = $_SERVER["DOCUMENT_ROOT"]."/pedidos/informes/archivos/cartasdeporte/".trim($zona[$i])."_Carta-de-Porte.XLS";
if (file_exists($_archivo)){ ?>
archivo = <?php echo trim($zona[$i]); ?>+'_Carta-de-Porte.XLS';
direccion = 'https://neo-farma.com.ar/pedidos/informes/archivos/cartasdeporte/'+archivo;
window.open(direccion, '_blank');
direccion = ""; <?php
}else{ ?>
alert("No hay Carta de Porte correspondiente a la zona <?php echo trim($zona[$i]); ?>"); <?php
}
} ?>
}
break;
}
}
</script><file_sep>/planificacion/logica/ajax/update.planificacion.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//*******************************************
$_enviar = (isset($_POST['enviar'])) ? $_POST['enviar'] : NULL;
$_cantplanif = (isset($_POST['cantplanif'])) ? $_POST['cantplanif'] : NULL;
$_fecha_plan = (isset($_POST['fecha_plan'])) ? $_POST['fecha_plan'] : NULL;
$_planifcliente = json_decode(str_replace ('\"','"', $_POST['planifcliente_Obj']), true);
$_planifnombre = json_decode(str_replace ('\"','"', $_POST['planifnombre_Obj']), true);
$_planifdir = json_decode(str_replace ('\"','"', $_POST['planifdir_Obj']), true);
//*************************************************
//Controlo campos
//*************************************************
//controla si el envío de la planif ya fue realizado
$_planificado = DataManager::getDetallePlanificacion($_fecha_plan, $_SESSION["_usrid"]);
if (count($_planificado)){
foreach ($_planificado as $k => $_planifcontrol){
$_planifcontrol = $_planificado[$k];
$_planifcontrolactiva = $_planifcontrol["planifactiva"];
if($_planifcontrolactiva == 0){
echo "La planificación YA fue enviada. No puede ser modificada."; exit;
}
}
}
//*************************************************
//Controlo campos
//*************************************************
//controla que no se hayan repetido idclientes.
for($i = 0; $i < $_cantplanif; $i++){
if($_planifcliente[$i] != 0){ //discrimina el cero que serían clientes nuevos
for($j = 0; $j < $_cantplanif; $j++){
if (($_planifcliente[$i] == $_planifcliente[$j]) && ($i!=$j)){
echo "No puede cargarse la misma cuenta ".$_planifcliente[$i]." más de una vez."; exit;
}
}
}
}
//*************************************************
$date = $_fecha_plan;
list($dia, $mes, $ano) = explode('-', str_replace('/', '-', $date));
$_fecha_plan = $ano."-".$mes."-".$dia;
//*******************************************
//BORRO EL REGISTRO EN ESA FECHA Y ESE VENDEDOR
//*******************************************
$ID = DataManager::deleteFromPlanificado($_SESSION["_usrid"], $_fecha_plan);
//*******************************************
// GRABO LA PLANIFICACIÓN
//*******************************************
for($i = 0; $i < $_cantplanif; $i++){
if (!empty($_planifcliente[$i])){
if(empty($_planifnombre[$i]) || empty($_planifdir[$i])){
echo "Hubo un error al cargar los datos. Revise y vuelva a intentarlo"; exit;
}
$_planifobject = DataManager::newObjectOfClass('TPlanificacion');
$_planifobject->__set('ID', $_planifobject->__newID());
$_planifobject->__set('IDVendedor', $_SESSION["_usrid"]);
$_planifobject->__set('Fecha', $_fecha_plan);
$_planifobject->__set('Cliente', $_planifcliente[$i]);
$_planifobject->__set('Nombre', $_planifnombre[$i]);
$_planifobject->__set('Direccion', $_planifdir[$i]);
if ($_enviar == 1){
//Al realizar el envío, se crea el objeto para cargarlo también como parte diario
$_parteobject = DataManager::newObjectOfClass('TPartediario');
$_parteobject->__set('ID' , $_parteobject->__newID());
$_parteobject->__set('IDVendedor', $_SESSION["_usrid"]);
$_parteobject->__set('Fecha' , $_fecha_plan);
$_parteobject->__set('Cliente' , $_planifcliente[$i]);
$_parteobject->__set('Nombre' , $_planifnombre[$i]);
$_parteobject->__set('Direccion', $_planifdir[$i]);
$_parteobject->__set('Envio' , date("2001-01-01 00:00:00"));
$_parteobject->__set('Activa' , '1');
$ID_parte = DataManager::insertSimpleObject($_parteobject);
if (empty($ID_parte)) { echo "Error Parte. $ID."; exit; }
//una vez cargado como parte diario, se desactiva como planificado ya que fué enviado y se graba la fecha
$_planifobject->__set('Envio' , date("Y-m-d H:i:s"));
$_planifobject->__set('Activa' , '0');
} else {
$_planifobject->__set('Envio' , date("2001-01-01 00:00:00"));
$_planifobject->__set('Activa' , '1');
}
$ID = DataManager::insertSimpleObject($_planifobject);
if (empty($ID)) { echo "Error. $ID."; exit; }
}
}
echo $_enviar;
?><file_sep>/soporte/motivos/logica/jquery/script.js
$(function(){"use strict"; $('#sector').change(changeSector); });
function changeSector() {
"use strict";
$('#motid').val("");
$('#responsable').val("");
$('#motivo').val("");
var idSector = $("#sector").val();
getMotivos(idSector);
}
function getMotivos(idSector) {
"use strict";
$.ajax({
type : 'POST',
cache : false,
data : {sector : idSector},
url : 'logica/ajax/getMotivos.php',
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
$('#box_cargando').css({'display':'none'});
if (resultado){
document.getElementById('tablamotivos').innerHTML = resultado;
} else {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
},
});
}
function dac_changeMotivo(id, motivo, usrresponsable) {
"use strict";
$('#motid').val(id);
$('#motivo').val(motivo);
$('#responsable').val(usrresponsable).change();
}
<file_sep>/transfer/logica/exportar.historial.total.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=PedidosTransfers-".date('d-m-y').".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos (Pedidos Transfers) .::</TITLE>
<head></head>
<body>
<table border="0">
<thead>
<tr>
<td scope="col" >Fecha</td>
<td scope="col" >Transfer</td>
<td scope="col" >Dni</td>
<td scope="col" >Vendedor</td>
<td scope="col" >Id Drogueria</td>
<td scope="col" >Drogueria</td>
<td scope="col" >Cliente en Drog</td>
<td scope="col" >Cliente en Neo</td>
<td scope="col" >Cliente</td>
<td scope="col" >ID Artículo</td>
<td scope="col" >Artículo</td>
<td scope="col" >Cantidad</td>
<td scope="col" >Precio</td>
<td scope="col" >Descuento</td>
<td scope="col" >Precio Finalo</td>
<td scope="col" >Importe Total</td>
</tr>
</thead>
<?php
$_transfers_recientes = DataManager::getTransfers(0);
if($_transfers_recientes){
for( $k=0; $k < count($_transfers_recientes); $k++ ){
$_transfer_r = $_transfers_recientes[$k];
$fecha = explode(" ", $_transfer_r["ptfechapedido"]);
list($ano, $mes, $dia) = explode("-", $fecha[0]);
$_fecha = $dia."-".$mes."-".$ano;
$_nropedido = $_transfer_r["ptidpedido"];
$_nombre = $_transfer_r["ptclirs"];
$_detalles = DataManager::getTransfersPedido(NULL, NULL, NULL, NULL, NULL, NULL, $_nropedido); //DataManager::getDetallePedidoTransfer($_nropedido);
if ($_detalles) {
for( $j=0; $j < count($_detalles); $j++ ){
$_precio_final = 0;
$_importe_final = 0;
$_detalle = $_detalles[$j];
$_idvendedor = $_detalle['ptidvendedor'];
$_nombreven = DataManager::getUsuario('unombre', $_idvendedor);
$_dniven = DataManager::getUsuario('udni', $_idvendedor);
$_iddrogueria = $_detalle['ptiddrogueria'];
$ctaId = $_detalle['ptidclineo'];
$ctaIdCuenta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $ctaId);
$_nombredrog = strtoupper(DataManager::getCuenta('ctanombre', 'ctaid', $ctaIdCuenta));
$_idcliente_drog = $_detalle['ptnroclidrog'];
if ($ctaId != 0){
$_idcliente_neo = $ctaId;
} else {
$_idcliente_neo = "";
}
$_contacto = $_detalle['ptcontacto'];
$_unidades = $_detalle['ptunidades'];
$_descuento = $_detalle['ptdescuento'];
$_ptidart = $_detalle['ptidart'];
$_ptprecio = $_detalle['ptprecio'];
$_descripcion = DataManager::getArticulo('artnombre', $_ptidart, 1, 1);
$_precio_final = round( ($_ptprecio - (($_descuento/100)*$_ptprecio)), 3);
$_importe_final = round( $_precio_final * $_unidades, 3);
echo sprintf("<tr align=\"left\">");
echo sprintf("<td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>", $_fecha, $_nropedido, $_dniven, $_nombreven, $_iddrogueria, $_nombredrog, $_idcliente_drog, $_idcliente_neo, $_nombre, $_ptidart, $_descripcion, $_unidades, $_ptprecio, $_descuento, number_format($_precio_final,2), number_format($_importe_final,2));
echo sprintf("</tr>");
}
}
}
}
?>
</table>
</body>
</html>
<file_sep>/relevamiento/relevar/logica/update.relevar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_nrorel = (isset($_POST['nrorel'])) ? $_POST['nrorel'] : NULL;
$_origenid = (isset($_POST['origenid'])) ? $_POST['origenid'] : NULL;
$_origen = (isset($_POST['origen'])) ? $_POST['origen'] : NULL;
$_relevamiento = DataManager::getRelevamiento($_nrorel, 1);
if (count($_relevamiento)) {
foreach ($_relevamiento as $k => $_rel) {
$_reltiporesp = $_rel["reltiporesp"];
$_relpregunta = $_rel["relpregunta"];
$_reladmitenulo = $_rel["reladmitenulo"];
$_resid[$k] = (isset($_POST["resid".$k])) ? $_POST["resid".$k] : NULL;
switch ($_reltiporesp){
case 'sino':
$_respuesta[$k] = (isset($_POST["sino".$k])) ? $_POST["sino".$k] : NULL;
break;
case 'cant':
$_respuesta[$k] = (isset($_POST["cant".$k])) ? $_POST["cant".$k] : NULL;
if (!empty($_respuesta[$k]) && !is_numeric($_respuesta[$k])) {
echo "Responda a la pregunta ".($k+1)." correctamente. </br>".$_relpregunta; exit;
}
break;
case 'abierto':
$_respuesta[$k] = (isset($_POST["respuesta".$k])) ? $_POST["respuesta".$k] : NULL;
if ($k == 2 || $k == 4 || $k == 6 || $k == 8){
if($_POST["sino".($k-1)] == 1){
if (empty($_respuesta[$k])) {
echo "Debe indicar: ".$_relpregunta; exit;
}
}
}
break;
default: echo "Error en el tipo de respuesta"; exit;
break;
}
}
} else {
echo "Error al intenta grabar los datos. Consulte con el administrador de la web."; exit;
}
if(empty($_origenid) || empty($_origen)){
echo "Error al intenta grabar los datos. Consulte con el administrador de la web."; exit;
}
//**************************//
// Acciones Guardar //
//**************************//
if (count($_relevamiento)) {
foreach ($_relevamiento as $k => $_rel) {
$_resobject = ($_resid[$k]) ? DataManager::newObjectOfClass('TRespuesta', $_resid[$k]) : DataManager::newObjectOfClass('TRespuesta');
$_relid = $_rel["relid"];
$_resobject->__set('IDRelevamiento' , $_relid);
$_resobject->__set('Respuesta' , $_respuesta[$k]);
$_resobject->__set('Origen' , $_origen);
$_resobject->__set('IDOrigen' , $_origenid);
$_resobject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$_resobject->__set('LastUpdate' , date("Y-m-d"));
if ($_resid[$k]) {
//Modifica Cliente
$ID = DataManager::updateSimpleObject($_resobject);
} else {
$_resobject->__set('ID' , $_resobject->__newID());
$_resobject->__set('Activa' , 1);
$ID = DataManager::insertSimpleObject($_resobject);
}
}
//Registra el movimiento del usuario//
$movimiento = 'REL_RELEVADO_NROREL_'.$_nrorel;
dac_registrarMovimiento($movimiento, "UPDATE", "TPedido", $_nrorel);
echo "1"; exit;
}
echo "Error al intenta grabar los datos. Consulte con el administrador de la web."; exit;
?><file_sep>/noticias/logica/changestatus.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$_idnt = empty($_REQUEST['idnt']) ? 0 : $_REQUEST['idnt'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/noticias/': $_REQUEST['backURL'];
if ($_idnt) {
$_noticia = DataManager::newObjectOfClass('TNoticia', $_idnt);
$_status = ($_noticia->__get('Activa')) ? 0 : 1;
$_noticia->__set('Activa', $_status);
$ID = DataManager::updateSimpleObject($_noticia);
}
header('Location: '.$backURL.'?pag='.$_pag);
?><file_sep>/usuarios/logica/update.zonaven.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_uid = empty($_REQUEST['uid']) ? 0 : $_REQUEST['uid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/usuarios/': $_REQUEST['backURL'];
$_zonas = $_POST['zzonas'];
$_SESSION['s_zonas'] = $_zonas;
if ($_uid) {
DataManager::deletefromtabla('zonas_vend', 'uid', $_uid);
$_campos = "uid, zona";
$_tabla = "zonas_vend";
if(count($_zonas) > 0){
foreach($_zonas as $nrozona){
//echo "XXX $_tabla, $_campos, $_uid, $nrozona ZZZZ";
DataManager::insertfromtabla($_tabla, $_campos, $_uid, $nrozona);
}
}
}
unset($_SESSION['s_zonas'] );
header('Location:' . $backURL);
?><file_sep>/rendicion/logica/ajax/update.rendicion.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$_retencion = (isset($_REQUEST['ret'])) ? $_REQUEST['ret'] : '0.00';
$_deposito = (isset($_REQUEST['dep'])) ? $_REQUEST['dep'] : '0.00';
$_nrorendicion = (isset($_REQUEST['rendicion'])) ? $_REQUEST['rendicion']: NULL;
$_retencion = empty($_retencion)? '0.00' : $_retencion;
$_deposito = empty($_deposito) ? '0.00' : $_deposito;
if(empty($_nrorendicion)){
echo "No se verifica el número de rendición."; exit;
}
$_rendiciones = DataManager::getRendicion($_SESSION["_usrid"], $_nrorendicion, '1');
if (count($_rendiciones)){
foreach ($_rendiciones as $k => $_rendicion) {
$_rendid = $_rendicion['rendid'];
$_rendicionbject= DataManager::newObjectOfClass('TRendicion', $_rendid);
$_rendicionbject->__set('Retencion', $_retencion);
$_rendicionbject->__set('Deposito', $_deposito);
DataManager::updateSimpleObject($_rendicionbject);
echo 1; exit;
}
} else {
echo "El valor no puede modificarse. Esta rendición YA fue enviada." ;
}
?><file_sep>/listas/logica/changestatus.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$id = empty($_REQUEST['id']) ? 0 : $_REQUEST['id'];
$backURL= empty($_REQUEST['backURL']) ? '/pedidos/listas/': $_REQUEST['backURL'];
if ($id) {
$listObject= DataManager::newObjectOfClass('TListas', $id);
$_status = ($listObject->__get('Activa')) ? 0 : 1;
$listObject->__set('Activa', $_status);
DataManagerHiper::updateSimpleObject($listObject, $id);
DataManager::updateSimpleObject($listObject);
}
// Registro MOVIMIENTO //
$movTipo = 'UPDATE';
$movimiento = 'ChangeStatusTo_'.$_status;
dac_registrarMovimiento($movimiento, $movTipo, "TListas", $id);
header('Location: '.$backURL);
?><file_sep>/newsletter/logica/newsletter.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
//**********************************
//envío por MAIL
//**********************************
//lista clientes activos de empresa 1 neo-farma
$pag = 0;
$rows = 9999;
$empresa = 1;
$mostrarTodos = 1;
$newsletter = '<img src="../felicesfiestas-neo.jpg" width="600" height="600"/>';
$clientes = DataManager::getClientes($pag, $rows, $empresa, $mostrarTodos); //la última página vendrá incompleta
for( $k=0; $k < count($clientes); $k++ ) {
if ($k > 1150){ //&& $k < 1152 //El if se usa por si el proceso de envío se cuelga, para continuar desde el último K enviado.
//Son 120 por hora
$cliente = $clientes[$k];
$idCliente = $cliente['cliidcliente'];
//$correoNombre = $cliente['clinombre'];
$correo = $cliente['clicorreo']; //"<EMAIL>";//
if (!empty($correo)){
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = "<EMAIL>";
$mail->FromName = "Neo-farma - Distrubuidor de Laboratorio GEZZI";
$mail->Subject = "Felices Fiestas!";
$mensaje = "¡Felices Fiestas! Es un deseo de Neo-farma de Laboratorio GEZZI";
$total = '
<html>
<head>
<title>Email de Empresa</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 90%;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 0px;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>
<body style="text-align: center;">
<div align="center">
<table width="600" border="0" cellspacing="1">
<tr>
<td>
<div class="texto" style="float: left;
height: auto;
width: 90%;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 0px;">
'.$mensaje.'
<div />
</td >
</tr>
<tr>
<td>'.$newsletter.'</td>
</tr>
<tr align="center" class="saludo" style="width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;">
<td valign="top">
<div class="saludo" align="left" style="width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;">
Gracias por confiar en nosotros.<br/>
Le saludamos atentamente,
</div>
</td>
</tr>
</table>
<div/>
</body>
';
$mail->msgHTML($total);
//$mail->AddAddress('<EMAIL>', "PARA" $para);
//$mail->AddAddress($correo);
$mail->AddBCC($correo); //, $correoNombre);
//$mail->AddBCC("<EMAIL>");
echo "</br>".($k+1)." de ".count($clientes)." clientes enviado. </br>";
//Sobreescribe en una tabla de servido, el último K recorrido por si luego hay que hacerlo manual.
if(!$mail->Send()) {
echo "</br>Fallo de envío del cliente: ".$idCliente."</br>";
}
echo "</br>";
sleep(30);
} else {
echo "</br>".($k+1)." de ".count($clientes)." Cliente con correo VACIO. </br>";
}///fin control correo vacío
}
}
echo "</br></br> ¡SE HAN ENVIADO TODOS LOS NEWSLATTERS!</br></br>";
?> <a href="<?php echo $_SERVER['HTTP_REFERER']."/"; ?>">Volver</a><?php echo "</br></br></br>";
exit;
?><file_sep>/cadenas/logica/ajax/getCuentas.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
exit;
}
//*************************************************
$empresa = (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
//*************************************************
$cuentas = DataManager::getCuentas(0, 0, $empresa, NULL, "'C', 'CT', 'T', 'TT'", $_SESSION["_usrzonas"]);
if (count($cuentas)) {
echo '<table id="tblCuentas" style="table-layout:fixed;">';
echo '<thead><tr align="left"><th>Id</th><th>Nombre</th><th>Localidad</th></tr></thead>';
echo '<tbody>';
foreach ($cuentas as $k => $cta) {
$id = $cta['ctaid'];
$idCuenta = $cta['ctaidcuenta'];
$nombre = $cta['ctanombre'];
$localidad = $cta['ctaidloc'];
$localidadNombre = DataManager::getLocalidad('locnombre', $localidad);
$localidadNombre = (empty($localidadNombre) ? $cta['ctalocalidad'] : $localidadNombre);
((($k % 2) == 0)? $clase="par" : $clase="impar");
if($idCuenta != 0){
echo "<tr id=cuenta".$id." class=".$clase." style=\"cursor:pointer;\" onclick=\"javascript:dac_cuentaRelacionada('$id', '$idCuenta', '$nombre')\">";
echo "<td>".$idCuenta."</td><td>".$nombre."</td><td>".$localidadNombre."</td>";
echo "</tr>";
}
}
echo "</tbody></table>";
} else {
echo '<table><thead><tr><th align="center">No hay registros activos.</th></tr></thead></table>'; exit;
}
?><file_sep>/pedidos/logica/changestatus.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_nropedido = empty($_REQUEST['nropedido']) ? 0 : $_REQUEST['nropedido'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/pedidos/' : $_REQUEST['backURL'];
if ($_nropedido) {
$_detalles = DataManager::getPedidos(NULL, NULL, $_nropedido);
if ($_detalles) {
foreach ($_detalles as $k => $_detalle) {
$_idPedido = $_detalle["pid"];
$_pedidoObject = DataManager::newObjectOfClass('TPedido', $_idPedido);
$_status = ($_pedidoObject->__get('Activo')) ? 0 : 1;
$_pedidoObject->__set('Activo', $_status);
$ID = DataManager::updateSimpleObject($_pedidoObject);
}
//--------------//
// MOVIMIENTO //
$movimiento = 'PEDIDO_CHANGESTATUS_'.$_nropedido;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TPedido", $_nropedido);
}
}
header('Location: '.$backURL);
?><file_sep>/login/registrarme/logica/update.registrarme.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/detect.Browser.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php");
//---------------------------------------------
/*Forma de ller todo el form sin llamar por sus normbres*/
/*foreach ($_POST as $key => $value) {
echo '<p><strong>' . $key.':</strong> '.$value.'</p>';
}*/
$empresa = (isset($_POST['empselect'])) ? $_POST['empselect'] : NULL;
$_razonsocial = (isset($_POST['razonsocial'])) ? $_POST['razonsocial'] : NULL;
$_provincia = (isset($_POST['provincia'])) ? $_POST['provincia'] : NULL;
$_localidad = (isset($_POST['localidad'])) ? $_POST['localidad'] : NULL;
$_direccion = (isset($_POST['direccion'])) ? $_POST['direccion'] : NULL;
$_codpostal = (isset($_POST['codpostal'])) ? $_POST['codpostal'] : NULL;
$_cuit = (isset($_POST['cuit'])) ? $_POST['cuit'] : NULL;
$_nroIBB = (isset($_POST['nroIBB'])) ? $_POST['nroIBB'] : NULL;
$_telefono = (isset($_POST['telefono'])) ? $_POST['telefono'] : NULL;
$_usuario = (isset($_POST['usuario'])) ? $_POST['usuario'] : NULL;
$_email = (isset($_POST['email'])) ? $_POST['email'] : NULL;
$_emailconfirm = (isset($_POST['emailconfirm'])) ? $_POST['emailconfirm'] : NULL;
$_clave = (isset($_POST['clave'])) ? $_POST['clave'] : NULL;
$_web = (isset($_POST['web'])) ? $_POST['web'] : NULL;
$_comentario = (isset($_POST['comentario'])) ? $_POST['comentario'] : NULL;
//$_valor_captcha = (isset($_POST['g-recaptcha-response'])) ? $_POST['g-recaptcha-response'] : NULL;
$_empresas = DataManager::getEmpresas(1);
if (count($_empresas)) {
foreach ($_empresas as $k => $_emp) {
$_idemp = $_emp["empid"];
if ($_idemp == $empresa){
$_nombreemp = $_emp["empnombre"];
}
}
}
//**********************************************************
$_SESSION['razonsocial'] = $_razonsocial;
$_SESSION['provincia'] = $_provincia;
$_SESSION['localidad'] = $_localidad;
$_SESSION['direccion'] = $_direccion;
$_SESSION['codpostal'] = $_codpostal;
$_SESSION['cuit'] = $_cuit;
$_SESSION['nroIBB'] = $_nroIBB;
$_SESSION['usuario'] = $_usuario;
$_SESSION['telefono'] = $_telefono;
$_SESSION['email'] = $_email;
$_SESSION['emailconfirm'] = $_emailconfirm;
$_SESSION['clave'] = $_clave;
$_SESSION['web'] = $_web;
$_SESSION['comentario'] = $_comentario;
//**********************************************************
if (empty($_razonsocial)) {
$_goURL = "../index.php?sms=1";
header('Location:' . $_goURL); exit;
}
if (!dac_validarCuit($_cuit)) {
$_goURL = "../index.php?sms=2";
header('Location:' . $_goURL); exit;
}
$_cuit = dac_corregirCuit($_cuit);
if (empty($_nroIBB)) {
$_goURL = "../index.php?sms=24";
header('Location:' . $_goURL); exit;
}
if ($_provincia == 0) {
$_goURL = "../index.php?sms=13";
header('Location:' . $_goURL); exit;
}
if ($_localidad == "Seleccione Localidad...") {
$_goURL = "../index.php?sms=14";
header('Location:' . $_goURL); exit;
}
if (empty($_direccion)) {
$_goURL = "../index.php?sms=16";
header('Location:' . $_goURL); exit;
}
if (!empty($_codpostal) && !is_numeric($_codpostal)) {
$_goURL = "../index.php?sms=15";
header('Location:' . $_goURL); exit;
} else {
$_codpostal = 0;
}
if (empty($_telefono)) {
$_goURL = "../index.php?sms=3";
header('Location:' . $_goURL); exit;
}
//---------------------------------------------
// Comprobamos si el nombre de usuario y/o la cuenta de correo ya existían ( $checkusuario y $email_exist )
// AGREGAR UN CONTROL DE EN QUÉ FORMA SE QUIERE VALIDAD COMO ES UN NOMBRE DE USUARIO
if (!empty($_usuario)){
if(!ctype_alnum($_usuario)){ //el usuario solo sea alfanumérico
$_goURL = "../index.php?sms=18";
header('Location:' . $_goURL); exit;
}
$_ID = DataManager::getIDByField('TUsuario', 'ulogin', $_usuario);
$_ID2 = DataManager::getIDByField('TProveedor', 'provlogin', $_usuario);
if ($_ID || $_ID2){ //El usuario ya existe
$_goURL = "../index.php?sms=4";
header('Location:' . $_goURL); exit;
}
} else { //El usuario ya existe
$_goURL = "../index.php?sms=12";
header('Location:' . $_goURL); exit;
}
$_email = trim($_email, ' ');
if (!preg_match( "/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,4})$/", $_email )) {
$_goURL = "../index.php?sms=6";
header('Location:' . $_goURL); exit;
}
$_emailconfirm = trim($_emailconfirm, ' ');
if (strcmp ($_email , $_emailconfirm ) != 0){
$_goURL = "../index.php?sms=7";
header('Location:' . $_goURL); exit;
}
if (empty($_clave)) {
$_goURL = "../index.php?sms=8";
header('Location:' . $_goURL); exit;
}
//---------------------------------------------
//Se declaran las variables de la dirección de los archivos enviados a éste PHP
//---------------------------------------------
$_cant_files = 4;
$_maximo = 1024 * 1024 * 4;
$cont = 0;
for($i = 1; $i <= $_cant_files; $i++){
$archivo_nombre[$i] = dac_Normaliza($_FILES["archivo".$i]["name"]);
$archivo_peso[$i] = $_FILES["archivo".$i]["size"];
$archivo_temporal[$i] = $_FILES["archivo".$i]["tmp_name"];
if($archivo_peso[$i] != 0){
$cont++;
if($archivo_peso[$i] > $_maximo){
$_goURL = "../index.php?sms=11";
header('Location:' . $_goURL); exit;
}
}
}
if ($cont < 1){
$_goURL = "../index.php?sms=10";
header('Location:' . $_goURL); exit;
}
//Controlo las extensiones de los archivos cargados que sean PDF o IMAGEN
for($i = 1; $i <= $_cant_files; $i++){
# Si hay algun archivo que subir
# Recorremos todos los arhivos que se han subido
if($archivo_nombre[$i]){
# Si es un formato de imagen/pdf
if($_FILES["archivo".$i]["type"]!="image/jpeg" && $_FILES["archivo".$i]["type"]!="image/pjpeg" && $_FILES["archivo".$i]["type"]!="image/gif" && $_FILES["archivo".$i]["type"]!="image/png" && $_FILES["archivo".$i]["type"]!="application/pdf") {
//Uno de los archivos no es imagen o pdf
//echo "<br>".$_FILES["archivo".$i]["name"]." - NO es imagen jpg o archivo pdf";
$_goURL = "../index.php?sms=22";
header('Location:' . $_goURL);
exit;
}
}
}
//controlo el captcha
/*
if (!dac_enviarDatosCaptcha($_valor_captcha)){
$_goURL = "../index.php?sms=20";
header('Location:' . $_goURL);
exit;
}*/
//---------------------------------------------
//agregamos la variable $_activate que es un numero aleatorio de
//20 digitos crado con la funcion genera_random de mas arriba
//para proveedores no la utilizao, ya que el alta la tienen que aprobar una vez hayan visto la documentación desde la web interna.
//$_activate = dac_generarRandom(20);
//aqui es donde insertamos los nuevos valosres en la BD activate y el estado --> valor 1 que es desactivado
//en el caso de proveedores coloco el campo activo en 3
//---------------------------------------------
$_provobject = DataManager::newObjectOfClass('TProveedor');
$_provobject->__set('ID', $_provobject->__newID());
$_provobject->__set('Empresa', $empresa);
$_provobject->__set('Proveedor', '0');
$_provobject->__set('Nombre', $_razonsocial);
$_provobject->__set('Login', $_usuario);
$_provobject->__set('Clave', md5($_clave));
$_provobject->__set('Direccion', $_direccion);
$_provobject->__set('Provincia', $_provid);
$_provobject->__set('Localidad', $_localidad);
$_provobject->__set('CP', $_codpostal);
$_provobject->__set('Cuit', $_cuit);
$_provobject->__set('NroIBB', $_nroIBB);
$_provobject->__set('Email', $_email);
$_provobject->__set('Web', $_web);
$_provobject->__set('Telefono', $_telefono);
$_provobject->__set('Observacion', $_comentario);
$_provobject->__set('Activo', 3);
//El 3 es para que no salga en listado de activos ni inactivos,
//y que en vez de crear nuevos proveedores con el +,
//solo se pueda dar de alta con éstos clientes ya modificados desde un apartado diferente
//***************************************//
$ID = DataManager::insertSimpleObject($_provobject);
//Control si se grabaron los datos de solicitud
if(!$ID){
//Error al registrar en la tabla proveedores
$_goURL = "../index.php?sms=20";
header('Location:' . $_goURL); exit;
}
//antes que insertar los datos, intento insertar la documentación
# definimos la carpeta destino
$_destino = "../archivos/proveedor/".$ID."/";
for($i = 1; $i <= $_cant_files; $i++){
# Si hay algun archivo que subir # Recorremos todos los arhivos que se han subido
if($archivo_nombre[$i]){ //$_FILES["archivo".$i]["name"]
# Si es un formato de imagen/pdf
if($_FILES["archivo".$i]["type"]=="image/jpeg" || $_FILES["archivo".$i]["type"]=="image/pjpeg" || $_FILES["archivo".$i]["type"]=="image/gif" || $_FILES["archivo".$i]["type"]=="image/png" || $_FILES["archivo".$i]["type"]=="application/pdf") {
# Si exsite la carpeta o se ha creado
if(file_exists($_destino) || @mkdir($_destino, 0777, true)) {
$info = new SplFileInfo($archivo_nombre[$i]);
$origen = $archivo_temporal[$i]; //$_FILES["archivo".$i]["tmp_name"];
$destino = $_destino.'documento'.$i.'F'.date("dmY").".".$info->getExtension(); //$_FILES["archivo".$i]["name"]
if(@move_uploaded_file($origen, $destino)) {
//echo "<br>".$_FILES["archivo".$i]["name"]." movido correctamente";
}else{
//echo "<br>No se ha podido mover el archivo: ".$_FILES["archivo".$i]["name"];
$_goURL = "../index.php?sms=23";
header('Location:' . $_goURL); exit;
}
} else {
//echo "<br>No se ha podido crear la carpeta: up/".$user;
$_goURL = "../index.php?sms=23";
header('Location:' . $_goURL); exit;
}
}else{
//Uno de los archivos no es imagen o pdf
$_goURL = "../index.php?sms=22";
header('Location:' . $_goURL); exit;
}
}
}
//**************************************************
// Armado del CORREO para el envío
//**************************************************
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = $_email;
$mail->FromName = "InfoWeb GEZZI";
$mail->Subject = " Datos de registro de ".$_usuario." en ".$_nombreemp.", guarde este email.";
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
$_total = '
<html>
<head>
<title>Notificación de Solicitud</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 90%;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 0px;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>
<body>
<div align="center">
<table width="600" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Se enviaron los datos de <strong>SOLICITUD DE ACTIVACIÓN</strong> en '.$_nombreemp.' como <b>'.$_usuario.' </b>de manera satisfactoria.<br /> ';
/*Le enviaremos ahora un email para activar su cuenta, al correo que nos facilito.<br />*/
$_total .='
<div />
</td >
</tr>
<tr bgcolor="#597D92">
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight: bold;">
<strong>Estos son sus datos de registro, '.$_usuario.'</strong>
</div>
</td>
</tr>
<tr>
<td height="95" valign="top">
<div class="texto">
<table width="600px" style="border:1px solid #597D92">
<tr>
<th rowspan="2" align="left" width="100">
Nombre:<br />
Usuario:<br />
Correo:
</th>
<th rowspan="2" align="left" width="250">
'.$_razonsocial.'<br />
'.$_usuario.'<br />
'.$_email.'
</th>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con la empresa al 4555-3366 de Lunes a Viernes de 10 a 17 horas.
</font>
<div style="color:#000000; font-size:12px;">
<strong>SE LE NOTIFICARA LA ACTIVACION DE SU CUENTA POR EL CORREO FACILITADO, cuando se hayan verificado y aceptado los datos de la solicitud.</strong></a></br></br>
</div>
</div>
</td>
</tr>
';
/*
<strong>SU LINK DE ACTIVACION:<br><a href="'.$_activateLink.'">'.$_activateLink.' </strong></a><br><br><br>
<strong>POR FAVOR HAGA CLICK EN LINK DE ARRIBA PARA ACTIVAR SU CUENRA Y ACCEDER A LA PAGINA SIN RESTRICCIONES</strong><br><br><br>
<strong>SI EL LINK NO FUNCIONA A LA PRIMERA INTENTELO UNA SEGUNDA, EL SERVIDOR A VECES TARDA EN PROCESAR LA PRIMERA ORDEN</strong><br><br><br>
*/
$_total .= '
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Gracias por registrarse en '.$_nombreemp.'<br />
Le Saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
';
$mail->msgHTML($_total);
$mail->AddAddress($_email, 'Solicitud de Alta en '.$_nombreemp);
$mail->AddBCC("<EMAIL>", "Infoweb");
switch($empresa) {
case 1:
$mail->AddBCC("<EMAIL>");
break;
case 3:
$mail->AddBCC("<EMAIL>");
break;
case 4:
$mail->AddBCC("<EMAIL>");
break;
default:
$mail->AddBCC("<EMAIL>");
break;
}
if(!$mail->Send()) {
//Si el envío falla, que mande otro mail indicando que la solicittud no fue correctamente enviada?=?
//echo 'Fallo en el envío';
$_goURL = "../index.php?sms=21";
header('Location:' . $_goURL);
exit;
}
//Envío exitoso
$_goURL = "../index.php?sms=30";
header('Location:' . $_goURL);
//*************************************//
unset($_SESSION['empselect']);
unset($_SESSION['razonsocial']);
unset($_SESSION['provincia']);
unset($_SESSION['localidad']);
unset($_SESSION['direccion']);
unset($_SESSION['codpostal']);
unset($_SESSION['cuit'] );
unset($_SESSION['nroIBB']);
unset($_SESSION['usuario']);
unset($_SESSION['telefono']);
unset($_SESSION['email']);
unset($_SESSION['emailconfirm']);
unset($_SESSION['clave']);
unset($_SESSION['web']);
unset($_SESSION['radio']);
unset($_SESSION['comentario']);
//*************************************//
exit;
?><file_sep>/includes/metas.inc.php
<title>LABORATORIO GEZZI | EXTRANET CORPORATIVA</title>
<link rel="shortcut icon" href="/pedidos/images/icons/icon.ico" type="image/x-icon" /> <!-- icono para la web en favoritos-->
<!--meta charset="utf-8"-->
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Language" content="es-es" />
<meta name="author" content="<EMAIL>" />
<meta name="description" content="extranet corporativa de neo-farma.com.ar" />
<meta name="keywords" content="laboratorio de elaboración y comercialización de especialidades medicinales en medicamentos de venta libre." />
<!-- EVITAR POSICIONAR LAS URL EN GOOGLE-->
<meta name="Robots" content="nofollow" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<!-- ESTILOS CSS-->
<link rel="stylesheet" type="text/css" href="/pedidos/css/all.css" media="screen" />
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600" media="screen" />
<!-- JQUERY-->
<script language="JavaScript" src="/pedidos/js/jquery/jquery-2.1.1.min.js" type="text/javascript"></script> <!--Versión minimizada-->
<!-- Scripts CALENDARIO -->
<link rel="stylesheet" type="text/css" media="all" href="/pedidos/css/jsDatePick_ltr.min.css"/>
<script type="text/javascript" src="/pedidos/js/jsDatePick.min.1.3.js"></script>
<!-- Scripts funcion BUSCAR en tablas transfer-->
<script language="JavaScript" type="text/javascript" src="/pedidos/js/buscar-en-tabla.js"></script>
<!-- Scripts para BOTONES ADJUNTAR archivos -->
<!-- El sig Scripts permite que BOTONES ADJUNTAR archivos, se muestren con una imagen -->
<script type="text/javascript" src="/pedidos/js/BotonFileAdjuntar.js"></script>
<!-- Scripts para Provincias y localidades -->
<script type="text/javascript" src="/pedidos/js/provincias/selectScript.provincia.js"></script>
<script type="text/javascript" src="/pedidos/js/provincias/selectScript.localidad.js"></script>
<!-- Scripts FUNCIONES COMUNES -->
<script language="JavaScript" type="text/javascript" src="/pedidos/js/funciones_comunes.js"></script>
<!-- Scripts para MAPA ARGENTINA -->
<script type="text/javascript" src="/pedidos/js/mapa/jquery.imagemapster.min.js"></script>
<!-- Scripts para RECAPCHA (control de formularios) https://www.google.com/recaptcha/admin#site/320675277?setup -->
<script src='https://www.google.com/recaptcha/api.js'></script>
<!-- Scripts FUNCIONES Jquery COMO VENTANA EMERGENTES Y DRAGGABLE TIPO WINDOWS-->
<script type="text/javascript" src="/pedidos/js/jquery-ui-1.10.4/js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/pedidos/js/jquery-ui-1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="/pedidos/js/jquery-ui-1.11.4/jquery-ui.structure.css"/>
<link rel="stylesheet" type="text/css" href="/pedidos/js/jquery-ui-1.11.4/jquery-ui.theme.css"/>
<script type="text/javascript" src="/pedidos/js/jquery.timepicker.js"></script>
<link rel="stylesheet" type="text/css" href="/pedidos/js/jquery.timepicker.css"/>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/cargaWeb.php"); ?>
<file_sep>/includes/class/class.movimiento.php
<?php
require_once('class.PropertyObject.php');
class TMovimientos extends PropertyObject {
protected $_tablename = 'movimiento';
protected $_fieldid = 'movid';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'movid';
$this->propertyTable['Operacion'] = 'movoperacion';
$this->propertyTable['Transaccion'] = 'movtransaccion';
$this->propertyTable['Origen'] = 'movorigen';
$this->propertyTable['OrigenId'] = 'movorigenid';
$this->propertyTable['Fecha'] = 'movfecha';
$this->propertyTable['Usuario'] = 'movusrid';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/includes/class/class.cuentarelacionada.php
<?php
require_once('class.PropertyObject.php');
class TCuentaRelacionada extends PropertyObject {
protected $_tablename = 'cuenta_relacionada';
protected $_fieldid = 'ctarelid';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'ctarelid';
$this->propertyTable['Cuenta'] = 'ctarelctaid'; //ctaid
$this->propertyTable['Drogueria'] = 'ctarelidcuentadrog'; //ctaid de la cuenta droguería relacionada
$this->propertyTable['Transfer'] = 'ctarelnroclientetransfer';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
/*public function __getFieldActivo() {
return $this->_fieldactivo;
}*/
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/transfer/gestion/liquidacion/detalle_liq.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_ptnropedido = empty($_REQUEST['idpedido'])? 0 : $_REQUEST['idpedido'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/transfer/gestion/liquidacion/': $_REQUEST['backURL'];
?>
<!DOCTYPE html>
<html >
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "transfer";
$_subsection = "liquidacion_transfer";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<div class="cbte">
<div class="cbte_header">
<div class="cbte_boxheader">
<?php
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
echo $cabeceraPedido;
?>
</div> <!-- cbte_boxheader -->
<div class="cbte_boxheader">
<h1>LIQUIDACIÓN TRANSFER</h1>
Guevara 1347 - CP1427 - Capital Federal - Tel: 4555-3366
</div> <!-- cbte_boxheader -->
</div>
<?php
if ($_ptnropedido) {
//******************************************//
// Consulta liquidaciones del transfer //
$_liquidaciones = DataManager::getDetalleLiquidacionTransfer(NULL, NULL, $_ptnropedido, NULL);
if ($_liquidaciones) {
foreach ($_liquidaciones as $k => $_liq){
$_liq = $_liquidaciones[$k];
if ($k==0){ ?>
<div class="cbte_boxcontent">
<div class="cbte_box">Nro. Transfer <?php echo $_ptnropedido;?></div>
</div> <!-- cbte_box_nro -->
<div class="cbte_boxcontent2">
<table id="tabla_liquidacion" name="tabla_liquidacion" class="tabla_liquidacion" border="0">
<thead>
<tr height="60px;"> <!-- Títulos de las Columnas -->
<th align="center">Liquidación</th>
<th align="center">Transfer</th>
<th align="center">Droguería</th>
<th align="center">Fecha Factura</th>
<th align="center">Artículo</th>
<th align="center">Cantidad</th>
<th align="center">PSL Unit.</th>
<th align="center">Desc. PSL</th>
<th align="center">Importe NC</th>
</tr>
</thead>
<tbody id="lista_liquidacion"> <?php
}
$_liqID = $_liq['liqid'];
$_drogid = $_liq['liqdrogid'];
$_liqFecha = dac_invertirFecha($_liq['liqfecha']);
$_liqFechaFact = dac_invertirFecha( $_liq['liqfechafact'] );
$_liqean = str_replace("", "", $_liq['liqean']);
$_articulo = DataManager::getFieldArticulo("artcodbarra", $_liqean) ;
$_nombreart = $_articulo['0']['artnombre'];
$_idart = $_articulo['0']['artidart'];
$_liqcant = $_liq['liqcant'];
$_liqunit = $_liq['liqunitario'];
$_liqdesc = $_liq['liqdescuento'];
$_liqimportenc = $_liq['liqimportenc'];
$_TotalNC += $_liqimportenc;
((($k % 2) != 0)? $clase="par" : $clase="impar");
// CONTROLA las Condiciones de las Liquidaciones y Notas de Crédito//
$_liqTransfer = $_ptnropedido;
include($_SERVER['DOCUMENT_ROOT']."/pedidos/transfer/gestion/liquidacion/logica/controles.liquidacion.php");
/*****************/
?>
<tr id="lista_liquidacion<?php echo $k;?>" class="<?php echo $clase;?>">
<input id="idliquid" name="idliquid[]" type="text" value="<?php echo $_liqID;?>" hidden/>
<td> <input id="fecha" name="fecha[]" type="text" size="7px" value="<?php echo $_liqFecha;?>" readonly/> </td>
<td><input id="transfer" name="transfer[]" type="text" size="7px" value="<?php echo $_liqTransfer;?>" style="border:none; text-align:center;" readonly/></td>
<td><input id="drogid" name="drogid[]" type="text" size="8px" value="<?php echo $_drogid;?>" style="border:none; text-align:center;" readonly/></td>
<td><input id="fechafact" name="fechafact[]" type="text" size="8px" value="<?php echo $_liqFechaFact;?>" style="border:none; text-align:center;" readonly/></td>
<td><?php echo $_idart." - ".$_nombreart; ?>
<input id="idart" name="idart[]" type="text" value="<?php echo $_idart;?>" readonly hidden/>
</td>
<td><input id="cant" name="cant[]" type="text" size="5px" value="<?php echo $_liqcant;?>" style="border:none; text-align:center;" readonly/></td>
<td><input id="unitario" name="unitario[]" type="text" size="8px" value="<?php echo $_liqunit;?>" style="border:none; text-align:center;" readonly/></td>
<td><input id="desc" name="desc[]" type="text" size="8px" value="<?php echo $_liqdesc;?>" style="border:none; text-align:center;" readonly/></td>
<td><input id="importe" name="importe[]" type="text" size="8px" value="<?php echo $_liqimportenc;?>" style="border:none; text-align:center;" readonly/></td>
</tr> <?php
} ?>
<tfoot>
<tr>
<th colspan="7" height="30px" style="border:none; font-weight:bold;"></th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;">Total</th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;"><?php echo $_TotalNC; ?></th>
</tr>
</tfoot>
</tbody> <?php
} else { ?>
<tr class="impar"><td colspan="8" align="center">No hay liquidaciones cargadas</td></tr><?php
} ?>
</table>
</div> <!-- cbte_boxcontent2 -->
<?php } ?>
</div>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/pedidos/logica/ajax/getCondiciones.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
$empresa = (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
$laboratorio = (isset($_POST['laboratorio'])) ? $_POST['laboratorio'] : NULL;
$condiciones = DataManager::getCondiciones(0, 0, 1, $empresa, $laboratorio, date("Y-m-d"));
if (count($condiciones)) {
echo '<table id="tblCondiciones" style="table-layout:fixed;">';
echo '<thead><tr align="left"><th scope="colgroup" height="18" align="left">Tipo</th><th scope="colgroup" align="left">Nombre</th></tr></thead>';
echo '<tbody>';
foreach ($condiciones as $k => $cond) {
$condId = $cond['condid'];
$condTipo = $cond['condtipo'];
$condCuentas = $cond['condidcuentas'];
$condNombre = $cond['condnombre'];
$condPago = $cond['condcondpago'];
$condObservacion = $cond['condobservacion'];
$condListaCondicion = $cond['condlista'];
if($condTipo == "Pack") {
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class=".$clase." style=\"cursor:pointer;\" onclick=\"javascript:dac_CargarCondicionComercial($empresa, $laboratorio, $condId, '$condTipo', '$condCuentas', '$condPago', '$condNombre', '$condObservacion', '$condListaCondicion')\">";
echo "<td>$condTipo</td>";
echo "<td>$condNombre</td>";
echo "</tr>";
}
}
echo "</tbody></table>";
exit;
} else {
echo '<table><tr><td align="center">No hay registros activos.</td></tr></table>'; exit;
}
?><file_sep>/transfer/gestion/abmtransferdrog/logica/exportar.abm.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_mes = empty($_REQUEST['mes']) ? 0 : $_REQUEST['mes'];
$_anio = empty($_REQUEST['anio']) ? 0 : $_REQUEST['anio'];
$_drogid = empty($_REQUEST['drogid']) ? 0 : $_REQUEST['drogid'];
$_drogueria = strtoupper(DataManager::getDrogueriaField('drogtnombre', $_drogid));
$_tipodrog = strtoupper(DataManager::getDrogueriaField('drogttipoabm ', $_drogid));
$_style_tit = 'align="center" style="background-color:#1876bc; color:#FFF; font-weight:bold;"';
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=".$_drogueria."-TFR-".$_mes.$_anio.".xls");
?>
<?php echo $_style_tit; ?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos (ABM Transfer) .::</TITLE>
<head></head>
<body>
<table id="tabla_bonif" name"tabla_bonif" class="tabla_bonif" border="2">
<thead>
<?php if($_tipodrog == 'B'){
?>
<tr> <!-- Títulos de las Columnas -->
<th <?php echo $_style_tit; ?>>MODULO (si aplica)</th>
<th <?php echo $_style_tit; ?>>CODIGO DE BARRAS</th>
<th <?php echo $_style_tit; ?>>DESCRIPCION</th>
<th <?php echo $_style_tit; ?>>% DESCUENTO A TRASLADAR SOBRE PSL</th>
<th <?php echo $_style_tit; ?>>MIN</th>
<th <?php echo $_style_tit; ?>>MAX</th>
<th <?php echo $_style_tit; ?>>MULT</th>
<th <?php echo $_style_tit; ?>>PLAZO</th>
<th <?php echo $_style_tit; ?>>COMPENSACION EN NC %</th>
<th <?php echo $_style_tit; ?>>COMPENSACION EN FACTURA LIBRE %</th>
</tr> <?php
} else { ?>
<tr> <!-- Títulos de las Columnas -->
<th <?php echo $_style_tit; ?>>LABORATORIO</th>
<th <?php echo $_style_tit; ?>>TIPO</th> <!-- TIPO TRF TD o TL -->
<th <?php echo $_style_tit; ?>>EAN</th> <!-- CODIGO DE BARRAS -->
<th <?php echo $_style_tit; ?>>DESCRIPCION</th>
<th <?php echo $_style_tit; ?>>% DESC SOBRE PSL</th> <!-- % DESCUENTO A TRASLADAR SOBRE PSL -->
<th <?php echo $_style_tit; ?>>MIN</th>
<th <?php echo $_style_tit; ?>>PLAZO</th>
<th <?php echo $_style_tit; ?>>% COMP NC</th> <!-- COMPENSACION EN NC % -->
</tr> <?php
} ?>
</thead>
<tbody><?php
/**************************************/
/*Consulta ABM del mes año y drogueria*/
/**************************************/
$_abms = DataManager::getDetalleAbm($_mes, $_anio, $_drogid, 'TD');
if ($_abms) {
foreach ($_abms as $k => $_abm){
$_abm = $_abms[$k];
$_abmID = $_abm['abmid'];
$_abmArtid = $_abm['abmartid'];
$_abmDesc = $_abm['abmdesc'];
$_abmDifComp= $_abm['abmdifcomp'];
//$estilo_fila = "background-color:#666; color:#FFF; font-weight:bold;";
?>
<?php if($_tipodrog == 'B'){ ?>
<tr style=" <?php /*echo $estilo;*/ ?> ">
<td></td>
<?php $_artean = DataManager::getArticulo('artcodbarra', $_abmArtid, 1, 1); ?>
<td align="center" style="mso-style-parent:style0; mso-number-format:\@;"><?php echo $_artean; ?> </td>
<?php $_artnombre = DataManager::getArticulo('artnombre', $_abmArtid, 1, 1); ?>
<td><?php echo $_artnombre; ?></td>
<td align="center" ><?php echo $_abmDesc." %"; ?></td>
<td align="center">1</td>
<td ></td><td ></td>
<td align="center">Habitual</td>
<td align="center"><?php echo ($_abmDesc - $_abmDifComp)." %"; ?></td>
<td ></td>
</tr> <?php
} else { ?>
<tr style=" <?php /*echo $estilo;*/ ?> ">
<td align="center">Laboratorios Gezzi SRL</td>
<td align="center" style="width:50px;">TD</td>
<?php $_artean = DataManager::getArticulo('artcodbarra', $_abmArtid, 1, 1); ?>
<td align="center" style="mso-style-parent:style0; mso-number-format:\@; width:120px;"><?php echo $_artean; ?> </td> <?php $_artnombre = DataManager::getArticulo('artnombre', $_abmArtid, 1, 1); ?>
<td><?php echo $_artnombre; ?></td>
<td align="center" style="width:50px;"><?php echo $_abmDesc." %"; ?></td>
<td align="center">1</td>
<td align="center">Habitual</td>
<td align="center" style="width:60px;"><?php echo $_abmDifComp." %";?></td>
<!--
La última columna tenía el siguiente cálculo -> *echo ($_abmDesc - $_abmDifComp)."%";*
pero estaba incorrecto ya que el valor de Compensación en NC% del excel es el % que se le paga a la droguería
y es el mismo que se ingresa en el ABM que estaba indicado como "Diferencia de Copmpensación" PERO???
se SUPONE que yo entendí que era DIF. de COMP. NUESTRO, cuando en realidad es DIF de COMP de DROGUERÍA.
-->
</tr> <?php
}
} //FIN del FOR
} ?>
</tbody>
<tfoot></tfoot>
</table>
</body>
</html>
<file_sep>/rendicion/logica/jquery/jqueryHeader.js
function dac_BuscarRecibo(rec, tal){
"use strict";
$.ajax({
url : 'logica/ajax/buscar.recibo.php',
data : { nrorecibo : rec,
nrotalonario : tal
},
type : 'GET',
beforeSend: function () {
$('#box_confirmacion2').css({'display':'none'});
$('#box_error2').css({'display':'none'});
$('#box_cargando2').css({'display':'block'});
$("#msg_cargando2").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
$('#box_cargando2').css({'display':'none'});
if (result){
if (result.replace("\n","") === '1'){
$('#box_confirmacion2').css({'display':'block'});
$("#msg_confirmacion2").html("El número de talonario no existe. Presione el botón 'Nuevo Talonario' si desea crearlo.");
} else {
document.getElementById("close-recibo").click();
$('#box_error2').css({'display':'block'});
$("#msg_error2").html(result);
}
} else {
//SALTA A LA SIGUIENTE VENTANA
document.getElementById("nro_tal").value = tal;
document.getElementById("nro_rec").value = rec;
document.getElementById("open-recibo").click();
}
},
error: function () {
$('#box_cargando2').css({'display':'none'});
$('#box_error2').css({'display':'block'});
$("#msg_error2").html("Error!");
}
});
}
function dac_NuevoTalonario(tal){
"use strict";
$.ajax({
url : 'logica/ajax/nuevo.talonario.php',
data : {nrotalonario : tal},
type : 'GET',
beforeSend: function () {
$('#box_confirmacion2').css({'display':'none'});
$('#box_error2').css({'display':'none'});
$('#box_cargando2').css({'display':'block'});
$("#msg_cargando2").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
if (result) {
$('#box_cargando2').css({'display':'none'});
if (result.replace("\n","") === '1'){
$('#box_confirmacion2').css({'display':'block'});
$("#msg_confirmacion2").html("El nuevo talonario fue creado.");
document.getElementById("open-recibo").click();
} else { alert(result); }
}
},
error: function () {
$('#box_cargando2').css({'display':'none'});
$('#box_error2').css({'display':'block'});
$("#msg_error2").html("Error!");
}
});
}
function dac_AnularRecibo(rendid, nro_rend, nro_tal, nro_rec){
"use strict";
$.ajax({
url : 'logica/ajax/anular.recibo.php',
data : {rendid : rendid,
nro_rend : nro_rend,
nro_tal : nro_tal,
nro_rec : nro_rec},
type : 'GET',
beforeSend: function () {
$('#box_confirmacion2').css({'display':'none'});
$('#box_error2').css({'display':'none'});
$('#box_cargando2').css({'display':'block'});
$("#msg_cargando2").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
if (result){
$('#box_cargando2').css({'display':'none'});
if (result.replace("\n","") === '1'){
$('#box_confirmacion2').css({'display':'block'});
$("#msg_confirmacion2").html("El recibo fue ANULADO.");
document.getElementById("close-recibo").click();
document.getElementById("close-talonario").click();
location.reload();
} else {
$('#box_cargando2').css({'display':'none'});
$('#box_error2').css({'display':'block'});
$("#msg_error2").html(result);
}
}
},
error: function () {
$('#box_cargando2').css({'display':'none'});
$('#box_error2').css({'display':'block'});
$("#msg_error2").html("Error!");
}
});
}
/* ALGUNOS controles para el formulario de nueva factura */
function dac_ValidarNumero(num, id){
"use strict";
var bruto, dto, total_neto, id_nro = 0;
if(isNaN(num)){
document.getElementById(id).value = "";
alert("Debe ingresar un valor numérico.");
}
if(id.substring(0, 13) === "importe_bruto"){
id_nro = id.substring(13, id.length);
if (document.getElementById('importe_dto'+id_nro).value === '0'){
document.getElementById('importe_neto'+id_nro).value = num;
} else {
bruto = num;
dto = document.getElementById('importe_dto'+id_nro).value;
total_neto = bruto - ((bruto * dto) / 100);
document.getElementById('importe_neto'+id_nro).value = total_neto;
}
dac_Calcular_Diferencia();
}
if(id.substring(0, 11) === "importe_dto"){
id_nro = id.substring(11, id.length);
dto = num;
bruto = document.getElementById('importe_bruto'+id_nro).value;
if (dto !== "") {
total_neto = bruto - ((bruto * dto) / 100);
document.getElementById('importe_neto'+id_nro).value = total_neto;
} else {
document.getElementById('importe_neto'+id_nro).value = bruto;
}
dac_Calcular_Diferencia();
}
if((id.substring(0, 13) === "pago_efectivo") || (id.substring(0, 13) === "pago_transfer") || (id.substring(0, 14) === "pago_retencion") || (id.substring(0, 15) === "pagobco_importe")){
dac_Calcular_Diferencia();
}
}
function dac_Calcular_Diferencia() {
"use strict";
//---------------------------------
//SUMA DE LOS TOTALES DE facturas
var factNumber = document.getElementsByName("nro_factura[]").length; //cantidad de facturass
var rowNumber = document.getElementsByName('pagobco_importe[]').length; //cantidad de cheques
var neto = 0;
var efect = 0;
var transf = 0;
var retenc = 0;
var importe = 0;
var suma = 0;
var diferencia = 0;
for (var j = 0; j < factNumber; j++){
var importe_neto = parseFloat(document.getElementsByName("importe_neto[]").item(j).value);
var pago_efectivo = parseFloat(document.getElementsByName("pago_efectivo[]").item(j).value);
var pago_transfer = parseFloat(document.getElementsByName("pago_transfer[]").item(j).value);
var pago_retencion = parseFloat(document.getElementsByName("pago_retencion[]").item(j).value);
if (!isNaN(importe_neto)){ neto = neto + importe_neto;}
if (!isNaN(pago_efectivo)){ efect = efect + pago_efectivo;}
if (!isNaN(pago_transfer)){ transf = transf + pago_transfer;}
if (!isNaN(pago_retencion)){ retenc = retenc + pago_retencion;}
}
for (var i = 0; i < rowNumber; i++){
var pagobco_importe = parseFloat(document.getElementsByName("pagobco_importe[]").item(i).value);
if (!isNaN(pagobco_importe)){ importe = importe + pagobco_importe;
}
}
suma = efect + transf + retenc + importe;
if (suma !== 0){
diferencia = suma - neto;
document.getElementById("diferencia").value = parseFloat(diferencia).toFixed(2);
}else{
document.getElementById("diferencia").value = "";
}
}
function dac_EnviarRecibo(){
"use strict";
var factNumber = document.getElementsByName("nro_factura[]").length; //cantidad de facturass
var rowNumber = document.getElementsByName("pagobco_importe[]").length; //cantidad de cheques
var rendid = document.getElementById("rendid").value;
var observacion = document.getElementById("observacion").value;
var diferencia = document.getElementById("diferencia").value;
//Otros datos para grabar
var nro_rendicion = document.getElementById("nro_rend").value;
var nro_tal = document.getElementById("nro_tal").value;
var nro_rec = document.getElementById("nro_rec").value;
//Declaro Objetos facturas
var nrofactObject ={};
var fechaObj ={};
var nombrecliObj ={};
var importe_dtoObj ={};
var importe_netoObj ={};
var importe_brutoObj={};
var pago_efectObj ={};
var pago_transfObj ={};
var pago_retenObj ={};
//Declaro Objetos Cheques
var bco_nombreObj ={};
var bco_nrochequeObj={};
var bco_fechaObj ={};
var bco_importeObj ={};
//por cant de facturas
for (var i = 0; i < factNumber; i++){
nrofactObject[i] = document.getElementsByName("nro_factura[]").item(i).value; // nro_factura[i].value;
fechaObj[i] = document.getElementsByName("fecha_factura[]").item(i).value; // fecha_factura[i].value;
nombrecliObj[i] = document.getElementsByName("nombrecli[]").item(i).value; // nombrecli[i].value;
importe_dtoObj[i] = document.getElementsByName("importe_dto[]").item(i).value; // importe_dto[i].value;
importe_netoObj[i] = document.getElementsByName("importe_neto[]").item(i).value; // importe_neto[i].value;
importe_brutoObj[i] = document.getElementsByName("importe_bruto[]").item(i).value; // importe_bruto[i].value;
pago_efectObj[i] = document.getElementsByName("pago_efectivo[]").item(i).value; // pago_efectivo[i].value;
pago_transfObj[i] = document.getElementsByName("pago_transfer[]").item(i).value; // pago_transfer[i].value;
pago_retenObj[i] = document.getElementsByName("pago_retencion[]").item(i).value; // pago_retencion[i].value;
}
//según cant de cheques
for (i = 0; i < rowNumber; i++){
bco_nombreObj[i] = document.getElementsByName("pagobco_nombre[]").item(i).value; //pagobco_nombre[i].value;
bco_nrochequeObj[i] = document.getElementsByName("pagobco_nrocheque[]").item(i).value; //pagobco_nrocheque[i].value;
bco_fechaObj[i] = document.getElementsByName("bco_fecha[]").item(i).value; //bco_fecha[i].value;
bco_importeObj[i] = document.getElementsByName("pagobco_importe[]").item(i).value; //pagobco_importe[i].value;
}
nrofactObject = JSON.stringify(nrofactObject);
fechaObj = JSON.stringify(fechaObj);
nombrecliObj = JSON.stringify(nombrecliObj);
importe_dtoObj = JSON.stringify(importe_dtoObj);
importe_netoObj = JSON.stringify(importe_netoObj);
importe_brutoObj = JSON.stringify(importe_brutoObj);
pago_efectObj = JSON.stringify(pago_efectObj);
pago_transfObj = JSON.stringify(pago_transfObj);
pago_retenObj = JSON.stringify(pago_retenObj);
bco_nombreObj = JSON.stringify(bco_nombreObj);
bco_nrochequeObj = JSON.stringify(bco_nrochequeObj);
bco_fechaObj = JSON.stringify(bco_fechaObj);
bco_importeObj = JSON.stringify(bco_importeObj);
$.ajax({
type : 'GET',
cache: false,
url : 'logica/ajax/update.recibo.php',
data:{
rendid : rendid,
factNumber : factNumber,
rowNumber : rowNumber,
observacion : observacion,
diferencia : diferencia,
nro_rendicion : nro_rendicion,
nro_tal : nro_tal,
nro_rec : nro_rec,
nrofactObject : nrofactObject,
fechaObj : fechaObj,
nombrecliObj : nombrecliObj,
importe_dtoObj : importe_dtoObj,
importe_netoObj : importe_netoObj,
importe_brutoObj: importe_brutoObj,
pago_efectObj : pago_efectObj,
pago_transfObj : pago_transfObj,
pago_retenObj : pago_retenObj,
bco_nombreObj : bco_nombreObj,
bco_nrochequeObj: bco_nrochequeObj,
bco_fechaObj : bco_fechaObj,
bco_importeObj : bco_importeObj
},
beforeSend: function () {
$('#box_confirmacion2').css({'display':'none'});
$('#box_error2').css({'display':'none'});
$('#box_cargando2').css({'display':'block'});
$("#msg_cargando2").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
if (result){
$('#box_cargando2').css({'display':'none'});
if (result.replace("\n","") === '1'){
$('#box_confirmacion2').css({'display':'block'});
$("#msg_confirmacion2").html("El Nuevo recibo fue creado.");
document.getElementById("close-recibo").click();
document.getElementById("close-talonario").click();
location.reload();
} else {
$('#box_error2').css({'display':'block'});
$("#msg_error2").html(result);
}
}
},
error: function () {
$('#box_cargando2').css({'display':'none'});
$('#box_error2').css({'display':'block'});
$("#msg_error2").html("Error en el proceso de Envío de Formulario.");
}
});
}
function dac_SelectFilaToDelete(recid, recnro){
"use strict";
//al seleccionar una fila cambia de color y la ultima anterior seleccionada vuelve a su color original segun sea par o impar
// ultimo id y nrorecibo de fila seleccionado
var ultimoid = document.getElementById("ultimocssth").value;
var ultimorecibo = document.getElementById("ultimorecibo").value;
// grabo el id de fila y nro recibo seleecionado para registrar el próximo ultimocss seleccionado
document.getElementById("ultimocssth").value = recid;
document.getElementById("ultimorecibo").value = recnro;
// en caso de que se haga clic en delete se borrará el recibo de la fila seleccionada
document.getElementById("deleterendicion").value = recid;
if(recid !== ultimoid){
if((ultimorecibo % 2) === 0){
document.getElementById(ultimoid).style.background = "#fff";
} else {
document.getElementById(ultimoid).style.background = "#f6f6f6";
}
document.getElementById(recid).style.background = "#5697C7";
}
}
function dac_deleteRecibo(){
"use strict";
var recid = document.getElementById("deleterendicion").value;
var rendid = document.getElementById("rendicionid").value;
$.ajax({
url : 'logica/ajax/delete.recibo.php',
data : {recid : recid,
rendid : rendid},
type : 'GET',
beforeSend: function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
if (result){
$('#box_cargando').css({'display':'none'});
if (result.replace("\n","") === '1'){
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html("El recibo fue ELIMINADO.");
location.reload();
} else {
alert(result);
}
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("ERROR!");
}
});
}
function dac_NuevaRendicion(nro){
"use strict";
if (isNaN(nro) || nro===0){alert("Debe utilizar la cobranza Nro. 1");
} else {
//document.getElementById("nro_rend_actual").value = nro;
document.getElementById("nro_rend").value = parseInt(nro) + 1;
}
}
function dac_Anular_Rendicion(){
"use strict";
var nro_anular = document.getElementById("nrorendi_anular").value;
var idusr = document.getElementById("vendedor").value;
if(confirm("Desea anular el env\u00edo de la rendici\u00f3n?")){
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/rendicion/logica/ajax/anular.rendicion.php',
data:{ idusr : idusr,
nro_anular : nro_anular
},
beforeSend: function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
if (result){
$('#box_cargando').css({'display':'none'});
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html(result);
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al intentar anular la Rendici\u00f3n.");
}
});
}
}<file_sep>/includes/class/class.condicioncomercial.bonif.php
<?php
require_once('class.PropertyObject.php');
class TCondicionComercialBonif extends PropertyObject {
protected $_tablename = 'condicion_bonif';
protected $_fieldid = 'cbid';
protected $_fieldactivo = 'cbactivo';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'cbid';
$this->propertyTable['Condicion'] = 'cbidcond';
$this->propertyTable['Articulo'] = 'cbidart';
$this->propertyTable['Cantidad'] = 'cbcant';
$this->propertyTable['Bonif1'] = 'cbbonif1';
$this->propertyTable['Bonif2'] = 'cbbonif2';
$this->propertyTable['Desc1'] = 'cbdesc1';
$this->propertyTable['Desc2'] = 'cbdesc2';
$this->propertyTable['Activo'] = 'cbactivo';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/zonas/logica/ajax/getCuentaZonas.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//*************************************************
$empresa= (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
$activas= (isset($_POST['activas'])) ? $_POST['activas'] : NULL;
$tipos = (isset($_POST['tipo'])) ? $_POST['tipo'] : NULL; //"'C', 'T'";
$zonas = (isset($_POST['zonas'])) ? $_POST['zonas'] : NULL;
$geoloc = (isset($_POST['geoloc'])) ? $_POST['geoloc'] : NULL;
//$_SESSION["_usrzonas"]
//*************************************************
$zona = (count($zonas)>0) ? implode(',', $zonas) : NULL;
$tipo = (count($tipos)>0) ? implode(', ', $tipos) : NULL;
$activas= ($activas!= 2) ? $activas : NULL;
$cuentas= DataManager::getCuentas(0, 0, $empresa, $activas, $tipo, $zona);
if (count($cuentas)) {
//registro de transfers de ultimo año
$dateFrom = new DateTime('now');
$dateFrom->modify("-1 year");
$dateTo = new DateTime('now');
$transfers = DataManager::getTransfersPedido(0, $dateFrom->format("Y-m-d"), $dateTo->format("Y-m-d"), NULL, NULL, NULL, NULL, NULL);
foreach ($cuentas as $k => $cuenta) {
$tipo = $cuenta['ctatipo'];
$zona = $cuenta['ctazona'];
if($tipo <> 'O') {
$latitud = $cuenta['ctalatitud'];
$longitud = $cuenta['ctalongitud'];
$id = $cuenta['ctaid'];
$nombre = $cuenta['ctanombre'];
$cuentaId = $cuenta['ctaidcuenta'];
$activa = $cuenta['ctaactiva'];
$estado = ($activa) ? 'Activa' : 'Inactiva' ;
$provincia = DataManager::getProvincia('provnombre', $cuenta['ctaidprov']);
$localidad = DataManager::getLocalidad('locnombre', $cuenta['ctaidloc']);
$direccion = $cuenta['ctadireccion'];
$direccion = ($cuenta['ctadirnro']) ? $direccion.' '.$cuenta['ctadirnro'] : $direccion;
$direccion = str_replace(' ', ' ', $direccion);
$direccion2 = ($provincia) ? $direccion.", ".$provincia : $direccion;
$direccion2 = ($localidad) ? $direccion2.", ".$localidad : $direccion2;
switch($tipo){
case 'C':
case 'CT':
if($activa){
$image = 'marcadorGreen.png';
$color = "#3dc349"; //verde
} else {
//Si cuenta es inactiva, verificar pedidos transfers del último año.
$indice = '';
$indice = array_search($id, array_column($transfers, 'ptidclineo'));
if($indice){
//inactiva Con pedido transfer
$image = 'marcadorGY.png';
$color = "#fcfcfc"; //oscuro
} else {
//inactiva
$image = 'marcadorGreenHover.png';
$color = "#328336"; //oscuro
}
}
break;
case 'T':
if($activa){
$image = 'marcadorYellow.png';
$color = "#d69a2c"; //amarillo
} else {
$image = 'marcadorYellowHover.png';
$color = "#855f1b"; //oscuro
}
break;
case 'TT':
if($activa){
$image = 'marcadorOrange.png';
$color = "#efbe9a"; //orange
} else {
$image = 'marcadorOrangeHover.png';
$color = "#E49044"; //dark orange
}
break;
case 'PS':
$image = 'marcadorRed.png';
$color = "#ba140c"; //rojo
break;
default:
$image = 'marcador.png';
$color = '#fcfcfc';
break;
}
if($geoloc == 1 && (empty($longitud) || empty($latitud))){ //&& $tipo == 'PS'
//calcula lat y long en caso de tener dirección mal cargada
if(!empty($direccion)){
$latLog = dac_getCoordinates($direccion2);
$latitud = $latLog[0];
$longitud = $latLog[1];
$datos[] = array(
"datos" => "<strong>Cuenta: </strong>".$cuentaId."<strong> Tipo: ".$tipo."</strong></br><strong> Estado: </strong>".$estado."</br><strong>Nombre: </strong>".$nombre."</br><strong>Provincia: </strong>".$provincia."</br><strong>Localidad: </strong>".$localidad."</br><strong>Direccion: </strong>".$direccion,
"latitud" => $latitud,
"longitud" => $longitud,
"cuenta" => $nombre,
"color" => $color,
"imagen" => $image,
"id" => $id,
"direccion" => $direccion2,
"idcuenta" => $cuentaId,
);
}
} else {
$datos[] = array(
"datos" => "<strong>Cuenta: </strong>".$cuentaId."<strong> Tipo: ".$tipo."</strong></br><strong> Estado: </strong>".$estado."</br><strong>Nombre: </strong>".$nombre."</br><strong>Provincia: </strong>".$provincia."</br><strong>Localidad: </strong>".$localidad."</br><strong>Direccion: </strong>".$direccion,
"latitud" => $latitud,
"longitud" => $longitud,
"cuenta" => $nombre,
"color" => $color,
"imagen" => $image,
"id" => $id,
"direccion" => $direccion2,
"idcuenta" => $cuentaId,
);
}
}
}
echo json_encode($datos); exit;
}
?><file_sep>/includes/headersAndFooters.php
<?php
$cabecera = '';
$pie = '';
$empresa = (!isset($empresa)) ? '' : $empresa;
switch($empresa){
case '1':
//NEO-FARMA
$cabecera = '<img src="https://www.neo-farma.com.ar/pedidos/images/mail/CabezalNeo.png" width="600" height="97"/>';
$pie = '<img src="https://www.neo-farma.com.ar/pedidos/images/mail/PieNeo.png" width="600" height="97"/>';
$cabeceraPropuesta = '<img src="https://www.neo-farma.com.ar/pedidos/images/logo/CabeceraNeoPropuesta.png"/>';
$piePropuesta = '<img src="https://www.neo-farma.com.ar/pedidos/images/logo/PiePedidoNeo.png"/>';
$cabeceraPedido = '<img src="https://www.neo-farma.com.ar/pedidos/images/logo/LogoNeoPedido.png" alt="Neo-farma"/>';
$piePedido = '<img src="https://www.neo-farma.com.ar/pedidos/images/pie/PieNeoPedidoConContacto.png" alt="Neo-farma"/>';
break;
case '3':
//GEZZI
$cabecera = '<img src="https://www.neo-farma.com.ar/pedidos/images/mail/CabezalGezzi.png" width="600" height="97"/>';
$pie = '<img src="https://www.neo-farma.com.ar/pedidos/images/mail/PieGezzi.png" width="600" height="97"/>';
$cabeceraPropuesta = '<img src="https://www.neo-farma.com.ar/pedidos/images/logo/CabeceraGezziPropuesta.png"/>';
$piePropuesta = '<img src="https://www.neo-farma.com.ar/pedidos/images/logo/PiePedidoGezzi.png"/>';
$cabeceraPedido = '<img src="https://www.neo-farma.com.ar/pedidos/images/logo/LogoGezziPedido.png"/>';
$piePedido = '<img src="https://www.neo-farma.com.ar/pedidos/images/pie/PieGezziPedidoConContacto.png"/>';
break;
default:
$cabecera = '<img src="https://www.neo-farma.com.ar/pedidos/images/mail/CabezalNeo.png" width="600" height="97"/>';
$pie = '<img src="https://www.neo-farma.com.ar/pedidos/images/mail/PieNeo.png" width="600" height="97"/>';
$cabeceraPedido = '<img src="https://www.neo-farma.com.ar/pedidos/images/logo/LogoNeoPedido.png" alt="Neo-farma"/>';
$piePedido = '<img src="https://www.neo-farma.com.ar/pedidos/images/pie/PieNeoPedidoConContacto.png" alt="Neo-farma"/>';
break;
}
?><file_sep>/cadenas/logica/ajax/getCadenas.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
exit;
}
$empresa = (isset($_POST['idEmpresa'])) ? $_POST['idEmpresa'] : NULL;
$cadenas = DataManager::getCadenas($empresa);
if (count($cadenas)) {
echo '<table id="tblCadenas">';
echo '<thead><tr><th>Cadena</th><th>Nombre</th></tr></thead>';
echo '<tbody>';
foreach ($cadenas as $k => $cadena) {
$id = $cadena['cadid'];
$idCadena = $cadena['IdCadena'];
$nombre = $cadena['NombreCadena'];
((($k % 2) == 0)? $clase="par" : $clase="impar");
if($idCadena != 0){
echo "<tr id=cadena".$id." class=".$clase." style=\"cursor:pointer;\" onclick=\"javascript:dac_changeCadena('$id', '$idCadena', '$nombre')\">";
echo "<td>".$idCadena."</td><td>".$nombre."</td>";
echo "</tr>";
}
}
echo "</tbody></table>";
} else {
echo '<table><thead><tr><th align="center">No hay registros activos.</th></tr></thead></table>'; exit;
}
?><file_sep>/localidades/logica/ajax/getCuentas.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
$idLoc = (isset($_POST['idLoc'])) ? $_POST['idLoc'] : NULL;
$idProv = (isset($_POST['idProv'])) ? $_POST['idProv'] : NULL;
$cuentas = DataManager::getCuentas(0, 0, NULL, NULL, '"C","CT","T","TT"', $_SESSION["_usrzonas"]);
if (count($cuentas)) {
$zonas = DataManager::getZonas(0, 0, 1);
foreach($zonas as $k => $zona){
$arrayZonas[] = $zona['zzona'];
}
$stringZonas = implode(",", $arrayZonas);
echo '<table id="tblTablaCta" style="table-layout:fixed;">';
echo '<thead><tr align="left"><th>Emp</th><th>Id</th><th>Nombre</th><th>Localidad</th></tr></thead>';
echo '<tbody>';
foreach ($cuentas as $k => $cta) {
$ctaID = $cta["ctaid"];
$empresa = $cta["ctaidempresa"];
$idCuenta = $cta["ctaidcuenta"];
$nombre = $cta["ctanombre"];
$zonaV = $cta["ctazona"];
$idLoc = $cta["ctaidloc"];
$localidad = '';
$localidad = (empty($idLoc)) ? DataManager::getCuenta('ctalocalidad', 'ctaid', $ctaID, $empresa) : DataManager::getLocalidad('locnombre', $idLoc);
((($k % 2) == 0)? $clase="par" : $clase="impar");
if($idCuenta != 0){
echo "<tr id=cuenta".$ctaID." class=".$clase." onclick=\"javascript:dac_cargarDatosCuenta('$ctaID', '$empresa', '$idCuenta', '$zonaV', '$stringZonas' )\" style=\"cursor:pointer\"><td>".$empresa."</td><td>".$idCuenta."</td><td>".$nombre."</td><td>".$localidad."</td></tr>";
}
}
echo '</tbody></table>';
} else {
echo '<table><tr><td align="center">No hay registros activos.</td></tr></table>';
}
?><file_sep>/includes/class/class.condicionesdepago.php
<?php
require_once('class.PropertyObject.php');
class TCondicionPago extends PropertyObject {
protected $_tablename = 'condiciones_de_pago';
protected $_fieldid = 'condid';
protected $_fieldactivo = 'condactiva';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'condid';
$this->propertyTable['Codigo'] = 'IdCondPago';
$this->propertyTable['Tipo'] = 'condtipo';
$this->propertyTable['Tipo1'] = 'condtipo1';
$this->propertyTable['Tipo2'] = 'condtipo2';
$this->propertyTable['Tipo3'] = 'condtipo3';
$this->propertyTable['Tipo4'] = 'condtipo4';
$this->propertyTable['Tipo5'] = 'condtipo5';
$this->propertyTable['Nombre'] = 'Nombre1CP';
$this->propertyTable['Nombre2'] = 'Nombre2CP';
$this->propertyTable['Nombre3'] = 'Nombre3CP';
$this->propertyTable['Nombre4'] = 'Nombre4CP';
$this->propertyTable['Nombre5'] = 'Nombre5CP';
$this->propertyTable['Dias'] = 'Dias1CP';
$this->propertyTable['Dias2'] = 'Dias2CP';
$this->propertyTable['Dias3'] = 'Dias3CP';
$this->propertyTable['Dias4'] = 'Dias4CP';
$this->propertyTable['Dias5'] = 'Dias5CP';
$this->propertyTable['Porcentaje'] = 'Porcentaje1CP';
$this->propertyTable['Porcentaje2'] = 'Porcentaje2CP';
$this->propertyTable['Porcentaje3'] = 'Porcentaje3CP';
$this->propertyTable['Porcentaje4'] = 'Porcentaje4CP';
$this->propertyTable['Porcentaje5'] = 'Porcentaje5CP';
$this->propertyTable['Signo'] = 'Signo1CP';
$this->propertyTable['Signo2'] = 'Signo2CP';
$this->propertyTable['Signo3'] = 'Signo3CP';
$this->propertyTable['Signo4'] = 'Signo4CP';
$this->propertyTable['Signo5'] = 'Signo5CP';
$this->propertyTable['Cuotas'] = 'Cuotas';
$this->propertyTable['Cantidad'] = 'Cantidad';
//Se define en caso de que deba descontar los días.
$this->propertyTable['Decrece'] = 'conddecrece';
$this->propertyTable['FechaFinDec'] = 'condfechadec1';
$this->propertyTable['FechaFinDec2']= 'condfechadec2';
$this->propertyTable['FechaFinDec3']= 'condfechadec3';
$this->propertyTable['FechaFinDec4']= 'condfechadec4';
$this->propertyTable['FechaFinDec5']= 'condfechadec5';
$this->propertyTable['UsrCreated'] = 'condusrcreated';
$this->propertyTable['Created'] = 'condcreated';
$this->propertyTable['UsrUpdate'] = 'condusrupdate';
$this->propertyTable['Update'] = 'condupdate';
$this->propertyTable['Activa'] = 'condactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
// Devuelve '#petid' para el alta de un nuevo registro
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/pedidos/logica/ajax/aprobar.pedido.php
e<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$_nropedido = (isset($_POST['nropedido'])) ? $_POST['nropedido'] : NULL;
$_estado = (isset($_POST['estado'])) ? $_POST['estado'] : NULL;
$_detalles = DataManager::getPedidos($_usr, NULL, $_nropedido);
if ($_detalles) {
foreach ($_detalles as $k => $_detalle) {
$_pid = $_detalle["pid"];
$_pidusr = $_detalle["pidusr"];
$_negociacion = $_detalle["pnegociacion"];
//$_aprobado = $_detalle["paprobado"];
if($_pid){
$_pedidoobject = DataManager::newObjectOfClass('TPedido', $_pid);
$_pedidoobject->__set('IDResp', $_SESSION["_usrid"]);
$_pedidoobject->__set('Responsable', $_SESSION["_usrname"]);
$_pedidoobject->__set('FechaAprobado', date("Y-m-d H:i:s"));
$_pedidoobject->__set('Aprobado', $_estado);
if ($_pid) {
$ID = DataManager::updateSimpleObject($_pedidoobject);
if(empty($ID)){
echo "Ocurrió un error y no se grabó el pedido $_nropedido. Pongase en contacto con el administrador de la web"; exit;
}
}
} else {
echo "X Error al intentar aprobar el pedido."; exit;
}
}
}
//******************************//
// NOTIFICO RECHAZO DE PEDIDO //
//******************************//
if($_estado == 2){
//*******************//
// Armado del CORREO //
//*******************//
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$_emailVen = DataManager::getUsuario('uemail', $_pidusr);
/*********************/
$mail->From = "<EMAIL>"; //mail del emisor
$mail->FromName = "InfoWeb GEZZI"; //"Vendedor: ".$_SESSION["_usrname"];
$mail->Subject = "Datos de negociacion del pedido web ".$_nropedido.", guarde este email.";
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
$_total = '
<html>
<head>
<title>Notificación de Negociación</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 90%;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 0px;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>
<body>
<div align="center">
<table width="600" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Su <strong>SOLICITUD DE APROBACIÓN DE NEGOCIACIÓN</strong> fue rechazada.<br />
<div />
</td >
</tr>
<tr bgcolor="#597D92">
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight: bold;">
<strong>Estos son los datos de negociación</strong>
</div>
</td>
</tr>
<tr>
<td height="95" valign="top">
<div class="texto">
<table width="600px" style="border:1px solid #597D92">
<tr>
<th rowspan="2" align="left" width="100">
<NAME>:<br />
Estado:
</th>
<th rowspan="2" align="left" width="250">
'.$_nropedido.'<br />
RECHAZADO
</th>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta del estado de su pedido, póngase en contacto con el encargado de aprobaciones.<br />
</font>
<div style="color:#000000; font-size:12px;">
<strong>El pedido quedará en su listado de pedidos pendientes hasta que ser eliminado por el solicitante.</strong></a></br></br>
</div>
</div>
</td>
</tr>
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Le Saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
';
$mail->msgHTML($_total);
$mail->AddAddress($_emailVen, "$_emailVen");
$mail->AddAddress($_email, "$_email"); //'Estado de Negociación del pedido '.$_nropedido
$mail->AddBCC("<EMAIL>", "Infoweb");
$mail->AddBCC("<EMAIL>", "Control de Gestion");
if(!$mail->Send()) {
//Si el envío falla, que mande otro mail indicando que la solicittud no fue correctamente enviada?=?
echo 'Fallo en el envío de la notificación de rechazo de negociación';
exit;
}
echo "2"; exit;
}
echo "1"; exit;
?><file_sep>/informes/logica/js/jquery.script.multifile.js
$(function(){"use strict"; $('#enviar_informes').click(subirInformes); });
$(function(){"use strict"; $('#enviar_informesUnicos').click(subirInformesUnicos); });
$(function(){"use strict"; $('#sendImportFile').click(importTableFile); });
/********************/
// SUBIR INFORMES //
/********************/
function subirInformes(){
"use strict";
var archivos = document.getElementById("informes");
var archivo = archivos.files;
archivos = new FormData();
for(var i=0; i<archivo.length; i++){
archivos.append('archivo'+i,archivo[i]);
}
var tipo = document.getElementById("tipo_informe").value;
archivos.append('tipo', tipo);
$.ajax({
url:'/pedidos/informes/logica/subir.informes.php',
type:'POST',
contentType:false,
data:archivos,
processData:false,
cache:false,
beforeSend : function () {
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
afterSend : function() {
$('#box_cargando').css({'display':'none'});
},
success : function(result) {
if(result){
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
},
}).done(function(){
if(tipo === "archivos/facturas/contrareembolso"){
vaciarFactuasContra();
}
});
}
//Vaciar las facturas contrareeembolso
function vaciarFactuasContra(){
"use strict";
$.ajax({
url:'/pedidos/informes/logica/vaciar_factcontra.php',
type:'POST',
contentType:false,
//data:archivos,
processData:false,
cache:false
});
}
/********************/
// SUBIR INFORMES UNICOS //
/********************/
function subirInformesUnicos(){
"use strict";
var archivos = document.getElementById("informesUnicos");
var archivo = archivos.files;
archivos = new FormData();
for(var i=0; i<archivo.length; i++){
archivos.append('archivo'+i,archivo[i]);
}
var tipo = document.getElementById("tipo_informeUnico").value;
archivos.append('tipo', tipo);
$.ajax({
url:'/pedidos/informes/logica/subir.informesUnicos.php',
type:'POST',
contentType:false,
data:archivos,
processData:false,
cache:false,
beforeSend : function () {
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
afterSend : function() {
$('#box_cargando').css({'display':'none'});
},
success : function(result) {
if(result){
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
},
});
}
/********************/
function importTableFile(){
"use strict";
var archivos = document.getElementById("importTableFile");
var archivo = archivos.files;
archivos = new FormData();
for(var i=0; i<archivo.length; i++){
archivos.append('archivo'+i,archivo[i]);
}
var tipo = document.getElementById("importTable").value;
archivos.append('tipo', tipo);
$.ajax({
url:'/pedidos/informes/logica/import.tableFile.php',
type:'POST',
contentType:false,
data:archivos,
processData:false,
cache:false,
beforeSend : function () {
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
afterSend : function() {
$('#box_cargando').css({'display':'none'});
},
success : function(result) {
if(result){
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
},
});
}<file_sep>/includes/class/class.respuesta.php
<?php
require_once('class.PropertyObject.php');
class TRespuesta extends PropertyObject {
protected $_tablename = 'respuesta';
protected $_fieldid = 'resid';
protected $_fieldactivo = 'resactiva';
protected $_timestamp = 0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'resid';
$this->propertyTable['IDRelevamiento'] = 'resrelid';
$this->propertyTable['Respuesta'] = 'respuesta1';
$this->propertyTable['Origen'] = 'resorigen'; // Tabla donde sale quién respondió el relevamiento (nombre Tabla) ejemplo, de un prospecto (tabla TProspecto)
$this->propertyTable['IDOrigen'] = 'resorigenid';// id de la tabla Origen. Id del prospecto que respondió.
$this->propertyTable['UsrUpdate'] = 'resuid'; // Usuario que hace el relevo, podría ser también el mismo del origen (si fuera una autoencuesta)
$this->propertyTable['LastUpdate'] = 'resfecha';
$this->propertyTable['Activa'] = 'resactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->propertyTable['ID']);
//return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/js/funciones_comunes.js
/** jQuery JavaScript Library ;
* Date: 01-11-2014
* Funciones Comunes para Extranet
*/
/****************************************
//FUNCIONES QUE CONTROLA QUE LOS PRECIOS SE CARGUEN CON PUNTO Y NO CON COMA
/*****************************************/
function ControlComa(id, precio) {
"use strict";
if(precio.indexOf(',') !== -1){
document.getElementById(id).value = "";
alert("El valor debe llevar punto en vez de coma");
}
}
// Redondear Números en JAvascript
function dac_Redondeo(nro, decimales){
"use strict";
var flotante = parseFloat(nro);
var resultado = Math.round(flotante * Math.pow(10,decimales)) / Math.pow(10,decimales);
return resultado;
}
/****************************************
//FUNCIONES QUE CONTROLA QUE LOS PRECIOS SE CARGUEN CON PUNTO Y NO CON COMA
/*****************************************/
function dac_ControlNegativo(id, precio) {
"use strict";
if(precio < 0){
document.getElementById(id).value = "";
alert("El valor debe ser mayor a cero");
}
}
//----------------------//
/* VALIDAR CAMPO FECHA */
//Ver de usar en los textos de observación de cuentas etc
function dac_ValidarCaracteres(e){
"use strict";
var tecla = (document.all) ? e.keyCode : e.which;
if (tecla===13){ return false; } //Enter
if (tecla===8){ return true; }
var patron =/[\^$*+?=!:|\\/()\[\]{}¨º~#·&'¡¿`´><ª¬]/; //var patron =/[A-Za-z0-9]/;
var te = String.fromCharCode(tecla);
if (patron.test(te)) {
//alert('No puedes usar ese caracter');
return false;
}
}
/************************/
/* VALIDAR CAMPO FECHA */
/************************/
//Usado para Recibos en Rendiciones
function dac_ValidarCampoFecha(id, valor, estado){
"use strict";
var fecha = valor.replace(/^\s+/,'').replace(/\s+$/,'');
var long = fecha.length;
switch(estado){
case "KeyUp":
var caracter = valor.charAt(long-1);
if (long === 3 || long === 6){
if (caracter !== "-"){
alert ("El valor de fecha debe tener el formato dd-mm-aaaa");
document.getElementById(id).value = valor.substring(0, valor.length-1);
}
} else {
if (isNaN(caracter)){
alert ("El valor ingresado debe ser un n\u00famero");
document.getElementById(id).value = valor.substring(0, valor.length-1);
} else {
if (long === 1 && caracter > '3'){
alert ("Error en el ingreso del d\u00eda.");
document.getElementById(id).value = valor.substring(0, valor.length-1);}
if (long === 4 && caracter > '1'){
alert ("Error en el ingreso del mes.");
document.getElementById(id).value = valor.substring(0, valor.length-1);}
if (long === 5 && caracter > '2' && (valor.charAt(long-2)) === 1){
alert ("Error en el ingreso del mes.");
document.getElementById(id).value = valor.substring(0, valor.length-1);}
if (long === 7 && caracter !== '2'){ //obliga que sea año 2000
alert ("Error en el ingreso del a\u00f1o."+long);
document.getElementById(id).value = valor.substring(0, valor.length-1);}
if (long === 8 && caracter !== '0'){ //obliga que sea siglo 1
alert ("Error en el ingreso del a\u00f1o."+long);
document.getElementById(id).value = valor.substring(0, valor.length-1);}
}
}
break;
case "Blur":
if(long !== 10 && long !== 0){
alert('La fecha est\u00e1 incompleta. Vuelva a ingresarla');
document.getElementById(id).value = '';
}
break;
}
}
/************************************/
/* IMPRIMIR MUESTRA */
/************************************/
function dac_imprimirMuestra(muestra){
"use strict";
var ficha = document.getElementById(muestra);
var ventimp=window.open(' ','popimpr');
ventimp.document.write(ficha.innerHTML);
ventimp.document.close();
ventimp.print();
ventimp.close();
}
/************************************/
/* LIMITA CANTIDAD DE CARACTERES */
/************************************/
function dac_LimitaCaracteres(elEvento, ID, maximoCaracteres) {
"use strict";
//limita la cantidad de caracteres en cada onkeypress
var elemento = document.getElementById(ID);
// Obtener la tecla pulsada
var evento = elEvento || window.event;
var codigoCaracter = evento.charCode || evento.keyCode;
// Permitir utilizar las teclas con flecha horizontal
if(codigoCaracter === 37 || codigoCaracter === 39) { return true; }
// Permitir borrar con la tecla Backspace y con la tecla Supr.
if(codigoCaracter === 8 || codigoCaracter === 46) { dac_ActualizaCaracteres(elemento, maximoCaracteres); /*return true;*/ }
else /*if(elemento.value.length >= maximoCaracteres ) { return false;
} else { return true; }*/
{dac_ActualizaCaracteres(elemento, maximoCaracteres);}
}
/*************************************/
/* ACTUALIZA CANTIDAD DE CARACTERES */
/*************************************/
function dac_ActualizaCaracteres(elemento, maximoCaracteres) {
"use strict";
//actualiza cantidad de caracteres por cada onkeyup
//var elemento = document.getElementById(ID);
//lo siguiente es donde se notificará la cantidad de caracteres
var info = document.getElementById("msg_informacion");
info.style.display = "inline";
document.getElementById('box_informacion').style.display = "inline";
if(elemento.value.length >= maximoCaracteres ) {
info.innerHTML = "Sobran "+(elemento.value.length-maximoCaracteres)+" caracteres de "+maximoCaracteres+" permitidos";
} else {
info.innerHTML = "Quedan "+(maximoCaracteres-elemento.value.length)+" caracteres";
}
}
/******************/
/* CONTROL CUIT */
/******************/
function dac_validarCuit(cuit) {
"use strict";
cuit = cuit.replace(/-/g, "");
if(cuit.length !== 11) {return false;} //alert("El CUIT es incorrecto.");
var acumulado = 0;
var digitos = cuit.split("");
var digito = digitos.pop();
for(var i = 0; i < digitos.length; i++) {
acumulado += digitos[9 - i] * (2 + (i % 6));
}
var verif = 11 - (acumulado % 11);
if(verif === 11) { verif = 0; //alert("El CUIT es incorrecto.");
} else if(verif === 10) {verif = 9;} //alert("El CUIT es incorrecto.");
return digito === verif; //{alert("CUIT correcto");}
}
/**********************/
/* SCROLL SUBIR WEB */
/**********************/
var arriba;
function subir() {
"use strict";
if (document.body.scrollTop !== 0 || document.documentElement.scrollTop !== 0) {
window.scrollBy(0, -15);
arriba = setTimeout('subir()', 10);
} else {
clearTimeout(arriba);
}
}
/**********************/
/* ELIMINAR ARCHIVO */
/**********************/
function dac_fileDelete(id, url, direccion) {
"use strict";
if(confirm('\u00BFEst\u00e1 seguro que desea ELIMINAR EL ARCHIVO?')){
$.ajax({
url: url,
type:'POST',
data:{direccion : direccion,},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success: function(result){
$('#box_cargando').css({'display':'none'});
if(result) {
/* oculto el registro del id donde se ve el archivos */
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('Los datos fueron eliminados');
document.getElementById(id).style.display = "none";
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error en el proceso");
},
});
}
}
// Botón eliminar para quitar un div de artículos
function dac_deleteCuentaTransferRelacionada(id, nextCuentaTransfer){
"use strict";
var elemento = document.getElementById('rutcuenta'+nextCuentaTransfer);
elemento.parentNode.removeChild(elemento);
}
/*******************/
/* Select Cuentas */
/*******************/
function dac_changeStatus(url, id, pag) {
"use strict";
$.ajax({
type : 'POST',
cache: false,
url : url,
data: { id : id,
pag : pag
},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
if (result){
$('#box_cargando').css({'display':'none'});
if (result.replace("\n","") === '1'){
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('Cambio de estado realizado.');
window.location.reload(true);
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al intentar consultar el estado.");
},
});
}
//**************//
// Llamadas //
//**************//
function dac_registrarLlamada(origen, idorigen, nroRel, telefono, contesta, resultado, observacion){
"use strict";
$.ajax({
type: "POST",
url: "/pedidos/llamada/logica/update.llamada.php",
data: { origen : origen,
idorigen : idorigen,
nroRel : nroRel,
telefono : telefono,
tiporesultado: contesta,
resultado : resultado,
observacion : observacion
},
success: function(result){
if(result){
if(result.replace("\n","") !== '1'){
alert(result); //
} else {
//Cierra el formulario y registra la llamada como No contesta
$("#dialogo").dialog("close");
}
}
}
});
}
function dac_incidencia(onoff) {
"use strict";
if(onoff === 1){
$('#incidencia').css("display", "inline");
$( "#dialogo" ).css("height", 320);
} else {
$('#incidencia').css("display", "none");
$( "#dialogo" ).css("height", 180);
}
}
function dac_reprogramar(origen, idorigen, nroRel, contesta, telefono){
"use strict";
$("#reprogramar").empty();
$("#reprogramar").dialog({
modal: true,
title: 'Reprogramar llamada',
zIndex: 100,
autoOpen: true,
resizable: false,
width: 380,
height: 420,
buttons: {
Aceptar : function () {
var fecha_reprog = $( "#fecha_reprog" ).val();
var hora_reprog = $( "#hora_reprog" ).val();
var motivo = $( "#motivo" ).val();
var telefono2 = $( "#telefono2" ).val();
var descripcion2 = $( "#descripcion2" ).val();
if(fecha_reprog.trim() === "" || fecha_reprog.length < 1){
alert("Indique una fecha para rellamar");
} else if (hora_reprog.trim() === "" || hora_reprog.length < 1) {
alert("Indique un horario");
} else if (motivo.trim() === "" || motivo.length < 1) {
alert("Indique el motivo de rellamada");
} else if(telefono2.trim() === "" || telefono2.length < 1){
alert("Indique el tel\u00e9fono a rellamar");
} else {
dac_registrarLlamada(origen, idorigen, nroRel, telefono2, contesta, 'rellamar', descripcion2);
//CARGA A LA AGENDA COOMO RELLAMAR//
//dac_updateEvent();
var fechaInicio = fecha_reprog.split('/');
var fechaFin = new Date(fechaInicio[2]+"/"+fechaInicio[1]+"/"+fechaInicio[0]+" "+hora_reprog);
//var dias = fechaFin.getDate();
//fechaFin.setDate(dias + 1);
var horas = fechaFin.getHours();
fechaFin.setHours(horas + 1);
var hora = fechaFin.getHours();
var minuto = fechaFin.getMinutes();
var dia = fechaFin.getDate();
var mes = fechaFin.getMonth() + 1;
mes = (mes < 10) ? ("0" + mes) : mes;
dia = (dia < 10) ? ("0" + dia) : dia;
hora = (hora < 10) ? ("0" + hora) : hora;
minuto = (minuto < 10) ? ("0" + minuto) : minuto;
//alert(mes+'/'+dia+'/'+fechaFin.getFullYear()+" "+hora+":"+minuto);
var url = window.location.origin+'/pedidos/cuentas/editar.php?ctaid='+idorigen; var eventData;
eventData = {
id : 0,
color : "ffee00", //Amarillo
title : "Rellamar Prospecto",
url : url,
texto : "Rellamar Prospecto ID "+idorigen+". "+descripcion2,
start : fechaInicio[1]+'/'+fechaInicio[0]+'/'+fechaInicio[2]+' '+hora_reprog,
end : mes+'/'+dia+'/'+fechaFin.getFullYear()+" "+hora+":"+minuto,
constraint : "Rellamar",
};
$.ajax({
type: "POST",
cache: false,
url: "/pedidos/agenda/ajax/setEvents.php",
data: { eventData : eventData,},
success: function(result){
if(result){
if(isNaN(result)){
alert("No se pudo registrar el rellamado en la agenda");
}
}
},
error: function () {
alert("Error. No se pudo registrar el rellamado en la agenda");
},
});
$("#this").dialog("close");
$("#reprogramar").dialog("close");
}
},
Cerrar : function () {
$("#reprogramar").dialog("close");
}
},
});
var fecha = new Date();
var h = dac_addZero(fecha.getHours());
var m = dac_addZero(fecha.getMinutes());
var hm = h+":"+m;
function dac_addZero(i) {
if (i < 10) { i = "0" + i; }
return i;
}
var contenido =
'<form>'+
'<div class="bloque_6"><label>Fecha</label><input id="fecha_reprog" type="text" name="fecha_reprog" readonly></div>'+
'<div class="bloque_7"><label>Hora</label><input id="hora_reprog" type="text" class="time" value="'+hm+'" maxlength="5"/></div>'+
'<div class="bloque_6"><label>Teléfono: </label><input id="telefono2" name="telefono2" type="text" value="'+telefono+'" maxlength="25"></div>'+
'<div class="bloque_1"><label>Motivo:</label><input id="motivo" name="motivo" type="text" value="'+contesta+'"></div>'+
'<div class="bloque_1"><label>Comentario:</label><textarea id="descripcion2" name="descripcion2" type="text" maxlength="200"></textarea></div>'+
'</form>';
$(contenido).appendTo('#reprogramar');
$( "#fecha_reprog" ).datepicker({ inline: true });
$( "#fecha_reprog" ).datepicker( "option", "dateFormat", "dd/mm/yy" );
$('#hora_reprog').timepicker({
'timeFormat' : 'H:i',
'disableTimeRanges' : [
['0', '7:30'],
['18:30', '24:00']
]
});
}
//**********************//
// Envío de Formulario //
//**********************//
function dac_sendForm(form, url){
"use strict";
var scrolltohere = "";
var formData = new FormData($(form)[0]);
$.ajax({
url : url,
type : 'POST',
data : formData,
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
$("#btsend").hide(100);
},
success : function(result) {
if (result){
$('#box_cargando').css({'display':'none'});
if (result.replace("\n","") === '1'){
//Confirmación
scrolltohere = "#box_confirmacion";
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('Los datos fueron registrados');
window.location.reload(true);
} else {
//El pedido No cumple Condiciones
scrolltohere = "#box_error";
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
$('html,body').animate({
scrollTop: $(scrolltohere).offset().top
}, 2000);
$("#btsend").show(100);
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
scrolltohere = "#box_error";
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error en el proceso");
$("#btsend").show(100);
},
cache : false,
contentType : false,
processData : false
});
return false;
}
//******************//
// GEOLOCALIZACIÓN //
/* GOOGLE MAPS */
function dac_showMap(lat, long) {
"use strict";
var myCenter = new google.maps.LatLng(lat, long);
function dac_initiarMap() {
var mapProp = {
center:myCenter,
zoom:15,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', dac_initiarMap);
}
function dac_refreshMap(lat, long) {
"use strict";
var myCenter = new google.maps.LatLng(lat, long);
google.maps.event.addDomListener(window, 'load');
var mapProp = {
center:myCenter,
zoom:15,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
}
function dac_getLatitudLongitud(provincia, localidad, direccion, nro){
"use strict";
//controles de referencias
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
if(provincia === "Provincia..."){
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Debe indicar una provincia");
//alert("Debe indicar una provincia");
return false;
}
if(direccion === ""){
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Debe indicar una dirección");
//alert("Debe indicar una dirección")
return false;
}
if(nro === ""){
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Debe indicar un número de dirección");
//alert("Debe indicar un número de dirección");
return false;
}
// If adress is not supplied, use default value 'Buenos Aires, Argentina'
var address = provincia+", "+localidad+", "+direccion+" "+nro;
// Initialize the Geocoder
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var latitud = results[0].geometry.location.lat();
var longitud = results[0].geometry.location.lng();
//alert('La longitud es: ' + longitud + ', la latitud es: ' + latitud);
document.getElementById("longitud").value = longitud;
document.getElementById("latitud").value = latitud;
dac_refreshMap(latitud, longitud);
$('#box_cargando').css({'display':'none'});
} else {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
switch(status){
case 'ZERO_RESULTS':
$("#msg_error").html("No se encuentra la dirección indicada.");
break;
case 'ERROR':
$("#msg_error").html("Hubo un problema con los servidores de Google.");
break;
case 'INVALID_REQUEST':
$("#msg_error").html("La dirección no es válida.");
break;
case 'OVER_QUERY_LIMIT':
$("#msg_error").html("La página web ha superado el límite de solicitudes en un perííodo muy corto de tiempo.");
break;
case 'REQUEST_DENIED':
$("#msg_error").html("La página web no puede utilizar el geocodificador.");
break;
default:
$("#msg_error").html("Geocoding fallo debido a : " + status);
break;
}
}
});
}
//**********************************//
// Manejo de visión de imágenes //
//**********************************//
function dac_ShowImgZoom(src){
"use strict";
$('#img_ampliada').fadeIn('slow');
$('#img_ampliada').css({
'width': '100%',
'height': '100%',
'left': ($(window).width() / 2 - $(img_ampliada).width() / 2) + 'px',
'top': ($(window).height() / 2 - $(img_ampliada).height() / 2) + 'px'
});
document.getElementById("imagen_ampliada").src = src;
$(window).resize();
return false;
}
//**********************************//
function dac_CloseImgZoom(){
"use strict";
$('#img_ampliada').fadeOut('slow');
return false;
}
//**********************************//
$(window).resize(function(){
if($('#img_ampliada').length){
$('#img_ampliada').css({
'width': '100%',
'height': '100%',
'left': ($(window).width() / 2 - $(img_ampliada).width() / 2) + 'px',
'top': ($(window).height() / 2 - $(img_ampliada).height() / 2) + 'px'
});
$('#pdf_ampliado').css({
'width': '100%',
'height': '100%',
'left': ($(window).width() / 2 - $(img_ampliada).width() / 2) + 'px',
'top': ($(window).height() / 2 - $(img_ampliada).height() / 2) + 'px'
});
}
});
//-------------------------------
// Exportar archivo Excel
function exportTableToExcel(table, filename){
var downloadLink;
// Specify file name
filename = filename ? filename+'.xls' : 'excel_data.xls';
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
if (!table.nodeType) { table = document.getElementById(table); }
var ctx = { worksheet: filename || 'Worksheet', table: table.innerHTML }
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
// Create a link to the file
downloadLink.href = uri + base64(format(template, ctx));
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
//window.location.href = uri + base64(format(template, ctx))
}<file_sep>/zonas/lista.php
<div class="box_body">
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
<div id="mapa" style="height: 600px;"></div>
</div>
<fieldset>
<legend>Ruta</legend>
<div class="bloque_1">
<select multiple id="waypoints2" style="height: 80px;"></select>
</div>
<div id="waypoints"></div>
</fieldset>
</div> <!-- FIN box_body-->
<div class="box_seccion">
<fieldset>
<legend>Filtros</legend>
<div class="bloque_5">
<label>Empresa</label>
<select id="empselect" name="empselect"><?php
$empresas = DataManager::getEmpresas(1);
if (count($empresas)) {
foreach ($empresas as $k => $emp) {
$idEmp = $emp["empid"];
$nombreEmp = $emp["empnombre"];
if ($idEmp == $empresa){
$selected="selected";
} else { $selected=""; } ?>
<option id="<?php echo $idEmp; ?>" value="<?php echo $idEmp; ?>" <?php echo $selected; ?>><?php echo $nombreEmp; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_5">
<br>
<input id="filterMap" type="button" value="Filtrar">
</div>
<div class="bloque_1"></div>
<div class="bloque_1">
<input type="checkbox" name="geoloc" title="Esta opcion puede tener una alta demora de carga" >
<label title="Esta opcion puede tener una alta demora de carga">Incluir Cuentas Sin Geolocalizar</label>
</div>
<div class="bloque_1"></div>
<div class="bloque_1">
<label><strong>Zonas</strong></label>
<div class="desplegable"> <?php
$zonas = DataManager::getZonas( 0, 0, 1);
for( $k = 0; $k < count($zonas); $k++ ) {
$zona = $zonas[$k];
$numero = $zona['zzona'];
$nombre = $zona['znombre']; ?>
<input name="zonas" type="checkbox" value="<?php echo $numero ?>">
<?php echo $numero." - ".$nombre; ?>
<br>
<?php
} ?>
</div>
</div>
<div class="bloque_1"></div>
<div class="bloque_1">
<label><strong>Tipos de Cuentas</strong></label>
<div class="desplegable">
<img class="icon-marker-green">
<input type="checkbox" name="tipo" value="C">
Cliente
<br>
<!--img class="icon-marker-green">
<input type="checkbox" name="tipo" value="CT">
Cliente Telefonico
<br-->
<img class="icon-marker-yellow">
<input type="checkbox" name="tipo" value="T">
Transfer
<br>
<img class="icon-marker-orange">
<input type="checkbox" name="tipo" value="TT">
Transfer Telefonico
<br>
<img class="icon-marker-red">
<input type="checkbox" name="tipo" value="PS">
Prospecto
<br>
<img class="icon-marker">
Seleccionados
<br>
<img class="icon-marker-dark-green">
Cliente Inactivo
<br>
<img class="icon-marker-green-yellow">
Cliente Inactivo con Transfer Activo
<br>
<img class="icon-marker-orange-hover">
Transfer Inactivo
<br>
</div>
</div>
<div class="bloque_1"></div>
<div class="bloque_1">
<label><strong>Estado</strong></label>
<div class="desplegable">
<input type="radio" name="activas" value="2" checked>
<label>Todas</label>
<br>
<input type="radio" name="activas" value="1">
<label>Activas</label>
<br>
<input type="radio" name="activas" value="0">
<label>Inactivas</label>
</div>
</div>
</fieldset>
<div class="barra">
<div class="bloque_5">
<h1>Cuentas</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn" type="text" value="tblTablaCta" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<div id='tablacuenta'></div>
</div> <!-- Fin lista -->
<fieldset>
<div id="listCuentas"></div>
</fieldset>
</div>
<script src="/pedidos/zonas/logica/jquery/jquery.map.js"></script>
<script>
$("#filterMap").click(function () {
$("#waypoints").empty();
var tipo = [];
$.each($("input[name='tipo']:checked"), function(){
tipo.push("'"+$(this).val()+"'");
});
var zonas = [];
$.each($("input[name='zonas']:checked"), function(){
zonas.push($(this).val());
});
var geoloc = ($("input[name='geoloc']:checked").val()) ? 1 : 0;
var activas = $('input[name=activas]:checked').val();
var empresa = $('#empselect').val();
var data = {
tipo : tipo, //'"C", "T"',
activas : activas, //1,
empresa : empresa,
zonas : zonas,
geoloc : geoloc,
};
google.maps.event.addDomListener(window, 'load', initialize(data));
});
</script> <file_sep>/condicion/logica/ajax/actualizar.precios.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$arrayIdCond = empty($_POST['condid']) ? 0 : $_POST['condid'];
if(!$arrayIdCond){
echo "Seleccione condición para modificar."; exit;
}
if(count($arrayIdCond)){
foreach ($arrayIdCond as $j => $condId) {
if ($condId) {
$condObject = DataManager::newObjectOfClass('TCondicionComercial', $condId);
$empresa = $condObject->__get('Empresa');
$laboratorio = $condObject->__get('Laboratorio');
$tipo = $condObject->__get('Tipo');
$nombre = $condObject->__get('Nombre');
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
foreach ($articulosCond as $k => $artCond) {
$artCond = $articulosCond[$k];
$condArtId = $artCond['cartid'];
$condArtIdArt = $artCond['cartidart'];
$condArtPrecio = $artCond["cartprecio"];
$artPrecio = DataManager::getArticulo('artpreciolista', $condArtIdArt, $empresa, $laboratorio);
if($artPrecio){
$condArtObject = DataManager::newObjectOfClass('TCondicionComercialArt', $condArtId);
$condArtObject->__set('Precio' , $artPrecio);
DataManagerHiper::updateSimpleObject($condArtObject, $condArtId);
DataManager::updateSimpleObject($condArtObject);
} else {
echo "El artículo $condArtIdArt de la condición $tipo $nombre no se encuentra para actualizar. Verifique y vuelva a intentarlo"; exit;
}
}
}
// Registro MOVIMIENTO
$movimiento = 'ACTUALIZA_PRECIOS';
dac_registrarMovimiento($movimiento, "UPDATE", 'TCondicionComercial', $condId);
} else {
echo "Error al consultar condición."; exit;
}
}
echo "1"; exit;
} else {
echo "Seleccione una condición."; exit;
}
echo "Error de proceso en condiciones."; exit;
?><file_sep>/soporte/mensajes/logica/jquery/script.js
$(function(){"use strict"; $('#cerrarTicket').click(sendForm); });
/********************/
// SUBIR INFORMES UNICOS //
/********************/
function sendForm(){
"use strict";
var tkid = $('#tkid').val();
$.ajax({
url :'/pedidos/soporte/mensajes/logica/close.ticket.php',
type :'POST',
data : { tkid : tkid, },
contentType :false,
processData :false,
cache :false,
beforeSend : function () {
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
afterSend : function() {
$('#box_cargando').css({'display':'none'});
},
success : function(result) {
if(result){
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
} else {
//reenvía al inicia
}
},
});
}<file_sep>/proveedores/fechaspago/logica/jquery/jqueryHeader.js
// CARGAR FACTURA
var nextpagoinput = 0;
var saldo_total = 0;
function dac_CargarDatosPagos(k, idfact, idempresa, idprov, nombre, plazo, fechavto, tipo, factnro, fechacbte, saldo, observacion, activa){
"use strict";
nextpagoinput++;
var borrar = '<div class="bloque_10"><img id="borrar_fact" class=\"icon-delete\" onClick="dac_EliminarDetallePagos('+nextpagoinput+', '+saldo+')"/></div>';
var notificar = '<div class="bloque_10"><img class=\"icon-notify\" onClick="dac_NotificarFechaPago('+idempresa+', '+idprov+', '+factnro+')"/></div>';
var campo = '<div id="rutfact'+nextpagoinput+'">';
campo += '<input id="idfact'+nextpagoinput+'" name="idfact[]" type="text" value="'+idfact+'" readonly="readonly" hidden="hidden">';
campo += '<div class="bloque_10"><input id="empresa'+nextpagoinput+'" name="empresa[]" type="text" value="'+idempresa+'" readonly="readonly"></div>';
campo += '<div class="bloque_9"><input id="idprov'+nextpagoinput+'" name="idprov[]" type="text" value="'+idprov+'" readonly="readonly"></div>';
campo += '<div class="bloque_7"><input id="nombre'+nextpagoinput+'" name="nombre[]" type="text" value="'+nombre+'" readonly="readonly"></div>';
campo += '<div class="bloque_10"><input id="plazo'+nextpagoinput+'" name="plazo[]" type="text" value="'+plazo+'" readonly="readonly"></div>';
campo += '<div class="bloque_8"><input id="fechavto'+nextpagoinput+'" name="fechavto[]" type="text" value="'+fechavto+'" readonly="readonly"></div>';
campo += '<div class="bloque_10"><input id="tipo'+nextpagoinput+'" name="tipo[]" type="text" value="'+tipo+'" readonly="readonly"></div>';
campo += '<div class="bloque_9"><input id="factnro'+nextpagoinput+'" name="factnro[]" type="text" value="'+factnro+'" readonly="readonly"></div>';
campo += '<div class="bloque_8"><input id="fechacbte'+nextpagoinput+'" name="fechacbte[]" type="text" value="'+fechacbte+'" readonly="readonly"></div>';
campo += '<div class="bloque_9"><input id="saldo'+nextpagoinput+'" name="saldo[]" type="text" value="'+saldo+'" style="text-align:right;" readonly="readonly"></div>';
campo += '<div class="bloque_8"><input id="observacion'+nextpagoinput+'" name="observacion[]" type="text" value="'+observacion+'"></div>';
campo += borrar;
campo += notificar+'<hr class="hr-line">';
$("#lista_fechaspago").before(campo);
saldo_total += parseFloat(saldo);
document.getElementById('saldo_total').innerHTML = dac_Redondeo(saldo_total, 2);
}
function dac_EliminarDetallePagos(id, saldo){
"use strict";
var elemento = document.getElementById('rutfact'+id);
elemento.parentNode.removeChild(elemento);
saldo_total -= parseFloat(saldo);
document.getElementById('saldo_total').innerHTML = dac_Redondeo(saldo_total, 2);
}
function dac_NotificarFechaPago(idemp, idprov, factnro){
"use strict";
var fecha = document.getElementById('f_fecha').value;
$.ajax({
type : "POST",
cache : false,
url : "/pedidos/proveedores/fechaspago/logica/ajax/notificar.fechapago.php",
data : { idempresa : idemp,
idprov : idprov,
fechapago : fecha,
factnro : factnro },
beforeSend: function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function(result) {
if(result){
$('#box_cargando').css({'display':'none'});
if(result.replace("\n","") !== '1'){
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
subir();
} else{
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('Se envió la notificación de fecha de pago');
setTimeout($('#box_confirmacion').css({'display':'block'}), 5000);
}
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("ERROR! al cargar los datos del proveedor");
}
});
}
/* Controla si el proveedor está activo en el listado de proveedores */
function dac_ControlProveedor(idempresa, idprov){
"use strict";
$.ajax({
type : "POST",
cache : false,
url : "/pedidos/proveedores/fechaspago/logica/ajax/control.proveedor.php",
data : { idempresa : idempresa,
idprov : idprov },
beforeSend: function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function(result) {
if(result){
$('#box_cargando').css({'display':'none'});
if(result.replace("\n","") !== '1'){
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
subir();
}
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("ERROR! al cargar los datos del proveedor");
}
});
}<file_sep>/condicion/logica/update.condicion.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$condId = (isset($_POST['condid'])) ? $_POST['condid'] : NULL;
$empresa = (isset($_POST['empselect'])) ? $_POST['empselect'] : NULL;
$laboratorio = (isset($_POST['labselect'])) ? $_POST['labselect'] : NULL;
$nombre = (isset($_POST['nombre'])) ? $_POST['nombre'] : NULL;
$tipo = (isset($_POST['tiposelect'])) ? $_POST['tiposelect'] : NULL;
$condPago = (isset($_POST['condpago'])) ? $_POST['condpago'] : NULL;
$condPagoId = (isset($_POST['condpagoid'])) ? $_POST['condpagoid'] : '';
$cantMinima = (isset($_POST['cantMinima'])) ? $_POST['cantMinima'] : NULL;
$minReferencias = (isset($_POST['minReferencias'])) ? $_POST['minReferencias'] : NULL;
$minMonto = (isset($_POST['minMonto'])) ? $_POST['minMonto'] : NULL;
$fechaInicio = (isset($_POST['fechaInicio'])) ? $_POST['fechaInicio'] : NULL;
$fechaFin = (isset($_POST['fechaFin'])) ? $_POST['fechaFin'] : NULL;
$observacion = (isset($_POST['observacion'])) ? $_POST['observacion'] : NULL;
$cuentaId = (isset($_POST['cuentaid'])) ? $_POST['cuentaid'] : '';
$lista = (isset($_POST['listaPrecio'])) ? $_POST['listaPrecio'] : 0;
//Condición Habitual
$habitualCant = (isset($_POST['habitualCant'])) ? $_POST['habitualCant'] : '';
$habitualBonif1 = (isset($_POST['habitualBonif1'])) ? $_POST['habitualBonif1'] : NULL;
$habitualBonif2 = (isset($_POST['habitualBonif2'])) ? $_POST['habitualBonif2'] : NULL;
$habitualDesc1 = (isset($_POST['habitualDesc1'])) ? $_POST['habitualDesc1'] : NULL;
$habitualDesc2 = (isset($_POST['habitualDesc2'])) ? $_POST['habitualDesc2'] : NULL;
//String para pasar a array
//$arrayCondIdCond= (isset($_POST['condidcond'])) ? $_POST['condidcond'] : NULL;
$arrayCondIdArt = (isset($_POST['condidart'])) ? $_POST['condidart'] : NULL;
$arrayPrecioArt = (isset($_POST['condprecioart'])) ? $_POST['condprecioart'] : NULL;
$arrayPrecioDigit= (isset($_POST['condpreciodigit'])) ? $_POST['condpreciodigit']: NULL;
$arrayCantMin = (isset($_POST['condcantmin'])) ? $_POST['condcantmin'] : NULL;
$arrayEstadoOAM = (isset($_POST['condoferta'])) ? $_POST['condoferta'] : NULL;
$arayOfertaCheck = (isset($_POST['condofertacheck'])) ? $_POST['condofertacheck'] : NULL;
//Arrays de string para pasar a Arrays
$arrayCant = (isset($_POST['condcant'])) ? explode('|', $_POST['condcant']) : NULL;
$arrayBonif1 = (isset($_POST['condbonif1'])) ? explode('|', $_POST['condbonif1']) : NULL;
$arrayBonif2 = (isset($_POST['condbonif2'])) ? explode('|', $_POST['condbonif2']) : NULL;
$arrayDesc1 = (isset($_POST['conddesc1'])) ? explode('|', $_POST['conddesc1']) : NULL;
$arrayDesc2 = (isset($_POST['conddesc2'])) ? explode('|', $_POST['conddesc2']) : NULL;
if (empty($empresa)) {
echo "Seleccione una empresa."; exit;
}
if (empty($laboratorio)) {
echo "Indique un laboratorio."; exit;
}
if(empty($tipo)){
echo "Indique el tipo de condición"; exit;
}
if(empty($nombre)){
echo "Indique el nombre de condición"; exit;
}
if(!empty($cantMinima) && (!is_numeric($cantMinima) || $cantMinima < 0)){
echo "La cantidad mínima debe ser numérica"; exit;
}
if(!empty($minReferencias) && (!is_numeric($minReferencias) || $minReferencias < 0)){
echo "El mínimo de referencias debe ser numérico"; exit;
}
if($lista != 0 && (!empty($cuentaId) || !empty($condPagoId)) ){
echo "Una condición tipo lista no puede tener cuentas relacionadas ni condiciones de pago"; exit;
} else {
//Controla que la lista no exista activa en otra condicion comercial activa en fecha inicio y fin actual.
//$fechaListasHoy = new DateTime('now'); //$fechaListasHoy->format("Y-m-d")
//$fechaInicio->format("Y-m-d")
//$fechaFin->format("Y-m-d")
$fechaDesde = new DateTime($fechaInicio);
$fechaHasta = new DateTime($fechaFin);
$condicionesListas = DataManager::getCondiciones(0, 0, 1, $empresa, $laboratorio, $fechaDesde->format("Y-m-d"), NULL, NULL, NULL, NULL, NULL);
if($condicionesListas){
foreach($condicionesListas as $k => $cond){
$condIdCond = $cond['condid'];
$condNombre = $cond['condnombre'];
$condLista = $cond['condlista'];
if($condId != $condIdCond && $condLista == $lista && $condLista != 0){
echo "Ya existe la condción comercial '".$condNombre."' con la misma lista de precios definida."; exit;
}
}
}
}
if(!empty($minMonto) && (!is_numeric($minMonto) || $minMonto < 0)){
echo "El Monto Mínimo debe ser numérico"; exit;
}
if (empty($fechaInicio) || empty($fechaFin)) {
echo "Debe indicar fecha de Inicio y Fin"; exit;
}
$fechaI = new DateTime($fechaInicio);
$fechaF = new DateTime($fechaFin);
if($fechaI->format("Y-m-d") >= $fechaF->format("Y-m-d")){
echo "La fecha de Inicio debe ser menor que la de Fin"; exit;
}
if (count($arrayCondIdArt) < 1){
echo "Cargue artículos a la condición."; exit;
} else {
//Controlar que no se repitan los artículos
$resultado = dac_duplicadoEnArray($arrayCondIdArt);
if($resultado){ echo $resultado; exit; }
}
//***********************************//
//Control de los artículos cargados //
//empieza el for desde el 1 porque el cero envía en todos un valor desconocido.
for($k = 0; $k < count($arrayCondIdArt); $k++){
if (empty($arrayPrecioArt[$k]) || !is_numeric($arrayPrecioArt[$k])){
echo "El precio del artículo ".$arrayCondIdArt[$k]." es incorrecto"; exit;
}
if (!empty($arrayPrecioDigit[$k]) && !is_numeric($arrayPrecioDigit[$k]) || $arrayPrecioDigit[$k] < 0){
echo "El precio digitado del artículo ".$arrayCondIdArt[$k]." es incorrecto"; exit;
}
if ($arrayCantMin[$k] < 0){
echo "La cantidad mínima del artículo ".$arrayCondIdArt[$k]." debe ser mayor o igual a cero."; exit;
}
$arrayPrecioDigit[$k] = empty($arrayPrecioDigit[$k]) ? 0 : $arrayPrecioDigit[$k];
$arrayCantMin[$k] = empty($arrayCantMin[$k]) ? 0 : $arrayCantMin[$k];
//si hay cantidades en el array cantidades
if($arrayCant[$k]){
//Arrays Bonificaciones del artículo K
$cant = explode("-", $arrayCant[$k]);
$bonif1 = explode("-", $arrayBonif1[$k]);
$bonif2 = explode("-", $arrayBonif2[$k]);
$desc1 = explode("-", $arrayDesc1[$k]);
$desc2 = explode("-", $arrayDesc2[$k]);
//Controlar que no se repitan las cantidades
$resultado = dac_duplicadoEnArray($cant);
if($resultado){ echo $resultado; exit; }
for($j = 0; $j < count($cant); $j++){
if(empty($cant[$j]) || $cant[$j] < 0){
echo "Indique las cantidadades para la bonificación del artículo ".$arrayCondIdArt[$k]; exit;
}
if (!empty($bonif1[$j]) || !empty($bonif2[$j])){
if (empty($bonif1[$j]) || empty($bonif2[$j]) || !is_numeric($bonif1[$j]) || !is_numeric($bonif2[$j]) || $bonif1[$j] < 1 || $bonif2[$j] < 1 || $bonif1[$j] <= $bonif2[$j]){
echo "La bonificación del artículo ".$arrayCondIdArt[$k]." con cantidad ".$cant[$j]." es incorrecta."; exit;
}
}
if ((!empty($desc1[$j]) && (!is_numeric($desc1[$j])) || $desc1[$j] < 0)){
echo "Un descuento 1 del artículo ".$arrayCondIdArt[$k]." con cantidad ".$cant[$j]." es incorrecto."; exit;
}
if ((!empty($desc2[$j]) && (!is_numeric($desc2[$j])) || $desc2[$j] < 0)){
echo "Un descuento 2 del artículo ".$arrayCondIdArt[$k]." con cantidad ".$cant[$j]." es incorrecto."; exit;
}
if(empty($bonif1[$j]) && empty($bonif2[$j]) && empty($desc1[$j]) && empty($desc2[$j])){
echo "Debe indicar bonificación o descuento para el artículo ".$arrayCondIdArt[$k]." con cantidad ".$cant[$j]."."; exit;
}
}
}
}
//**********//
// Grabar //
$cantMinima = empty($cantMinima) ? 0 : $cantMinima;
$minReferencias = empty($minReferencias) ? 0 : $minReferencias;
$minMonto = empty($minMonto) ? 0 : $minMonto;
$habitualCant = empty($habitualCant) ? 0 : $habitualCant;
$habitualBonif1 = empty($habitualBonif1) ? 0 : $habitualBonif1;
$habitualBonif2 = empty($habitualBonif2) ? 0 : $habitualBonif2;
$habitualDesc1 = empty($habitualDesc1) ? 0 : $habitualDesc1;
$habitualDesc2 = empty($habitualDesc2) ? 0 : $habitualDesc2;
$condObject = ($condId) ? DataManager::newObjectOfClass('TCondicionComercial', $condId) : DataManager::newObjectOfClass('TCondicionComercial');
$condObject->__set('Empresa' , $empresa);
$condObject->__set('Laboratorio' , $laboratorio);
$condObject->__set('Cuentas' , $cuentaId);
$condObject->__set('Nombre' , $nombre);
$condObject->__set('Tipo' , $tipo);
$condObject->__set('CondicionPago' , $condPagoId); //$condPago
$condObject->__set('CantidadMinima' , $cantMinima);
$condObject->__set('MinimoReferencias' , $minReferencias);
$condObject->__set('MinimoMonto' , $minMonto);
$condObject->__set('FechaInicio' , $fechaI->format("Y-m-d"));
$condObject->__set('FechaFin' , $fechaF->format("Y-m-d"));
$condObject->__set('Observacion' , $observacion);
$condObject->__set('Cantidad' , $habitualCant);
$condObject->__set('Bonif1' , $habitualBonif1);
$condObject->__set('Bonif2' , $habitualBonif2);
$condObject->__set('Desc1' , $habitualDesc1);
$condObject->__set('Desc2' , $habitualDesc2);
$condObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$condObject->__set('LastUpdate' , date("Y-m-d H:i:s"));
$condObject->__set('Lista' , $lista);
if ($condId) {
//UPDATE
$IDCondCom = $condId;
DataManagerHiper::updateSimpleObject($condObject, $condId);
DataManager::updateSimpleObject($condObject);
//***************************************//
// Insert, Update o Delete de artículos //
$articulosCondicion = DataManager::getCondicionArticulos($condId);
if (count($articulosCondicion)) {
unset($arrayArticulosDDBB);
foreach ($articulosCondicion as $k => $artCond) {
$condArtId = $artCond['cartid'];
$condArtIdArt = $artCond['cartidart'];
//Creo el array de artículos de BBDD
$arrayArticulosDDBB[] = $condArtIdArt;
if (count($arrayCondIdArt) && in_array($condArtIdArt, $arrayCondIdArt)) {
//B //UPDATE
//Indice de donde se encuentra el artículo en el array web
$key = array_search($condArtIdArt, $arrayCondIdArt);
unset($cant);
$cant = explode("-", $arrayCant[$key]);
unset($arrayCantidadesDDBB);
$condArtObject = DataManager::newObjectOfClass('TCondicionComercialArt', $condArtId);
$condArtObject->__set('Precio' , $arrayPrecioArt[$key]);
$condArtObject->__set('Digitado' , $arrayPrecioDigit[$key]);
$condArtObject->__set('CantidadMinima' , $arrayCantMin[$key]);
$condArtObject->__set('OAM' , $arrayEstadoOAM[$key]);
$condArtObject->__set('Oferta' , $arayOfertaCheck[$key]);
DataManagerHiper::updateSimpleObject($condArtObject, $condArtId);
DataManager::updateSimpleObject($condArtObject);
$bonificacionesArt = DataManager::getCondicionBonificaciones($condId, $condArtIdArt);
if (count($bonificacionesArt)) {
foreach ($bonificacionesArt as $j => $bonifArt) {
$bonifArtID = $bonifArt['cbid'];
$bonifArtCant = ($bonifArt['cbcant']) ? $bonifArt['cbcant'] : 0;
//Creo el array de cantidades de BBDD de ésta condicion y artículo
$arrayCantidadesDDBB[] = $bonifArtCant;
if(count($cant) && in_array($bonifArtCant, $cant)) {
//B //UPDATE bonificacion
$bonif1 = explode("-", $arrayBonif1[$key]);
$bonif2 = explode("-", $arrayBonif2[$key]);
$desc1 = explode("-", $arrayDesc1[$key]);
$desc2 = explode("-", $arrayDesc2[$key]);
//indice de bonificaciones donde se encuentra la cantidad
$key2 = array_search($bonifArtCant, $cant);
$bonif1[$key2] = empty($bonif1[$key2]) ? 0 : $bonif1[$key2];
$bonif2[$key2] = empty($bonif2[$key2]) ? 0 : $bonif2[$key2];
$desc1[$key2] = empty($desc1[$key2]) ? 0 : $desc1[$key2];
$desc2[$key2] = empty($desc2[$key2]) ? 0 : $desc2[$key2];
//-----------------
$condBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif', $bonifArtID);
$condBonifObject->__set('Bonif1' , $bonif1[$key2]);
$condBonifObject->__set('Bonif2' , $bonif2[$key2]);
$condBonifObject->__set('Desc1' , $desc1[$key2]);
$condBonifObject->__set('Desc2' , $desc2[$key2]);
DataManagerHiper::updateSimpleObject($condBonifObject, $bonifArtID);
DataManager::updateSimpleObject($condBonifObject);
} else {
//C //DELETE bonificacion
$condBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif', $bonifArtID);
$condBonifObject->__set('ID', $bonifArtID);
DataManagerHiper::deleteSimpleObject($condBonifObject, $bonifArtID);
DataManager::deleteSimpleObject($condBonifObject);
}
}
//INSERT Bonificaciones
if(count($cant)){
$bonif1 = explode("-", $arrayBonif1[$key]);
$bonif2 = explode("-", $arrayBonif2[$key]);
$desc1 = explode("-", $arrayDesc1[$key]);
$desc2 = explode("-", $arrayDesc2[$key]);
for($j = 0; $j < count($cant); $j++){
if(!in_array($cant[$j], $arrayCantidadesDDBB)) {
$bonif1[$j] = empty($bonif1[$j]) ? 0 : $bonif1[$j];
$bonif2[$j] = empty($bonif2[$j]) ? 0 : $bonif2[$j];
$desc1[$j] = empty($desc1[$j]) ? 0 : $desc1[$j];
$desc2[$j] = empty($desc2[$j]) ? 0 : $desc2[$j];
//-----------------
$condBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif');
$condBonifObject->__set('Condicion' , $condId);
$condBonifObject->__set('Articulo' , $condArtIdArt);
$condBonifObject->__set('Cantidad' , $cant[$j]);
$condBonifObject->__set('Bonif1' , $bonif1[$j]);
$condBonifObject->__set('Bonif2' , $bonif2[$j]);
$condBonifObject->__set('Desc1' , $desc1[$j]);
$condBonifObject->__set('Desc2' , $desc2[$j]);
$condBonifObject->__set('Activo' , 0);
$condBonifObject->__set('ID' , $condBonifObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDCondBonif = DataManager::insertSimpleObject($condBonifObject);
DataManagerHiper::insertSimpleObject($condBonifObject, $IDCondBonif);
}
}
}
} else {
//A //INSERT Bonificaciones
if($arrayCant[$key]){
$bonif1 = explode("-", $arrayBonif1[$key]);
$bonif2 = explode("-", $arrayBonif2[$key]);
$desc1 = explode("-", $arrayDesc1[$key]);
$desc2 = explode("-", $arrayDesc2[$key]);
for($j = 0; $j < count($cant); $j++){
$bonif1[$j] = empty($bonif1[$j]) ? 0 : $bonif1[$j];
$bonif2[$j] = empty($bonif2[$j]) ? 0 : $bonif2[$j];
$desc1[$j] = empty($desc1[$j]) ? 0 : $desc1[$j];
$desc2[$j] = empty($desc2[$j]) ? 0 : $desc2[$j];
//-----------------
$condBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif');
$condBonifObject->__set('Condicion' , $condId);
$condBonifObject->__set('Articulo' , $condArtIdArt);
$condBonifObject->__set('Cantidad' , $cant[$j]);
$condBonifObject->__set('Bonif1' , $bonif1[$j]);
$condBonifObject->__set('Bonif2' , $bonif2[$j]);
$condBonifObject->__set('Desc1' , $desc1[$j]);
$condBonifObject->__set('Desc2' , $desc2[$j]);
$condBonifObject->__set('Activo' , 0);
$condBonifObject->__set('ID' , $condBonifObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDCondBonif = DataManager::insertSimpleObject($condBonifObject);
DataManagerHiper::insertSimpleObject($condBonifObject, $IDCondBonif);
}
}
}
} else {
//C //DELETE de artículos
$condArtObject = DataManager::newObjectOfClass('TCondicionComercialArt', $condArtId);
$condArtObject->__set('ID', $condArtId);
DataManagerHiper::deleteSimpleObject($condArtObject, $condArtId);
DataManager::deleteSimpleObject($condArtObject);
$bonificacionesArt = DataManager::getCondicionBonificaciones($condId, $condArtIdArt);
if (count($bonificacionesArt)) {
foreach ($bonificacionesArt as $j => $bonifArt) {
$IDCondBonif = $bonifArt['cbid'];
$condBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif', $IDCondBonif);
$condBonifObject->__set('ID', $IDCondBonif);
DataManagerHiper::deleteSimpleObject($condBonifObject, $IDCondBonif);
DataManager::deleteSimpleObject($condBonifObject);
}
}
}
}
//Recorro e INSERT DE los artículos en el array que no estan en la addbb para insertar
for($k = 0; $k < count($arrayCondIdArt); $k++){
if(!in_array($arrayCondIdArt[$k], $arrayArticulosDDBB)) {
$condArtObject = DataManager::newObjectOfClass('TCondicionComercialArt');
$condArtObject->__set('Condicion' , $condId);
$condArtObject->__set('Articulo' , $arrayCondIdArt[$k]);
$condArtObject->__set('Precio' , $arrayPrecioArt[$k]);
$condArtObject->__set('Digitado' , $arrayPrecioDigit[$k]);
$condArtObject->__set('CantidadMinima' , $arrayCantMin[$k]);
$condArtObject->__set('OAM' , $arrayEstadoOAM[$k]);
$condArtObject->__set('Oferta' , $arayOfertaCheck[$k]);
$condArtObject->__set('Activo' , 0);
$condArtObject->__set('ID' , $condArtObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDCondArt = DataManager::insertSimpleObject($condArtObject);
DataManagerHiper::insertSimpleObject($condArtObject, $IDCondArt);
if($arrayCant[$k]){
//INSERT Bonificaciones
$cant = explode("-", $arrayCant[$k]);
$bonif1 = explode("-", $arrayBonif1[$k]);
$bonif2 = explode("-", $arrayBonif2[$k]);
$desc1 = explode("-", $arrayDesc1[$k]);
$desc2 = explode("-", $arrayDesc2[$k]);
for($j = 0; $j < count($cant); $j++){
$bonif1[$j] = empty($bonif1[$j]) ? 0 : $bonif1[$j];
$bonif2[$j] = empty($bonif2[$j]) ? 0 : $bonif2[$j];
$desc1[$j] = empty($desc1[$j]) ? 0 : $desc1[$j];
$desc2[$j] = empty($desc2[$j]) ? 0 : $desc2[$j];
//-----------------
$condBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif');
$condBonifObject->__set('Condicion' , $condId);
$condBonifObject->__set('Articulo' , $arrayCondIdArt[$k]);
$condBonifObject->__set('Cantidad' , $cant[$j]);
$condBonifObject->__set('Bonif1' , $bonif1[$j]);
$condBonifObject->__set('Bonif2' , $bonif2[$j]);
$condBonifObject->__set('Desc1' , $desc1[$j]);
$condBonifObject->__set('Desc2' , $desc2[$j]);
$condBonifObject->__set('Activo' , 0);
$condBonifObject->__set('ID' , $condBonifObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDCondBonif = DataManager::insertSimpleObject($condBonifObject);
DataManagerHiper::insertSimpleObject($condBonifObject, $IDCondBonif);
}
}
}
}
} else {
//INSERT Articulos //Si no hay artículos en la BBDD, solo inserta
for($k = 0; $k < count($arrayCondIdArt); $k++){
$condArtObject = DataManager::newObjectOfClass('TCondicionComercialArt');
$condArtObject->__set('Condicion' , $condId);
$condArtObject->__set('Articulo' , $arrayCondIdArt[$k]);
$condArtObject->__set('Precio' , $arrayPrecioArt[$k]);
$condArtObject->__set('Digitado' , $arrayPrecioDigit[$k]);
$condArtObject->__set('CantidadMinima' , $arrayCantMin[$k]);
$condArtObject->__set('OAM' , $arrayEstadoOAM[$k]);
$condArtObject->__set('Oferta' , $arayOfertaCheck[$k]);
$condArtObject->__set('Activo' , 0);
$condArtObject->__set('ID' , $condArtObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDCondArt = DataManager::insertSimpleObject($condArtObject);
DataManagerHiper::insertSimpleObject($condArtObject, $IDCondArt);
//Si hay bonificaciones cargadas
if($arrayCant[$k]){
//INSERT Bonificaciones
$cant = explode("-", $arrayCant[$k]);
$bonif1 = explode("-", $arrayBonif1[$k]);
$bonif2 = explode("-", $arrayBonif2[$k]);
$desc1 = explode("-", $arrayDesc1[$k]);
$desc2 = explode("-", $arrayDesc2[$k]);
for($j = 0; $j < count($cant); $j++){
$bonif1[$j] = empty($bonif1[$j]) ? 0 : $bonif1[$j];
$bonif2[$j] = empty($bonif2[$j]) ? 0 : $bonif2[$j];
$desc1[$j] = empty($desc1[$j]) ? 0 : $desc1[$j];
$desc2[$j] = empty($desc2[$j]) ? 0 : $desc2[$j];
//-----------------
$condBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif');
$condBonifObject->__set('Condicion' , $condId);
$condBonifObject->__set('Articulo' , $arrayCondIdArt[$k]);
$condBonifObject->__set('Cantidad' , $cant[$j]);
$condBonifObject->__set('Bonif1' , $bonif1[$j]);
$condBonifObject->__set('Bonif2' , $bonif2[$j]);
$condBonifObject->__set('Desc1' , $desc1[$j]);
$condBonifObject->__set('Desc2' , $desc2[$j]);
$condBonifObject->__set('Activo' , 0);
$condBonifObject->__set('ID' , $condBonifObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDCondBonif = DataManager::insertSimpleObject($condBonifObject);
DataManagerHiper::insertSimpleObject($condBonifObject, $IDCondBonif);
}
}
}
}
//MOVIMIENTO Condiciones Comerciales
$condId = $IDCondCom;
$movimiento = 'CONDICION_COMERCIAL';
$movTipo = 'UPDATE';
} else {
//INSERT Condicion
$condObject->__set('ID' , $condObject->__newID());
$condObject->__set('Activa' , 0);
DataManagerHiper::_getConnection('Hiper');
$IDCondCom = DataManager::insertSimpleObject($condObject);
DataManagerHiper::insertSimpleObject($condObject, $IDCondCom);
//INSERT Articulos
for($k = 0; $k < count($arrayCondIdArt); $k++){
$condArtObject = DataManager::newObjectOfClass('TCondicionComercialArt');
$condArtObject->__set('Condicion' , $IDCondCom);
$condArtObject->__set('Articulo' , $arrayCondIdArt[$k]);
$condArtObject->__set('Precio' , $arrayPrecioArt[$k]);
$condArtObject->__set('Digitado' , $arrayPrecioDigit[$k]);
$condArtObject->__set('CantidadMinima' , $arrayCantMin[$k]);
$condArtObject->__set('OAM' , $arrayEstadoOAM[$k]);
$condArtObject->__set('Oferta' , $arayOfertaCheck[$k]);
$condArtObject->__set('Activo' , 0);
$condArtObject->__set('ID' , $condArtObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDCondArt = DataManager::insertSimpleObject($condArtObject);
DataManagerHiper::insertSimpleObject($condArtObject, $IDCondArt);
if($arrayCant[$k]){
//INSERT Bonificaciones
$cant = explode("-", $arrayCant[$k]);
$bonif1 = explode("-", $arrayBonif1[$k]);
$bonif2 = explode("-", $arrayBonif2[$k]);
$desc1 = explode("-", $arrayDesc1[$k]);
$desc2 = explode("-", $arrayDesc2[$k]);
for($j = 0; $j < count($cant); $j++){
$bonif1[$j] = empty($bonif1[$j]) ? 0 : $bonif1[$j];
$bonif2[$j] = empty($bonif2[$j]) ? 0 : $bonif2[$j];
$desc1[$j] = empty($desc1[$j]) ? 0 : $desc1[$j];
$desc2[$j] = empty($desc2[$j]) ? 0 : $desc2[$j];
//-----------------
$condBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif');
$condBonifObject->__set('Condicion' , $IDCondCom);
$condBonifObject->__set('Articulo' , $arrayCondIdArt[$k]);
$condBonifObject->__set('Cantidad' , $cant[$j]);
$condBonifObject->__set('Bonif1' , $bonif1[$j]);
$condBonifObject->__set('Bonif2' , $bonif2[$j]);
$condBonifObject->__set('Desc1' , $desc1[$j]);
$condBonifObject->__set('Desc2' , $desc2[$j]);
$condBonifObject->__set('Activo' , 0);
$condBonifObject->__set('ID' , $condBonifObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDCondBonif = DataManager::insertSimpleObject($condBonifObject);
DataManagerHiper::insertSimpleObject($condBonifObject, $IDCondBonif);
}
}
}
//MOVIMIENTO Condicion Comerciales
$condId = $IDCondCom;
$movimiento = 'CONDICION_COMERCIAL';
$movTipo = 'INSERT';
}
// Registro movimiento
dac_registrarMovimiento($movimiento, $movTipo, 'TCondicionComercial', $condId);
//Controlar las fechas con condiciones comerciales finalizadas que estén activas, para desactivar
$condiciones = DataManager::getCondiciones(0, 0, 1);
if($condiciones){
$fechaHoy = new DateTime('now');
foreach($condiciones as $k => $condicion) {
$fechaFinal = new DateTime($condicion['condfechafin']);
if($fechaFinal->format("Y-m-d") < $fechaHoy->format("Y-m-d")){
$condId = $condicion['condid'];
$condObject = DataManager::newObjectOfClass('TCondicionComercial', $condId);
$condObject->__set('Activa' , 0);
DataManagerHiper::updateSimpleObject($condObject, $condId);
DataManager::updateSimpleObject($condObject);
//MOVIMIENTO Condicion Comerciales
$movimiento = 'DesactivaPorFechaFin_'.$fechaFinal->format("Y-m-d")."_menorA_".$fechaHoy->format("Y-m-d");
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, 'TCondicionComercial', $condId);
}
}
}
echo 1; exit;
?><file_sep>/includes/class/class.condicionespecial.php
<?php
require_once('class.PropertyObject.php');
class TCondicionEspecial extends PropertyObject {
protected $_tablename = 'condicion_especial';
protected $_fieldid = 'condid';
protected $_fieldactivo = 'condactiva';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'condid';
$this->propertyTable['Empresa'] = 'condidemp';
$this->propertyTable['Laboratorio'] = 'condidlab';
$this->propertyTable['Cliente'] = 'condidcliente';
$this->propertyTable['Bonificacion1'] = 'condbonif1';
$this->propertyTable['Bonificacion2'] = 'condbonif2';
$this->propertyTable['Descuento1'] = 'conddesc1';
$this->propertyTable['Descuento2'] = 'conddesc2';
$this->propertyTable['CondicionPago'] = 'condcondpago';
$this->propertyTable['Observacion'] = 'condobservacion';
$this->propertyTable['Activa'] = 'condactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
/*public function __getFieldActivo() {
return $this->_fieldactivo;
}*/
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/includes/class/class.PropertyObject.php
<?php
require_once('interface.Validator.php');
abstract class PropertyObject implements Validator {
protected $data; //datos actuales de la BBDD (Sin cambios)
protected $propertyTable = array(); //almacena pares nombre-valor asociando propiedades a campos de la BBDD.
protected $changedProperties = array(); //lista de propiedades que han sido cambiadas
protected $errors = array(); //Errores de validación
protected $updatePending = FALSE; //Actualización pendiente
public function __construct($arData) {
$this->data = $arData;
}
function __get($propertyName) {
if(!array_key_exists($propertyName, $this->propertyTable)) throw new Exception("Propiedad inexistente: \"$propertyName\"!");
if(method_exists($this, 'get' . $propertyName)) {
return call_user_func(array($this, 'get' . $propertyName));
} else {
return $this->data[0][$this->propertyTable[$propertyName]];
}
}
function __set($propertyName, $value) {
if(!array_key_exists($propertyName, $this->propertyTable)) throw new Exception("Propiedad inexistente: \"$propertyName\"!");
if(method_exists($this, 'set' . $propertyName)) {
$this->updatePending = TRUE;
return call_user_func( array($this, 'set' . $propertyName), $value );
} else {
//Si el valor de la propiedad ha cambiado y la propiedad no se h incluido entre las cambiadas, lo hacemos aquí.
// if($this->data[$this->propertyTable[$propertyName]] != $value && !in_array($propertyName, $this->changedProperties)) {
if(!in_array($propertyName, $this->changedProperties)) {
$this->changedProperties[] = $propertyName;
}
//Now set the new value
$this->updatePending = TRUE;
$this->data[$this->propertyTable[$propertyName]] = $value;
}
}
// Devuelve el nombre de campo de tabla que corresponde con una propiedad;
//
function __getFieldName( $_propertyName ) {
return $this->propertyTable[$_propertyName];
}
// Devuelve el array (nombre_campo_tabla => valor_campo) para inserciones en la BBDD
//
function __getData() {
return $this->data;
}
// Necesario Actualizar?
//
function __updatePending() {
return $this->updatePending;
}
// Devuelve el array (nombre_campo_tabla => valor_campo) únicamente de aquellos campos modificados
//
function __getUpdated() {
$_updated = array();
foreach($this->changedProperties as $k => $property) {
$_updated[$this->propertyTable[$property]] = $this->data[$this->propertyTable[$property]];
}
return $_updated;
}
function validate() {
return true;
}
}
?>
<file_sep>/relevamiento/logica/changestatus.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$_relid = empty($_REQUEST['relid']) ? 0 : $_REQUEST['relid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/relevamiento/' : $_REQUEST['backURL'];
if ($_relid) {
$_relobject = DataManager::newObjectOfClass('TRelevamiento', $_relid);
$_status = ($_relobject->__get('Activo')) ? 0 : 1;
$_relobject->__set('Activo', $_status);
$ID = DataManager::updateSimpleObject($_relobject);
}
header('Location: '.$backURL.'?pag='.$_pag);
?><file_sep>/login/logout.php
<?php
session_start();
$_SESSION = array();
$_toURL = "/pedidos/index.php";
session_unset();
session_destroy();
header("location: " . $_toURL);
?><file_sep>/includes/class/class.propuesta.php
<?php
require_once('class.PropertyObject.php');
class TPropuesta extends PropertyObject {
protected $_tablename = 'propuesta';
protected $_fieldid = 'propid';
protected $_fieldactivo = 'propactiva';
protected $_timestamp = 0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'propid';
$this->propertyTable['Nombre'] = 'propnombre'; //el nombre sería editable en otro tipo de propuestas
$this->propertyTable['Tipo'] = 'proptipo'; //Podriá tipificarse en códigos 1 - Venta 2 - Alquiler - etc
$this->propertyTable['Estado'] = 'propestado'; //estado ACTUAL de la propuesta PENDIENTE/APROBADA/RECHAZADA
$this->propertyTable['Cuenta'] = 'propidcuenta';
$this->propertyTable['Empresa'] = 'propidempresa';
$this->propertyTable['Laboratorio'] = 'propidlaboratorio';
$this->propertyTable['Fecha'] = 'propfecha';
$this->propertyTable['FechaCierre'] = 'propfechacierre';
$this->propertyTable['UsrCreate'] = 'propusr';
$this->propertyTable['UsrAsignado'] = 'propusrasignado';
$this->propertyTable['LastUpdate'] = 'proplastupdate';
$this->propertyTable['UsrUpdate'] = 'propusrupdate';
$this->propertyTable['Observacion'] = 'propobservacion';
$this->propertyTable['Activa'] = 'propactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->propertyTable['ID']);
//return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/includes/class/class.cheques.php
<?php
require_once('class.PropertyObject.php');
class TCheques extends PropertyObject {
protected $_tablename = 'cheques';
protected $_fieldid = 'cheqid';
//protected $_fieldactivo = 'cheqactivo';
protected $_timestamp = 0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'cheqid'; //Relación con tabla "fact_cheq" para IDFactura
$this->propertyTable['Banco'] = 'cheqbanco';
$this->propertyTable['Numero'] = 'cheqnumero';
$this->propertyTable['Fecha'] = 'cheqfecha';
$this->propertyTable['Importe'] = 'cheqimporte';
//$this->propertyTable['Activa'] = 'cheqactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
/*
public function Autenticado() {
return $this->_autenticado;
}*/
public function __newID() {
// Devuelve '#petid' para el alta de un nuevo registro
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/includes/class/class.facturaprov.php
<?php
require_once('class.PropertyObject.php');
class TFacturaProv extends PropertyObject {
protected $_tablename = 'facturas_proveedor';
protected $_fieldid = 'factid';
protected $_fieldactivo = 'factactiva';
protected $_timestamp = 0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'factid';
$this->propertyTable['Empresa'] = 'factidemp';
$this->propertyTable['Proveedor'] = 'factidprov';
$this->propertyTable['Plazo'] = 'factplazo';
$this->propertyTable['Tipo'] = 'facttipo';
$this->propertyTable['Sucursal'] = 'factsuc';
$this->propertyTable['Numero'] = 'factnumero';
$this->propertyTable['Comprobante'] = 'factfechacbte';
$this->propertyTable['Vencimiento'] = 'factfechavto';
$this->propertyTable['Saldo'] = 'factsaldo';
$this->propertyTable['Pago'] = 'factfechapago';
$this->propertyTable['Observacion'] = 'factobservacion';
$this->propertyTable['Activa'] = 'factactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
// Devuelve '#$_ID' para el alta de un nuevo registro
return ('#'.$this->propertyTable['ID']);
}
}
?><file_sep>/js/provincias/selectScript.localidad.js
/*La funcion $( document ).ready hace que no se carge el script hasta que este cargado el html*/
$( document ).ready(function() {
/*Esta funcion se activa cada vez que se cambia el elemento seleccionado del <select id=f_localidad>*/
$('#f_localidad').change(function(){
/*Variable para almacenar la informacion que nos devuelve el servicio php*/
var codigosPostales;
/*Coge el value de elemento seleccionado del <select id=f_localidad>*/
var nombreLocalidad = $('#f_localidad option:selected').val();
/*Esta es la funcion de la peticion ajax. El primer parametro es la direccion del servicio php
en el que se hace la peticion de informacion, el segundo parametro es la funcion que se ejecuta
cuando se devuelve los datos por JSON.
El ajax accede desde el html que lo carga no desde el script de js.*/
$.getJSON('/pedidos/js/provincias/getCodigosPostales.php?nombreLocalidad='+nombreLocalidad, function(datos) {
codigosPostales = datos;
/*Borro la lista cada vez que se pide una nueva provincia para que no se acumulen las anteriores*/
//$('#f_codigopostal').find('option').remove();
$('#codigopostal').val("");
/*Hago un foreach en jQuery para cada elemento del array ciudades y lo inserto en el <select id="ciudad">*/
$.each( codigosPostales, function( key, value ) {
$('#codigopostal').val(value);
});
});
});
});
<file_sep>/planificacion/logica/jquery/jqueryUsr.js
var nextplanifinput = 0;
function dac_Carga_Planificacion(cliente, nombre, direccion, activa) {
"use strict";
nextplanifinput++;
var borrar;
if(activa === '1'){
borrar = '<img id="borrar_planif" class="icon-uncheck" onClick="EliminarDetallePlanif('+nextplanifinput+')"/>';
} else {
borrar = '<img id="borrar_planif" class="icon-check"/>';
}
var campo = '<div id="rutplanif'+nextplanifinput+'"><div class="bloque_9">'+borrar+'</div><div class="bloque_8"><input id="planifcliente'+nextplanifinput+'" name="planifcliente[]" type="text" value="'+cliente+'" placeholder="* CUENTA" onblur=\"javascript:dac_Buscar_Cliente(this.value, '+nextplanifinput+', 0)\"></div><div class="bloque_6"><input id="planifnombre'+nextplanifinput+'" name="planifnombre[]" type="text" value="'+nombre+'" placeholder="* NOMBRE" readonly="readonly"></div><div class="bloque_6"><input id="planifdir'+nextplanifinput+'" name="planifdir[]" type="text" value="'+direccion+'" placeholder="* CALLE" readonly="readonly"></div></div><hr>';
$("#detalle_planif").after(campo);
}
function EliminarDetallePlanif(id){
"use strict";
var elemento = document.getElementById('rutplanif'+id);
elemento.parentNode.removeChild(elemento);
}
var nextparteinput = 0;
function dac_Carga_Parte(cliente, nombre, direccion, trabaja, observacion, accion, activo, planificado, acciones){
"use strict";
nextparteinput++;
var campo = '<div id="rutparte'+nextparteinput+'">';
var readonly = '';
var readonly_2 = '';
var deshabilitar= '';
if(activo === '0'){ //fué enviado el parte por lo que no podrá modificar nada y estará con el check ok
readonly = 'readonly="readonly"';
readonly_2 = 'readonly="readonly"';
deshabilitar= 'disabled="disabled"';
campo = campo + '<div class="bloque_8"><label>' + nextparteinput + '</label><img id="borrar_parte" class="icon-check"/></div><div class="bloque_8"><input id="partecliente'+nextparteinput+'" name="partecliente[]" type="text" value="'+cliente+'" '+readonly+'/></div>';
}else{
if(planificado==='1'){//no se puodrá eliminar o modificar el cliente de los registros ya planificados
readonly = 'readonly="readonly"';
campo = campo + '<div class="bloque_8"><label>' + nextparteinput + '</label><img id="borrar_parte" class="icon-uncheck"/></div>';
campo = campo + '<div class="bloque_8"><input id="partecliente'+nextparteinput+'" name="partecliente[]" type="text" value="'+cliente+'" '+readonly+'/></div>';
} else { //readonly
campo = campo + '<div class="bloque_8"><label>' + nextparteinput + '</label><img id="borrar_parte" class="icon-uncheck" onClick="EliminarDetalleParte('+nextparteinput+')"/></div>';
campo = campo + '<div class="bloque_8"><input id="partecliente'+nextparteinput+'" name="partecliente[]" type="text" value="'+cliente+'" placeholder="* CLIENTE" onblur=\"javascript:dac_Buscar_Cliente(this.value, '+nextparteinput+', 1)\"/></div>';
}
}
campo = campo + '<div class="bloque_5"><input id="partenombre'+nextparteinput+'" name="partenombre[]" type="text" value="'+nombre+'" placeholder="NOMBRE" '+readonly+'/></div>';
campo = campo + '<div class="bloque_7"><input id="partedir'+nextparteinput+'" name="partedir[]" type="text" value="'+direccion+'" placeholder="CALLE" '+readonly+'/></div>';
//------------
// ACCIONES
var acid = 0;
var acnombre = 0;
var id_acciones = acciones;
if(id_acciones){
id_acciones = id_acciones.split("/");
acid = id_acciones[0].split(",");
acnombre = id_acciones[1].split(",");
}
//------------
campo = campo + '<input id="partenro'+nextparteinput+'" name="partenro[]" type="text" value="'+nextparteinput+'" readonly hidden/>';
campo = campo + '<div class="bloque_5"><div class="desplegable">';
//alert(accion); ejemplo 1,3,10
var idacciones = accion.split(",");
for (var i=0; i<acid.length; i++){ //acid.length = 10
var checked='';
for (var j=0; j<idacciones.length; j++){
if(idacciones[j] === acid[i]){checked='checked'; break;}
}
campo = campo + '<input id="parteaccion'+nextparteinput+'" type="checkbox" name="parteaccion'+nextparteinput+'[]" value="'+acid[i]+'" '+checked+' '+deshabilitar+' style="float:left;"><label>'+acnombre[i]+'</label><hr>';
}
campo = campo + '</div></div>';
campo = campo + '<div class="bloque_5"><input id="partetrabaja'+nextparteinput+'" name="partetrabaja[]" type="text" value="'+trabaja+'" placeholder="TRABAJÓ CON..." '+readonly_2+'/></div>';
campo = campo + '<div class="bloque_5"><textarea id="parteobservacion'+nextparteinput+'" name="parteobservacion[]" type="text" value="'+observacion+'" placeholder="OBSERVACIÓN" '+readonly_2+' onkeypress="return dac_ValidarCaracteres(event)">'+observacion+'</textarea></div>';
campo = campo + '<hr class="hr-line">';
campo = campo + '</div>';
$("#detalle_parte").after(campo);
}
function EliminarDetalleParte(id){
"use strict";
var elemento_parte = document.getElementById('rutparte'+id);
elemento_parte.parentNode.removeChild(elemento_parte);
}
/*****************************/
function dac_Buscar_Cliente(id, posicion, tipo){
"use strict";
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/planificacion/logica/ajax/buscar.cliente.php',
data:{ idcliente : id,
posicion : posicion,
tipo : tipo
},
success : function (result) {
if (result){
var elem = result.split('/', 4);
var nro = elem[0];
var pos = elem[1];
var cli = elem[2];
var dir = elem[3];
if(nro==='1'){ // Si el cliente se encontró
if(tipo===0){ //si es planificación
if(id!=='0'){
document.getElementById('planifnombre'+pos).value = cli;
document.getElementById('planifdir'+pos).value = dir;
} else {
document.getElementById('planifnombre'+pos).value = "";
document.getElementById('planifdir'+pos).value = "";
}
} else { //si es para parte diario
document.getElementById('partenombre'+pos).value = cli;
document.getElementById('partedir'+pos).value = dir;
}
} else{
if(tipo===0){ //si es planificación
document.getElementById('planifcliente'+posicion).value = "";
document.getElementById('planifnombre'+posicion).value = "";
document.getElementById('planifdir'+posicion).value = "";
} else {
if(result.replace("\n","") === '0'){
alert("Est\u00e1 por cargar un nuevo cliente");
} else {
document.getElementById('partecliente'+posicion).value = "";
document.getElementById('partenombre'+posicion).value = "";
document.getElementById('partedir'+posicion).value = "";
}
}
}
}
},
error: function () {
alert("Error al buscar el cliente.");
}
});
}
function dac_Guardar_Planificacion(enviar){
"use strict";
//cantidad de planificaciones
var cantplanif = document.getElementsByName('planifcliente[]').length;
var fecha_planif = document.getElementById("fecha_planif").value;
//Declaro Objetos de planificados
var planifcliente_Obj = {};
var planifnombre_Obj = {};
var planifdir_Obj = {};
//según cant de registros
if (cantplanif !== 0){
if (cantplanif === 1){
planifcliente_Obj[0] = document.getElementById("planifcliente1").value;
planifnombre_Obj[0] = document.getElementById("planifnombre1").value;
planifdir_Obj[0] = document.getElementById("planifdir1").value;
} else {
var planifcliente = document.fm_planificacion.elements["planifcliente[]"];
var planifnombre = document.fm_planificacion.elements["planifnombre[]"];
var planifdir = document.fm_planificacion.elements["planifdir[]"];
for(var i = 0; i < cantplanif; i++){ //i in cantplanif
planifcliente_Obj[i] = planifcliente[i].value;
planifnombre_Obj[i] = planifnombre[i].value;
planifdir_Obj[i] = planifdir[i].value;
}
}
planifcliente_Obj = JSON.stringify(planifcliente_Obj);
planifnombre_Obj = JSON.stringify(planifnombre_Obj);
planifdir_Obj = JSON.stringify(planifdir_Obj);
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/planificacion/logica/ajax/update.planificacion.php',
data:{ cantplanif : cantplanif,
fecha_plan : fecha_planif,
planifcliente_Obj : planifcliente_Obj,
planifnombre_Obj : planifnombre_Obj,
planifdir_Obj : planifdir_Obj,
enviar : enviar
},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
$('#box_cargando').css({'display':'none'});
if (result){
var url;
if (result.replace("\n","") === '0'){
$('#box_cargando').css({'display':'none'});
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('La planificaci\u00f3n fue grabada.');
} else {
if(result.replace("\n","") === '1'){
$('#box_cargando').css({'display':'none'});
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html("La planificaci\u00f3n fue enviada.");
url = window.location.origin+'/pedidos/planificacion/index.php?fecha_planif=' + document.getElementById("fecha_planif").value;
document.location.href=url;
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
}
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error en el proceso de Envío de Planificaci\u00f3n.");
},
});
} else {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Deber cargar al menos un cliente.");
}
}
function dac_Guardar_Parte(enviar){
"use strict";
var cantparte = document.getElementsByName('partecliente[]').length; //cantidad de partes
var fecha_parte = document.getElementById("fecha_planif").value;
var cant_acciones = document.getElementsByName('parteaccion1[]').length; //cantidad de acciones
//--------------------------
//Declaro Objetos del Parte
var partecliente_Obj = {};
var partenombre_Obj = {};
var partedir_Obj = {};
var partetrabaja_Obj = {};
var parteobservacion_Obj= {};
var parteacciones_Obj = {};
var nroparte_Obj = {};
//--------------------------
//según cant de partes
var parteacciones;
var j;
if (cantparte === 1){
nroparte_Obj[0] = document.getElementById("partenro1").value;
partecliente_Obj[0] = document.getElementById("partecliente1").value;
partenombre_Obj[0] = document.getElementById("partenombre1").value;
partedir_Obj[0] = document.getElementById("partedir1").value;
partetrabaja_Obj[0] = document.getElementById("partetrabaja1").value;
parteobservacion_Obj[0] = document.getElementById("parteobservacion1").value;
//-------------------------------
//recorro acciones del parte 1
for(j=0;j<cant_acciones;j++){
parteacciones = document.fm_parte.elements['parteaccion1[]'];
//se consulta si los checks estan en true o false
if(parteacciones[j].checked){
if(typeof(parteacciones_Obj[0]) === "undefined"){
parteacciones_Obj[0] = parteacciones[j].value;
} else {
parteacciones_Obj[0] = parteacciones_Obj[0]+","+parteacciones[j].value;
}
}
}
} else {
var partecliente = document.fm_parte.elements["partecliente[]"];
var partenombre = document.fm_parte.elements["partenombre[]"];
var partedir = document.fm_parte.elements["partedir[]"];
var partetrabaja = document.fm_parte.elements["partetrabaja[]"];
var parteobservacion = document.fm_parte.elements["parteobservacion[]"];
//nros de id de cada parte para sacar el nombre de acciones
var nroparte = document.fm_parte.elements["partenro[]"];
for(var i=0; i<cantparte; i++){ //cantidad de partes cargados
partecliente_Obj[i] = partecliente[i].value;
partenombre_Obj[i] = partenombre[i].value;
partedir_Obj[i] = partedir[i].value;
partetrabaja_Obj[i] = partetrabaja[i].value;
parteobservacion_Obj[i] = parteobservacion[i].value;
nroparte_Obj[i] = nroparte[i].value; //nro identificador del parte
var title_ac = 'parteaccion'+(nroparte_Obj[i])+'[]';
parteacciones = document.fm_parte.elements[title_ac]; //Carga los valores de las aaciones de cada parte
//----------------------------
//recorre cada accion de cada parte para cargar cada parteacciones_Obj[i] con los id de las acciones checadas
for(j=0;j<cant_acciones;j++){
//se consulta si los checks estan en true o false y se le pasa el id para grabar los seleccionados: Ejemplo: 1,5,14...etc
if(parteacciones[j].checked){
if(typeof(parteacciones_Obj[i]) === "undefined"){
parteacciones_Obj[i] = parteacciones[j].value;
} else {
parteacciones_Obj[i] = parteacciones_Obj[i]+","+parteacciones[j].value;
}
}
}
}
}
nroparte_Obj = JSON.stringify(nroparte_Obj);
partecliente_Obj = JSON.stringify(partecliente_Obj);
partenombre_Obj = JSON.stringify(partenombre_Obj);
partedir_Obj = JSON.stringify(partedir_Obj);
partetrabaja_Obj = JSON.stringify(partetrabaja_Obj);
parteobservacion_Obj = JSON.stringify(parteobservacion_Obj);
parteacciones_Obj = JSON.stringify(parteacciones_Obj);
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/planificacion/logica/ajax/update.parte.php',
data:{ cantparte : cantparte,
fecha_plan : fecha_parte,
partecliente_Obj : partecliente_Obj,
partenombre_Obj : partenombre_Obj,
partedir_Obj : partedir_Obj,
partetrabaja_Obj : partetrabaja_Obj,
parteobservacion_Obj: parteobservacion_Obj,
parteacciones_Obj : parteacciones_Obj,
nroparte_Obj : nroparte_Obj,
enviar : enviar
},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
$('#box_cargando').css({'display':'none'});
if (result){
if (result.replace("\n","") === '0'){
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('El parte fue grabado.');
} else {
if(result.replace("\n","") === '1'){
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('El parte fue enviado.');
var url = window.location.origin+'/pedidos/planificacion/index.php?fecha_planif=' + document.getElementById("fecha_planif").value;
document.location.href=url;
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
}
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error en el proceso de Envío del Parte Diario.");
}
});
}
function dac_Duplicar_Planificacion(fecha_origen){
"use strict";
var fecha_destino = document.getElementById("fecha_destino").value;
if(confirm("Desea duplicar la planificaci\u00f3n del d\u00eda "+fecha_origen+" a la fecha "+fecha_destino+" ?")){
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/planificacion/logica/ajax/duplicar.planificacion.php',
data:{ fecha_origen : fecha_origen,
fecha_destino : fecha_destino
},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
$('#box_cargando').css({'display':'none'});
if (result){
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error en el duplicado de Planificaci\u00f3n.");
}
});
}
}
function dac_ExportarPlanifOPartesToExcel(fecha_inicio, fecha_final, tipo){
"use strict";
document.getElementById("tipo_exportado").value = tipo;
if(fecha_final === ""){
alert("Debe indicar la fecha final para descargar el parte diario.");
} else {
if(confirm("Desea exportar lo/el "+tipo+" del d\u00eda "+fecha_inicio+" a la fecha "+fecha_final+" ?")){
document.getElementById("export_partes_to_excel").submit();
}
}
}
<file_sep>/includes/class/class.articulodispone.php
<?php
require_once('class.PropertyObject.php');
class TArticuloDispone extends PropertyObject {
protected $_tablename = 'articulodispone';
protected $_fieldid = 'adid';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'adid';
$this->propertyTable['NombreGenerico'] = 'adnombregenerico';
//--------------------
$this->propertyTable['Via'] = 'advia'; //oral, intramuscular, intravenosa, subcutánea, inhalatoria, transdérmica, nasal, oftálmica, ótica, tópica, rectal, vaginal,
//presentacion
$this->propertyTable['Forma'] = 'adforma'; //gel, liquido, solido, shampoo
$this->propertyTable['Envase'] = 'adenvase'; //frasco, blister
$this->propertyTable['Unidades'] = 'adunidades'; //1 si es frasco
$this->propertyTable['Cantidad'] = 'adcantidad'; //20, 120
$this->propertyTable['UnidadMedida'] = 'adunidadmedida'; //g, mg, l, ml
//--------------------
$this->propertyTable['Accion'] = 'adaccion';
$this->propertyTable['Uso'] = 'aduso';
$this->propertyTable['NoUsar'] = 'adnousar';
$this->propertyTable['CuidadosPre'] = 'adcuidadospre';
$this->propertyTable['CuidadosPost'] = 'adcuidadospost';
$this->propertyTable['ComoUsar'] = 'adcomousar';
$this->propertyTable['Conservacion'] = 'adconservacion';
$this->propertyTable['FechaUltVersion'] = 'adfechaultversion';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/proveedores/lista.php
<?php
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/proveedores/' : $_REQUEST['backURL'];
$_LPP = 1000;
$_total = DataManager::getNumeroFilasTotales('TProveedor', 0);
$_paginas = ceil($_total/$_LPP);
$_pag = isset($_REQUEST['pag']) ? min(max(1,$_REQUEST['pag']),$_paginas) : 1;
$_GOFirst = sprintf("<a class=\"icon-go-first\" href=\"%s?pag=%d\"></a>", $backURL, 1);
$_GOPrev = sprintf("<a class=\"icon-go-previous\" href=\"%s?pag=%d\"></a>", $backURL, $_pag-1);
$_GONext = sprintf("<a class=\"icon-go-next\" href=\"%s?pag=%d\"></a>", $backURL, $_pag+1);
$_GOLast = sprintf("<a class=\"icon-go-last\" href=\"%s?pag=%d\"></a>", $backURL, $_paginas);
/*****************************************/
$_total = count(DataManager::getProveedores($_pag, $_LPP, 3, NULL));
$_paginas2 = ceil($_total/$_LPP);
$_pag2 = isset($_REQUEST['pag2']) ? min(max(1,$_REQUEST['pag2']),$_paginas2) : 1;
$_GOFirst2 = sprintf("<a class=\"icon-go-first\" href=\"%s?pag2=%d\"></a>", $backURL, 1);
$_GOPrev2 = sprintf("<a class=\"icon-go-previous\" href=\"%s?pag2=%d\"></a>", $backURL, $_pag2-1);
$_GONext2 = sprintf("<a class=\"icon-go-next\" href=\"%s?pag2=%d\"></a>", $backURL, $_pag2+1);
$_GOLast2 = sprintf("<a class=\"icon-go-last\" href=\"%s?pa2g=%d\"></a>", $backURL, $_paginas2);
$btnNuevo = sprintf( "<a href=\"editar.php\" title=\"Nuevo\"><img class=\"icon-new\"/></a>");
?>
<div class="box_down">
<div class="barra">
<div class="bloque_4">
<h1>Proveedores</h1>
</div>
<div class="bloque_7">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn" type="text" value="tblProveedores" hidden/>
</div>
<div class="bloque_9"> <?php
if ($_SESSION["_usrrol"]=="A"){
echo $btnNuevo;
} ?>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblProveedores">
<thead>
<tr>
<th scope="col" align="left">Emp</th>
<th scope="col" align="left" height="18">Código</th>
<th scope="col" align="left" >Nombre</th>
<th scope="col" align="left" >Localidad</th>
<th scope="col" align="center">Correo</th>
<th scope="col" align="center" >Teléfono</th>
<th scope="colgroup" colspan="2" align="center" width="15">Acciones</th>
</tr>
</thead>
<?php
$_proveedores = DataManager::getProveedores($_pag, $_LPP, NULL, NULL);
$_max = count($_proveedores); // la última página vendrá incompleta
for( $k=0; $k < $_LPP; $k++ ) {
if ($k < $_max) {
$_prov = $_proveedores[$k];
$_idempresa = $_prov['providempresa'];
$_providprov= $_prov['providprov'];
$_nombre = $_prov['provnombre'];
$_localidad = $_prov['providloc'];
$_correo = $_prov['provcorreo'];
$_telefono = $_prov['provtelefono'];
$_estado = $_prov['provactivo'];
$_status = ($_estado) ? "<a title=\"Desactivar\"><img class=\"icon-status-active\"/></a>" : "<a title=\"Activar\"><img class=\"icon-status-inactive\"/></a>";
$_editar = sprintf( "<a href=\"editar.php?provid=%d&backURL=%s&pag=%s\" title=\"Editar Proveedor\">%s</a>", $_prov['provid'], $_SERVER['PHP_SELF'], $_pag, "<img class=\"icon-edit\" />");
$_borrar = sprintf( "<a href=\"logica/changestatus.php?provid=%d&backURL=%s&pag=%s\" title=\"Borrar Proveedor\">%s</a>", $_prov['provid'], $_SERVER['PHP_SELF'], $_pag, $_status);
} else {
$_idempresa = " ";
$_providprov= " ";
$_nombre = " ";
$_localidad = " ";
$_correo = " ";
$_telefono = " ";
$_editar = " ";
$_borrar = " ";
}
if($_estado != 3){
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\" align=\"center\">%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_idempresa, $_providprov, $_nombre, $_localidad, $_correo, $_telefono, $_editar, $_borrar);
echo sprintf("</tr>");
}
} ?>
</table>
</div> <!-- Fin listar -->
<?php
if ( $_paginas > 1 ) {
$_First = ($_pag > 1) ? $_GOFirst : " ";
$_Prev = ($_pag > 1) ? $_GOPrev : " ";
$_Last = ($_pag < $_paginas) ? $_GOLast : " ";
$_Next = ($_pag < $_paginas) ? $_GONext : " ";
echo("<table class=\"paginador\"><tr>");
echo sprintf("<td height=\"16\">Mostrando página %d de %d</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td>", $_pag, $_paginas, $_First, $_Prev, $_Next, $_Last);
echo("</tr></table>");
} ?>
<hr>
<div class="barra">
<div class="bloque_5">
<h1>Solicitud de alta de Proveedores</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar2" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn2" type="text" value="tblProveedores2" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblProveedores2">
<thead>
<tr>
<th scope="col" align="left">Emp</th>
<th scope="col" align="left" height="18">Código</th>
<th scope="col" align="left" >Nombre</th>
<th scope="col" align="left" >Localidad</th>
<th scope="col" align="left" >CP</th>
<th scope="col" align="left" >CUIT</th>
<th scope="col" align="center">Correo</th>
<th scope="col" align="center" >Teléfono</th>
<th scope="colgroup" colspan="3" align="center" width="15">Acciones</th>
</tr>
</thead>
<?php
$_proveedores = DataManager::getProveedores($_pag2, $_LPP, NULL, 3);
$_max = count($_proveedores); // la última página vendrá incompleta
for( $k=0; $k < $_LPP; $k++ ) {
if ($k < $_max) {
$_prov = $_proveedores[$k];
$_idempresa = $_prov['providempresa'];
$_providprov= $_prov['providprov'];
$_nombre = $_prov['provnombre'];
$_localidad = $_prov['providloc'];
$_cp = $_prov['provcp'];
$_cuit = $_prov['provcuit'];
$_correo = $_prov['provcorreo'];
$_telefono = $_prov['provtelefono'];
$_editar = sprintf( "<a href=\"editar.php?provid=%d&backURL=%s&pag=%s\" title=\"Editar Proveedor\">%s</a>", $_prov['provid'], $_SERVER['PHP_SELF'], $_pag2, "<img class=\"icon-edit\"/>");
$_borrar = '';
if($_providprov != 0){
$_status = "<img class=\"icon-status-inactive\"/>";
$_borrar = sprintf( "<a href=\"logica/changestatus.php?provid=%d&backURL=%s&pag=%s\" title=\"Activar\">%s</a>", $_prov['provid'], $_SERVER['PHP_SELF'], $_pag2, $_status);
}
$_eliminar = sprintf ("<a href=\"logica/eliminar.proveedor.php?provid=%d&backURL=%s&pag=%s\" title=\"Eliminar Proveedor\" onclick=\"return confirm('¿Está Seguro que desea ELIMINAR EL PROVEEDOR?')\"> <img class=\"icon-delete\"/></a>", $_prov['provid'], $_SERVER['PHP_SELF'], $_pag2, "Eliminar");
} else {
$_idempresa = " ";
$_providprov= " ";
$_nombre = " ";
$_localidad = " ";
$_cp = " ";
$_cuit = " ";
$_correo = " ";
$_telefono = " ";
$_editar = " ";
$_borrar = " ";
$_eliminar = " ";
}
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\" align=\"center\">%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_idempresa, $_providprov, $_nombre, $_localidad, $_cp, $_cuit, $_correo, $_telefono, $_editar, $_borrar, $_eliminar);
echo sprintf("</tr>");
} ?>
</table>
</div> <!-- Fin listar -->
<?php
if ( $_paginas2 > 1 ) {
$_First2 = ($_pag2 > 1) ? $_GOFirst2 : " ";
$_Prev2 = ($_pag2 > 1) ? $_GOPrev2 : " ";
$_Last2 = ($_pag2 < $_paginas2) ? $_GOLast2 : " ";
$_Next2 = ($_pag2 < $_paginas2) ? $_GONext2 : " ";
echo("<table class=\"paginador\"><tr>");
echo sprintf("<td height=\"16\">Mostrando página %d de %d</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td>", $_pag2, $_paginas2, $_First2, $_Prev2, $_Next2, $_Last2);
echo("</tr></table>");
} ?>
</div>
<file_sep>/js/provincias/getCodigoPostal.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php");
/*Me traigo el codigo Localidad seleccionado, el codigo localidad es la referencia a cada Localidad de la BBDD*/
$idLocalidad = $_GET['idLocalidad'];
$datosJSON;
$_localidades = DataManager::getLocalidades();
if (count($_localidades)) {
foreach ($_localidades as $k => $_loc) {
if ($idLocalidad == $_loc["locidloc"]){
$datosJSON[] = $_loc["loccodpostal"];
}
}
}
/*una vez tenemos un array con los datos los mandamos por json a la web*/
header('Content-type: application/json');
echo json_encode($datosJSON);
?><file_sep>/soporte/motivos/lista.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
} ?>
<script type="text/javascript" language="JavaScript" src="/pedidos/soporte/motivos/logica/jquery/script.js"></script>
<div class="box_body">
<form id="fmMotivo" name="fmMotivo" method="post">
<fieldset>
<legend>Datos de Motivo</legend>
<div class="bloque_1" align="center">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<input type="text" id="motid" name="motid" hidden="hidden">
<div class="bloque_5">
<label for="sector">Sector</label>
<select id="sector" name="sector">
<option id="0" value="0" selected></option>
<?php
$sectores = DataManager::getTicketSector();
foreach( $sectores as $k => $sec ) {
$id = $sec['tksid'];
$titulo = $sec['tksnombre']; ?>
<option id="<?php echo $id; ?>" value="<?php echo $id; ?>"><?php echo $titulo; ?></option><?php
} ?>
</select>
</div>
<div class="bloque_5">
<?php $urlSend = '/pedidos/soporte/motivos/logica/update.motivo.php';?>
<a id="btnSend" title="Enviar">
<img class="icon-send" onclick="javascript:dac_sendForm(fmMotivo, '<?php echo $urlSend;?>');"/>
</a>
</div>
<div class="bloque_5">
<label for="responsable">Responsable</label>
<select id="responsable" name="responsable">
<option id="0" value="0" selected></option> <?php
$responsables = DataManager::getUsuarios( 0, 0, 1, NULL, '"A", "M", "G"');
if (count($responsables)) {
foreach ($responsables as $k => $resp) {
$idUsr = $resp["uid"];
$nombreUsr = $resp['unombre']; ?>
<option id="<?php echo $idUsr; ?>" value="<?php echo $idUsr; ?>"><?php echo $nombreUsr; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_5">
<label for="motivo">Motivo</label>
<input type="text" id="motivo" name="motivo">
</div>
</fieldset>
</form>
</div> <!-- Fin box body -->
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Motivos</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn" type="text" value="tblmotivos" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<div id='tablamotivos'></div>
</div> <!-- Fin lista -->
</div> <!-- Fin box_seccion -->
<hr><file_sep>/transfer/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
} ?>
<!doctype html>
<html xml:lang='es'>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php"; ?>
<script type="text/javascript" src="logica/jquery/jqueryHeader.js"></script>
<script language="JavaScript" type="text/javascript">
//**********************//
// Nuevo div Artículo //
var nextinput = 0;
function dac_CargarArticulo(idart, ean, nombre, precio){
document.getElementById("field_listart").style.display = 'block';
nextinput++;
var campo = '<div id="rut'+nextinput+'">';
campo += '<input id="ptidart'+nextinput+'" name="ptidart[]" type="text" value="'+idart+'" hidden/>';
campo += '<input id="ptnombreart'+nextinput+'" name="ptnombreart[]" type="text" value="'+nombre+'" hidden/>';
campo += '<input id="ptean'+nextinput+'" name="ptean[]" type="text" value="'+ean+'" hidden/>';
campo += '<input id="ptprecioart'+nextinput+'" name="ptprecioart[]" type="text" value="'+precio+'" hidden/>';
campo += '<div class="bloque_6"><strong> Artículo '+idart+'</strong></br>'+nombre+'</div>';
campo += '<div class="bloque_8"><strong> Cantidad </strong><input id="ptcant'+nextinput+'" name="ptcant[]" onblur="javascript:dac_CalcularSubtotalTransfer();" maxlength="5"/></div>';
campo += '<div class="bloque_8"><strong>% Desc </strong> <input id="ptdesc'+nextinput+'" name="ptdesc[]" onkeydown="ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);" onkeyup="ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);" onblur="javascript:dac_CalcularSubtotalTransfer();" maxlength="5"/></div>';
var plazos = '';
<?php
$plazos = DataManager::getCondicionesDePagoTransfer(0, 0, 1);
if (count($plazos)) {
foreach ($plazos as $j => $plazo) {
$plazo = $plazos[$j];
$plazoId = $plazo["condid"];
$plazoNombre = $plazo["condnombre"];
if ($plazoId == 1) { ?>
plazos += '<option value="<?php echo $plazoId; ?>" selected><?php echo $plazoNombre; ?></option>';
<?php
} else { ?>
plazos += '<option value="<?php echo $plazoId; ?>"><?php echo $plazoNombre; ?></option>';
<?php
}
}
} ?>
campo += '<div class="bloque_7"><strong>Condición</strong><select id="ptcondpago" name="ptcondpago[]">'+plazos+'</select></div>';
campo += '<div class="bloque_9"></br><input id="btmenos" class="btmenos" type="button" value="-" onClick="EliminarArt('+nextinput+')"></div>';
campo += '<hr>'
campo += '</div>';
$("#lista_articulos2").append(campo);
dac_CargarDescAbm(nextinput);
}
// Quitar div de artículo
function EliminarArt(id){
elemento=document.getElementById('rut'+id);
elemento.parentNode.removeChild(elemento);
dac_CalcularSubtotalTransfer();
}
</script>
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "pedidos";
$_subsection= "nuevo_transfer";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<div class="box_body">
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<form id="fmPedidoTransfer" name="fmPedidoTransfer" method="post">
<input id="tblTransfer" name="tblTransfer" type="text" value="0" hidden/>
<fieldset>
<legend>Pedido Transfer</legend>
<div class="bloque_5">
<label for="ptParaIdUsr">Asignado a</label>
<select id="ptParaIdUsr" name="ptParaIdUsr" >
<option id="0" value="0" selected></option> <?php
$vendedores = DataManager::getUsuarios( 0, 0, 1, NULL, '"V"');
if (count($vendedores)) {
foreach ($vendedores as $k => $vend) {
$idVend = $vend["uid"];
$nombreVend = $vend['unombre'];
if ($idVend == $_SESSION["_usrid"]){ ?>
<option id="<?php echo $idVend; ?>" value="<?php echo $idVend; ?>" selected><?php echo $nombreVend; ?></option><?php
} else { ?>
<option id="<?php echo $idVend; ?>" value="<?php echo $idVend; ?>"><?php echo $nombreVend; ?></option><?php
}
}
} ?>
</select>
</div>
<div class="bloque_7">
<label for="contacto">Contacto</label>
<input name="contacto" type="text" maxlength="50"/>
</div>
<div class="bloque_7" align="right">
<?php $urlSend = '/pedidos/transfer/logica/update.pedido.php';?>
<?php $urlBack = '/pedidos/transfer/';?>
<a id="btnSend" title="Enviar">
<br>
<img class="icon-send" onclick="javascript:dac_sendForm(fmPedidoTransfer, '<?php echo $urlSend;?>', '<?php echo $urlBack;?>');"/>
</a>
</div>
</fieldset>
<fieldset>
<legend>Cuenta</legend>
<div id="detalle_cuenta"></div>
</fieldset>
<fieldset id="field_listart" style="display:none;">
<legend>Artículos</legend>
<div id="lista_articulos2"></div>
<div class="bloque_1">
<div id="ptsubtotal" style="display:none;"></div>
</div>
</fieldset>
</form>
</div> <!-- END box_body -->
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Cuentas</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn" type="text" value="tblCuentasTransfer" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<table id="tblCuentasTransfer">
<thead>
<tr align="left">
<th>Emp</th>
<th>Id</th>
<th>Nombre</th>
</tr>
</thead>
<tbody> <?php
if (!empty($_SESSION["_usrzonas"])) {
$cuentas = DataManager::getCuentas(0, 0, 1, NULL, '"C","CT","T","TT"', $_SESSION["_usrzonas"]);
if (count($cuentas)) {
$claseFila = 0;
foreach ($cuentas as $k => $cta) {
$ctaId = $cta["ctaid"];
$ctaIdCuenta = $cta["ctaidcuenta"];
$ctaIdEmpresa = $cta["ctaidempresa"];
$ctaNombre = $cta["ctanombre"];
$ctaTipo = $cta["ctatipo"];
$ctaActiva = $cta["ctaactiva"];
if($ctaIdCuenta != 0){
//deberá mostrar tódos los transfers menos transfers inactivos.
if(($ctaTipo == 'T' || $ctaTipo == 'TT') && $ctaActiva == 0){/*no mostrar*/} else {
$cuentasRelacionadas = DataManager::getCuentasRelacionadas($ctaId);
if (count($cuentasRelacionadas)) {
((($claseFila % 2) == 0)? $clase="par" : $clase="impar");
$claseFila ++; ?>
<tr class="<?php echo $clase;?>" onclick="javascript:dac_mostrarCuentasRelacionada('<?php echo $ctaId;?>')">
<td><?php echo $ctaIdEmpresa;?></td>
<td><?php echo $ctaIdCuenta;?></td>
<td><?php echo $ctaNombre;?></td>
</tr>
<tr>
<td colspan="3">
<table id="<?php echo $ctaId;?>" class="table-transfer">
<tbody>
<tr align="center">
<th hidden="hidden">ID</th>
<th hidden="hidden">Nombre</th>
<th width="30%">Cliente</th>
<th width="30%">Droguería</th>
<th width="40%">Nombre</th>
</tr> <?php
foreach ($cuentasRelacionadas as $j => $ctaRel) {
((($j % 2) == 0)? $clase2="par" : $clase2="impar");
$ctaRelDrogId = $ctaRel["ctarelidcuentadrog"];
$ctRelIdCuenta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $ctaRelDrogId);
$ctRelNombre = DataManager::getCuenta('ctanombre', 'ctaid', $ctaRelDrogId);
$ctaRelNroCliente = $ctaRel["ctarelnroclientetransfer"];
$ctRelEmpresa = DataManager::getCuenta('ctaidempresa', 'ctaid', $ctaRelDrogId);
?>
<tr class="<?php echo $clase2;?>" onclick="javascript:dac_cargarCuentaTransferRelacionada('<?php echo $ctaId;?>', '<?php echo $ctaRelDrogId;?>', '<?php echo $ctRelIdCuenta;?>', '<?php echo $ctRelNombre;?>', '<?php echo $ctaRelNroCliente;?>', '<?php echo $ctRelEmpresa;?>')">
<td hidden="hidden"><?php echo $ctaIdCuenta;?></td>
<td hidden="hidden"><?php echo $ctaNombre;?></td>
<td style="border:2px solid #117db6;"><?php echo $ctaRelNroCliente;?></td>
<td style="border:2px solid #117db6;"><?php echo $ctRelIdCuenta;?></td>
<td style="border:2px solid #117db6;"><?php echo $ctRelNombre;?></td>
</tr> <?php
}?>
</tbody>
</table>
</td>
</tr><?php
}
}
}
}
} else { ?>
<tr>
<td colspan="3"><?php echo "No hay cuentas activas."; ?></td>
</tr> <?php
}
} else { ?>
<tr>
<td colspan="3"><?php echo "Usuario sin zonas habilitadas."; ?></td>
</tr> <?php
} ?>
</tbody>
</table>
</div> <!-- Fin listar -->
<div class="barra">
<div class="bloque_5">
<h1>Artículo</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar2" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn2" type="text" value="tblTablaArt" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<div id='tablaarticulos'></div>
</div> <!-- Fin listar -->
</div> <!-- FIN box_seccion -->
<hr>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html>
<file_sep>/soporte/motivos/logica/ajax/getMotivos.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$idSector = empty($_POST['sector']) ? 0 : $_POST['sector'];
$motivos = DataManager::getTicketMotivos();
if (count($motivos)) {
echo '<table id="tblMotivos">';
echo '<thead><tr><th>Motivo</th><th>Responsable</th></tr></thead>';
echo '<tbody>';
foreach ($motivos as $k => $mot) {
$id = $mot['tkmotid'];
$sector = $mot['tkmotidsector'];
$motivo = $mot['tkmotmotivo'];
$usrResponsable = $mot['tkmotusrresponsable'];
$responsable = DataManager::getUsuario('unombre', $usrResponsable);
if($idSector){
if($idSector == $sector){
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr id=motivo".$id." class=".$clase." style=\"cursor:pointer;\" onclick=\"javascript:dac_changeMotivo('$id', '$motivo', '$usrResponsable')\">";
echo "<td>".$motivo."</td><td>".$responsable."</td>";
echo "</tr>";
}
}
}
echo "</tbody></table>";
} else {
echo '<table><thead><tr><th align="center">No hay registros activos.</th></tr></thead></table>'; exit;
}
?><file_sep>/planificacion/logica/ajax/buscar.cliente.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//*************************************************
$_idcliente = (isset($_POST['idcliente']))? $_POST['idcliente'] : NULL;
$_posicion = (isset($_POST['posicion'])) ? $_POST['posicion'] : NULL;
$_tipo = (isset($_POST['tipo'])) ? $_POST['tipo'] : NULL;
//*************************************************
//Controlo campo
//*************************************************
if ($_tipo == 0){ //si es planif //se pidió en la semana anterior al 06-03-2015 y se pide que se quite la semana del 08-05-15
if (!is_numeric($_idcliente)){
echo "El Código de cliente debe ser numérico."; exit;
}
} else {//si es parte diario
if ($_idcliente == "0" || $_idcliente == ""){ //en caso de cliente nuevo con entrada CERO
echo 0; exit;
//echo "Está cargando un cliente nuevo"; exit;
} else {
if (!is_numeric($_idcliente)){
//echo 1; exit;
echo "El Código de cliente debe ser numérico. En caso de ser un cliente nuevo. Debe colocarse el nro de cliente 0 (cero)";
exit;
}
}
}
//*********************************
// Control de Existencia de Cuenta
//*********************************
$ctaIdCta = DataManager::getCuenta('ctaid', 'ctaidcuenta', $_idcliente, 1);
if($ctaIdCta) {
$_nombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $_idcliente, 1);
$_direccion = DataManager::getCuenta('ctadireccion', 'ctaidcuenta', $_idcliente, 1)." ".DataManager::getCuenta('ctadirnro', 'ctaidcuenta', $_idcliente, 1);
echo "1/$_posicion/$_nombre/$_direccion"; exit;
} else {
echo "La cuenta no se encuentra."; exit;
}
?><file_sep>/usuarios/logica/changestatus.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$_uid = empty($_REQUEST['uid']) ? 0 : $_REQUEST['uid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/usuarios/': $_REQUEST['backURL'];
if ($_uid) {
$_usrobject = DataManager::newObjectOfClass('TUsuario', $_uid);
$_status = ($_usrobject->__get('Activo')) ? 0 : 1;
$_usrobject->__set('Activo', $_status);
$ID = DataManager::updateSimpleObject($_usrobject);
}
header('Location: '.$backURL.'?pag='.$_pag);
?><file_sep>/login/cambiar.browser.php
<?php require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/detect.Browser.php"); ?>
<!DOCTYPE html >
<html lang='es'>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php"; ?>
</head>
<body>
<main class="cuerpo">
<div id="logoneo" align="center">
<img src="/pedidos/images/logo/LogoNeo.png"/>
</div><!-- logo Neofarma -->
<div align="center">
</br>
<a id="chrome" href="https://www.google.com/intl/es-419/chrome/browser/desktop/index.html" title="Chrome">
<img id="icon-chrome" src="https://www.google.com/chrome/assets/common/images/chrome_logo_2x.png?mmfb=a5234ae3c4265f687c7fffae2760a907" style="border:none;"/>
</a>
</br></br></br></br>
<?php echo "La Web NO FUNCIONA EN ÉSTE EXPLORADOR.</br> Se recomienda utilizar Chrome."; ?>
</div>
</main> <!-- fin cuerpo -->
</body>
</html><file_sep>/transfer/logica/update.pedido.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$pId = 0;
$usrAsignado = (isset($_POST['ptParaIdUsr'])) ? $_POST['ptParaIdUsr'] : NULL;
$idCuenta = (isset($_POST['tblTransfer'])) ? $_POST['tblTransfer'] : NULL; //ctaid de tabla cuenta
$nombreCuenta = DataManager::getCuenta('ctanombre', 'ctaid', $idCuenta);
$cuit = DataManager::getCuenta('ctacuit', 'ctaid', $idCuenta);
$direccion = DataManager::getCuenta('ctadireccion', 'ctaid', $idCuenta);
$nro = DataManager::getCuenta('ctadirnro', 'ctaid', $idCuenta);
$piso = DataManager::getCuenta('ctadirpiso', 'ctaid', $idCuenta);
$dpto = DataManager::getCuenta('ctadirdpto', 'ctaid', $idCuenta);
$domicilio = $direccion." ".$nro." ".$piso." ".$dpto;
$contacto = (isset($_POST['contacto'])) ? $_POST['contacto'] : NULL;
$idDrogueria = (isset($_POST['cuentaId'])) ? $_POST['cuentaId'] : NULL; //ctarelidcuenta de tabla cuenta_relacionada
$nroClienteDrog = (isset($_POST['cuentaIdTransfer'])) ? $_POST['cuentaIdTransfer'] : NULL; //número de lciente transfer para la droguería
$condPago= (isset($_POST['ptcondpago'])) ? $_POST['ptcondpago'] : NULL;
$idArt = (isset($_POST['ptidart'])) ? $_POST['ptidart'] : NULL;
$precio = (isset($_POST['ptprecioart'])) ? $_POST['ptprecioart'] : NULL;
$cant = (isset($_POST['ptcant'])) ? $_POST['ptcant'] : NULL;
$desc = (isset($_POST['ptdesc'])) ? $_POST['ptdesc'] : NULL;
//----------------------//
// Controlo campos //
if(empty($usrAsignado)){
echo "Debe indicar usuario asignado."; exit;
}
if(count($idDrogueria) != 1){
echo "El pedido debe tener una cuenta transfer."; exit;
} else {
$idDrogueria = DataManager::getCuenta('ctaidcuenta', 'ctaid', $idDrogueria[0]);
$nroClienteDrog = $nroClienteDrog[0];
}
if (count($idArt) < 1){
echo "Debe cargar al menos un artículo."; exit;
}
for($i = 0; $i < count($idArt); $i++){
//Controla artículos repetidos
for($j = 0; $j < count($idArt); $j++){
if ($i != $j){
if ($idArt[$i] == $idArt[$j]){
echo "El artículo ".$idArt[$i]." está repetido."; exit;
}
}
}
if (empty($cant[$i]) || !is_numeric($cant[$i]) || $cant[$i] < 1){
echo "Debe cargar una cantidad para el artículo ".$idArt[$i]; exit;
}
//CONTROL de DESCUENTO
if ($desc[$i] < 0 || $desc[$i] == "" || !is_numeric($desc[$i])){
echo "Debe cargar el porcentaje de descuento para el artículo ".$idArt[$i]; exit;
}
//CONTROL ABM
$abms = DataManager::getDetalleAbm(date("m"), date("Y"), $idDrogueria, 'TL');
if ($abms) {
foreach ($abms as $k => $abm){
$abmArtId = $abm['abmartid'];
$abmDesc = $abm['abmdesc'];
$abmCondPago= $abm['abmcondpago'];
//Si descuento <= que el desc del ABM ACTUAL
if ($abmArtId == $idArt[$i]) { //&& $abmDrog == $idDrogueria
//Descuento ABM debe ser >= que del artículo.
if ($abmDesc < $desc[$i]) {
echo "El descuento del artículo ".$abmArtId." supera el porcentaje pactado actualmente."; exit;
}
//Controla Condición de pago
$abmDias = 0;
$abmCondPagoDias = DataManager::getCondicionDePagoTransfer('conddias', 'condid', $abmCondPago);
if ($abmCondPagoDias) {
//Saca los días máximos de cond de pago del Artículo.
$abmDias = max(explode(',', str_replace(' ', '', trim($abmCondPagoDias))));
}
$condPagoDiasPedido = 0;
$condicionesPagoDiasPedido = DataManager::getCondicionDePagoTransfer('conddias', 'condid', $condPago[$i]);
if ($condicionesPagoDiasPedido) {
//saca días el maximo de días del array (30, 60, 90...)
$condPagoDiasPedido = max(explode(',', str_replace(' ', '', trim($condicionesPagoDiasPedido))));
}
if($condPagoDiasPedido > $abmDias) {
echo "$condPagoDiasPedido > $abmDias - $abmArtId - "; exit;
echo "La condición de pago del pedido transfer para el artículo ".$abmArtId.", no cumple las condiciones de plazo de la droguería"; exit;
}
//Si el pedido es a X cantidad de días, el ABM debe tener opciones iguales o mayores a dicha cantdidad
}
}
} else {
echo "No hay condiciones ABM cargadas para la droguería ".$idDrogueria."."; exit;
}
}
if (($idDrogueria != 220061 && $idDrogueria != 220181) && !is_numeric($nroClienteDrog)){
echo "El código de cliente de la droguería es incorrecto."; exit;
}
//******************************//
// UPDATE DEL PEDIDO TRANSFER //
//Consulta Nro Pedido para Crear el nuevo.
$nroPedido = DataManager::dacLastId('pedidos_transfer', 'ptidpedido');
for($i = 0; $i < count($idArt); $i++){
$ptObject = ($pId) ? DataManager::newObjectOfClass('TPedidostransfer', $pId) : DataManager::newObjectOfClass('TPedidostransfer');
$ptObject->__set('IDPedido' , $nroPedido);
$ptObject->__set('IDVendedor' , $_SESSION["_usrid"]);
$ptObject->__set('ParaIdUsr' , $usrAsignado); //NO LLEGA
$ptObject->__set('IDDrogueria' , $idDrogueria);
$ptObject->__set('ClienteDrogueria' , $nroClienteDrog);
$ptObject->__set('ClienteNeo' , $idCuenta);
$ptObject->__set('RS' , $nombreCuenta); //sanear_string
$ptObject->__set('Cuit' , $cuit);
$ptObject->__set('Domicilio' , $domicilio); //sanear_string
$ptObject->__set('Contacto' , $contacto); //sanear_string
$ptObject->__set('Articulo' , $idArt[$i]);
$ptObject->__set('Precio' , $precio[$i]);
$ptObject->__set('Unidades' , $cant[$i]);
$ptObject->__set('Descuento' , $desc[$i]);
$ptObject->__set('CondicionPago' , $condPago[$i]);
$ptObject->__set('FechaPedido' , date('Y-m-d H:i:s'));
$ptObject->__set('Activo' , '1');
$ptObject->__set('IDAdmin' , '0');
$ptObject->__set('IDNombreAdmin' , '');
$ptObject->__set('FechaExportado' , date('2001-01-01'));
$ptObject->__set('Liquidado' , '0');
if ($pId) {
echo "Error. PID.";
} else {
$ptObject->__set('ID' , $ptObject->__newID());
$ID = DataManager::insertSimpleObject($ptObject);
}
}
echo "1";
?><file_sep>/planificacion/logica/exportar.parte.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_tipo_exp = (isset($_POST['tipo_exportado'])) ? $_POST['tipo_exportado'] : NULL;
$_fecha_final = (isset($_POST['fecha_destino'])) ? $_POST['fecha_destino'] : NULL;
$_fecha_inicio = (isset($_POST['fecha_planificado']))? $_POST['fecha_planificado'] : NULL;
$titulo = ($_tipo_exp == "parte") ? "parte" : "Planificaciones";
//*----------------------
//Duplicado de registros
//*----------------------
$_fecha_i = dac_invertirFecha( $_fecha_inicio );
$_fecha_f = dac_invertirFecha( $_fecha_final );
//---------------------------------
// Exportar datos de php a Excel
//---------------------------------
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
switch($_tipo_exp) {
case 'parte':
header("content-disposition: attachment;filename=Parte-diario_$_fecha_inicio-al-$_fecha_final.xls");
break;
case 'planificado':
header("content-disposition: attachment;filename=Planificaciones_$_fecha_inicio-al-$_fecha_final.xls");
break;
case 'reporte':
header("content-disposition: attachment;filename=Reporte_Partes_$_fecha_inicio-al-$_fecha_final.xls");
break;
default:
header("content-disposition: attachment;filename=Error_$_fecha_inicio-al-$_fecha_final.xls");
break;
} ?>
<HTML LANG="es"><TITLE>::. Exportacion de Datos .::</TITLE>
<meta charset="UTF-8">
<body>
<table border=1 align="center" cellpadding=1 cellspacing=1>
<?php
switch($_tipo_exp) {
case 'parte': ?>
<tr><td colspan="11" align="center" style="font-weight:bold; border:none;"> Detalle <?php echo $titulo; ?> </td></tr>
<tr><td colspan="11" style="font-weight:bold; border:none;"> DESDE: <?php echo $_fecha_inicio; ?></td></tr>
<tr><td colspan="11" style="font-weight:bold; border:none;"> HASTA: <?php echo $_fecha_final; ?></td></tr>
<tr>
<td>Fecha</td><td>Id</td><td>Nombre</td><td>Cliente</td><td>Nombre</td><td>Domicilio</td><td>Localidad</td><td>Acción</td><td>Trabajó con...</td><td>Observación</td><td>EnvÍo <?php echo $titulo; ?></td>
</tr>
<?php
$_detalle_partes = DataManager::getDetalleParteExportar($_fecha_i, $_fecha_f);
if (count($_detalle_partes)){
foreach ($_detalle_partes as $k => $_partes) {
$_partes = $_detalle_partes[$k];
$_partefecha = $_partes["partefecha"];
$_parteidvend = $_partes["parteidvendedor"];
$_partenombrevend = DataManager::getUsuario('unombre', $_partes["parteidvendedor"]);
$_partecliente = $_partes["parteidcliente"];
$_partenombre = $_partes["parteclinombre"];
$_partedir = $_partes["parteclidireccion"];
$_parteloc = DataManager::getCuenta('ctalocalidad', 'ctaidcuenta', $_partecliente, 1);
$_partetrabajo = $_partes["partetrabajocon"];
$_parteobs = $_partes["parteobservacion"];
$_parteenvioparte = $_partes["partefechaenvio"];
$_fecha_envio = ($_parteenvioparte == "0000-00-00 00:00:00" || $_parteenvioparte == "2001-01-01 00:00:00" || $_parteenvioparte == "1900-01-01 00:00:00") ? 'SIN ENVIAR' : $_parteenvioparte;
$_idcliente = ($_partecliente) ? $_partecliente : 'NUEVO';
$_parteacciones = "";
if (!empty($_partes["parteaccion"])){
$_accion = explode(',', $_partes["parteaccion"]);
for($j=0; $j < count($_accion); $j++){
$_partes_ac = DataManager::getAccion($_accion[$j]);
if($_partes_ac){
$_parteacciones = $_partes_ac[0]["acnombre"]; ?>
<tr>
<td><?php echo $_partefecha;?></td>
<td align="center"><?php echo $_parteidvend; ?></td>
<td><?php echo $_partenombrevend;?></td>
<td><?php echo $_idcliente ?></td>
<td><?php echo $_partenombre; ?></td>
<td><?php echo $_partedir; ?></td>
<td><?php echo $_parteloc; ?></td>
<td><?php echo $_parteacciones; ?></td>
<td><?php echo $_partetrabajo; ?></td>
<td><?php echo $_parteobs; ?></td>
<td><?php echo $_fecha_envio; ?></td>
</tr> <?php
}
}
} else { ?>
<tr>
<td><?php echo $_partefecha;?></td>
<td align="center"><?php echo $_parteidvend; ?></td>
<td><?php echo $_partenombrevend;?></td>
<td><?php echo $_idcliente ?></td>
<td><?php echo $_partenombre; ?></td>
<td><?php echo $_partedir; ?></td>
<td><?php echo $_parteloc; ?></td>
<td><?php echo $_parteacciones; ?></td>
<td><?php echo $_partetrabajo; ?></td>
<td><?php echo $_parteobs; ?></td>
<td><?php echo $_fecha_envio; ?></td>
</tr> <?php
}
}
}
break;
case 'planificado': ?>
<tr><td colspan="11" align="center" style="font-weight:bold; border:none;"> Detalle <?php echo $titulo; ?> </td></tr>
<tr><td colspan="11" style="font-weight:bold; border:none;"> DESDE: <?php echo $_fecha_inicio; ?></td></tr>
<tr><td colspan="11" style="font-weight:bold; border:none;"> HASTA: <?php echo $_fecha_final; ?></td></tr>
<tr>
<td>Fecha</td><td>Id</td><td>Nombre</td><td>Cliente</td><td>Nombre</td><td>Domicilio</td><td>Localidad</td><td>Acción</td><td>Trabajó con...</td><td>Observación</td><td>EnvÍo <?php echo $titulo; ?></td>
</tr>
<?php
$_detalle_planif = DataManager::getDetallePlanifExportar($_fecha_i, $_fecha_f);
if (count($_detalle_planif)){
foreach ($_detalle_planif as $k => $_planificados){
$_planificados = $_detalle_planif[$k];
$_planiffecha = $_planificados["planiffecha"];
$_planifidvend = $_planificados["planifidvendedor"];
$_planifnombrevend = DataManager::getUsuario('unombre', $_planificados["planifidvendedor"]);
$_planifcliente = $_planificados["planifidcliente"];
$_planifnombre = $_planificados["planifclinombre"];
$_planifdir = $_planificados["planifclidireccion"];
//FALTA HACERLO APTO PARA CONSULTAR SEGÚN DIFERENTE EMPRESA, sino el nombre del cliente no será del todo correcto ???
$_planifloc = DataManager::getCuenta('ctalocalidad', 'ctaidcuenta', $_planifcliente, 1);
$_planifenvioplanif = $_planificados["planiffechaenvio"];
$_fecha_envio = ($_planifenvioplanif == "0000-00-00 00:00:00" || $_planifenvioplanif == "2001-01-01 00:00:00" || $_planifenvioplanif == "1900-01-01 00:00:00") ? 'SIN ENVIAR' : $_planifenvioplanif;
?>
<tr>
<td><?php echo $_planiffecha;?></td>
<td align="center"><?php echo $_planifidvend; ?></td>
<td><?php echo $_planifnombrevend;?></td>
<td><?php echo $_planifcliente ?></td>
<td><?php echo $_planifnombre; ?></td>
<td><?php echo $_planifdir; ?></td>
<td><?php echo $_planifloc; ?></td>
<td></td>
<td></td>
<td></td>
<td><?php echo $_fecha_envio; ?></td>
</tr>
<?php
}
}
break;
case 'reporte': ?>
<tr>
<td>Fecha</td><td>Id</td><td>Nombre</td><td>Planificado</td><td>VCD</td><td>Sin Novedad</td><td>No realizado</td><td>Otros</td><td>Visitas</td>
</tr>
<?php
$_partecontPanificado = 0;
$_partecontVisita = 0;
$_partecont_VCD = 0; //Ventas, Cobranzas y/o Devolución
$_partecont_Otros = 0;
$_partecont_SN = 0;
$_partecont_NR = 0;
$_parteclienteAntes = 0;
$_detalle_partes = DataManager::getDetalleParteExportar($_fecha_i, $_fecha_f);
if (count($_detalle_partes)){
foreach ($_detalle_partes as $k => $_partes){
$_partefecha = $_partes["partefecha"];
$_parteidvend = $_partes["parteidvendedor"];
$_partenombrevend = DataManager::getUsuario('unombre', $_partes["parteidvendedor"]);
$_partecliente = $_partes["parteidcliente"];
if($_partecliente != $_parteclienteAntes){
$_partecontPanificado += 1;
$_parteclienteAntes = $_partecliente;
}
$_parteacciones = "";
if (!empty($_partes["parteaccion"])){
$_accion = explode(',', $_partes["parteaccion"]);
for($j=0; $j < count($_accion); $j++){
$_partes_ac = DataManager::getAccion($_accion[$j]);
if($_partes_ac){
$_parteacciones = $_partes_ac[0]["acnombre"];
switch($_parteacciones){
//Ventas, cobranzas y Devoluciones
case 'Venta':
case 'Cobranza':
case 'Devolución':
$_partecont_VCD += 1;
break;
//Sin Novedad
case 'Sin Novedades':
$_partecont_SN += 1;
break;
//No realizado
case 'No Realizada':
$_partecont_NR += 1;
break;
//OTROS Casos
case 'POP':
case 'Reemplazo':
case 'Adhesión Club':
case 'Troquel Club':
case 'Premios Club':
$_partecont_Otros += 1;
break;
}
}
}
}
if(($k+1) < count($_detalle_partes)){
$_partes_sig = $_detalle_partes[$k+1];
$_parteidvend_sig = $_partes_sig["parteidvendedor"];
if($_parteidvend != $_parteidvend_sig){
$_parteidvendante = $_parteidvend;
$visitas = $_partecont_VCD - $_partecont_SN - $_partecont_NR - $_partecont_Otros;
$_partecontVisitas = ($visitas == 0) ? 0 : $_partecontPanificado - $_partecont_NR;
?>
<tr>
<td><?php echo $_partefecha;?></td>
<td align="center"><?php echo $_parteidvend; ?></td>
<td><?php echo $_partenombrevend;?></td>
<td><?php echo $_partecontPanificado; ?></td>
<td><?php echo $_partecont_VCD; ?></td>
<td><?php echo $_partecont_SN; ?></td>
<td><?php echo $_partecont_NR; ?></td>
<td><?php echo $_partecont_Otros; ?></td>
<td><?php echo $_partecontVisitas; ?></td>
</tr> <?php
$_partecontPanificado= 0;
$_partecontVisita = 0;
$_partecont_VCD = 0; //Ventas, Cobranzas y/o Devolución
$_partecont_Otros = 0;
$_partecont_SN = 0;
$_partecont_NR = 0;
}
}
}
}
break;
default: ?>
<tr><td colspan="8" align="center" style="font-weight:bold; border:none;"> Detalle <?php echo $titulo; ?> </td></tr>
<tr><td colspan="8" style="font-weight:bold; border:none;"> DESDE: <?php echo $_fecha_inicio; ?></td></tr>
<tr><td colspan="8" style="font-weight:bold; border:none;"> HASTA: <?php echo $_fecha_final; ?></td></tr>
<tr>
<td colspan="8">Ocurrió un ERROR al intentar exportar. Vuelva a intentarlo</td>
</tr> <?php
break;
} ?>
</table>
</body>
</html><file_sep>/localidades/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$idLoc = empty($_REQUEST['idLoc']) ? 0 : $_REQUEST['idLoc'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/localidades/' : $_REQUEST['backURL'];
if ($idLoc) {
$localObject = DataManager::newObjectOfClass('TLocalidad', $idLoc);
$provincia = $localObject->__get('IDProvincia');
$localidad = $localObject->__get('Localidad');
$cp = $localObject->__get('CP');
$zonaVenta = $localObject->__get('ZonaVenta');
$zonaEntrega = $localObject->__get('ZonaEntrega');
} else {
$provincia = '';
$localidad = '';
$cp = '';
$zonaVenta = '';
$zonaEntrega = '';
} ?>
<!doctype html>
<html lang='es'>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
<script type="text/javascript" src="/pedidos/js/provincias/selectProvincia.js"></script>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
<script language="JavaScript" src="/pedidos/localidades/logica/jquery/jqueryUsr.js" type="text/javascript"></script>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = 'localidades';
$_subsection = 'editar_localidades';
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<div class="box_body">
<form name="fmLocalidadesEdit" method="post" enctype="multipart/form-data">
<input type="text" id="idLoc" name="idLoc" value="<?php echo $idLoc;?>" hidden="hidden">
<fieldset>
<legend>Localidad</legend>
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
<fieldset id='box_observacion' class="msg_alerta" style="display: block">
<div id="msg_atencion"> IMPORTANTE. Si agrega una nueva localidad asegúrese de que la misma no exista con el mismo nombre o uno similar. Evite generar duplicados.</div>
</fieldset>
</div>
<div class="bloque_6">
<label for="provincia">Provincia</label>
<select id="provincia" name="provincia" <?php echo $disabled; ?> >
<option value="0" selected> Provincia... </option> <?php
$provincias = DataManager::getProvincias();
if (count($provincias)) {
foreach ($provincias as $k => $prov) {
$selected = ($provincia == $prov["provid"]) ? "selected" : "";
if($idLoc) {
if($selected) { ?>
<option id="<?php echo $prov["provid"]; ?>" value="<?php echo $prov["provid"]; ?>" <?php echo $selected; ?> ><?php echo $prov["provnombre"]; ?></option><?php
}
} else { ?>
<option id="<?php echo $prov["provid"]; ?>" value="<?php echo $prov["provid"]; ?>" <?php echo $selected; ?> ><?php echo $prov["provnombre"]; ?></option><?php
}
}
} ?>
</select>
</div>
<div class="bloque_6">
<label for="localidad">Localidad</label>
<input id="localidad" name="localidad" value="<?php echo $localidad;?>">
</div>
<div class="bloque_7">
<label for="codigopostal">Código Postal</label>
<input type="text" name="codigopostal" maxlength="10" value="<?php echo $cp;?>">
</div>
<div class="bloque_6">
<label for="zonaVSelect" >Zona Vendedor</label>
<select name="zonaVSelect">
<option value="" selected></option> <?php
$zonas = DataManager::getZonas();
if (count($zonas)) {
foreach ($zonas as $k => $zon) {
$zId = $zon["zid"];
$nroZona = $zon["zzona"];
$nombreZona = $zon["znombre"];
$zActivo = $zon["zactivo"];
if($zActivo){
$selected = ($nroZona == $zonaVenta) ? "selected" : "";
?>
<option id="<?php echo $nroZona; ?>" value="<?php echo $nroZona; ?>" <?php echo $selected;?> ><?php echo $nroZona." - ".$nombreZona; ?></option>
<?php
}
}
} ?>
</select>
</div>
<div class="bloque_6">
<label for="zonaDSelect">Zona Distribución</label>
<select name="zonaDSelect">
<option value="" selected></option> <?php
$zonasDistribucion = DataManager::getZonasDistribucion();
if (count($zonasDistribucion)) {
foreach ($zonasDistribucion as $k => $zonasD) {
$zonaDId = $zonasD["IdZona"];
$zonaDNombre= $zonasD["NombreZN"];
$selected = ($zonaDId == $zonaEntrega) ? "selected" : ""; ?>
<option id="<?php echo $zonaDId; ?>" value="<?php echo $zonaDId; ?>" <?php echo $selected;?> ><?php echo $zonaDId." - ".$zonaDNombre; ?></option>
<?php
}
} ?>
</select>
</div>
<div class="bloque_8">
<?php $urlSend = '/pedidos/localidades/logica/update.localidad.php';?>
<?php $urlBack = '/pedidos/localidades/';?>
<a id="btnSend" title="Enviar">
<br>
<img class="icon-send" onclick="javascript:dac_sendForm(fmLocalidadesEdit, '<?php echo $urlSend;?>', '<?php echo $urlBack;?>');"/>
</a>
</div>
</fieldset>
<fieldset>
<legend>Excepciones</legend>
<div id="excepciones"></div>
</fieldset>
</form>
</div> <!-- END box_body -->
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Cuentas</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn" type="text" value="tblTablaCta" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<div id='tablacuenta'></div> <?php
$zonasExpecion = DataManager::getZonasExcepcion($idLoc);
if(count($zonasExpecion)){
//------------------
$zonas = DataManager::getZonas(0, 0, 1);
foreach($zonas as $k => $zona){
$arrayZonas[] = $zona['zzona'];
}
$stringZonas = implode(",", $arrayZonas);
//-------------------
foreach ($zonasExpecion as $k => $ze) {
$zeCtaId = $ze['zeCtaId'];
$zeZona = $ze['zeZona'];
$idCuenta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $zeCtaId);
$empresa = DataManager::getCuenta('ctaidempresa', 'ctaid', $zeCtaId);
echo "<script>";
echo "javascript:dac_cargarDatosCuenta('".$zeCtaId."', '".$empresa."', '".$idCuenta."', '".$zeZona."', '".$stringZonas."');";
echo "</script>";
}
} ?>
</div> <!-- Fin lista -->
</div> <!-- FIN box_seccion -->
<hr>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html>
<script language="JavaScript" src="/pedidos/localidades/logica/jquery/jqueryUsrFooter.js" type="text/javascript"></script>
<file_sep>/localidades/logica/update.localidad.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo "LA SESION HA CADUCADO."; exit;
}
$idLoc = (isset($_POST['idLoc'])) ? $_POST['idLoc'] : NULL;
$provincia = (isset($_POST['provincia'])) ? $_POST['provincia'] : NULL;
$localidad = (isset($_POST['localidad'])) ? $_POST['localidad'] : NULL;
$codigoPostal = (isset($_POST['codigopostal'])) ? $_POST['codigopostal'] : NULL;
$zonaVSelect = (isset($_POST['zonaVSelect'])) ? $_POST['zonaVSelect'] : NULL;
$zonaDSelect = (isset($_POST['zonaDSelect'])) ? $_POST['zonaDSelect'] : NULL;
$ctaIdWeb = (isset($_POST['ctaId'])) ? $_POST['ctaId'] : NULL;
$zonaVExcWeb = (isset($_POST['zonaVExc'])) ? $_POST['zonaVExc'] : NULL;
if(empty($provincia)){ echo "Debe indicar una provincia."; exit; }
if(empty($localidad)){ echo "Debe indicar una localidad."; exit; }
if(empty($codigoPostal) && $codigoPostal != 0){ echo "Debe indicar un código postal."; exit; }
if(empty($zonaVSelect)){ echo "Debe indicar una zona de venta."; exit; }
if(empty($zonaDSelect)){ echo "Debe indicar una zona de distribución."; exit; }
//Comprobar que dicha localidad no existe
$cont = 0;
$localidad = mb_strtoupper(trim(str_replace(" ", " ", $localidad)),"UTF-8" );
$localidades = DataManager::getLocalidades(0, $provincia);
foreach ($localidades as $k => $loc) {
$locNombre = $loc['locnombre'];
$locIdLoc = $loc['locidloc'];
if($idLoc == 0) {
//Si localidad es nueva, solo debe uscar en ddbb.
if(!strcasecmp($localidad, $locNombre)) {
echo "La localidad ya existe."; exit;
}
} else {
//Si localidad es editada, debe controlar bbdd <> a editar + la posibilidad a editar
if(!strcasecmp($localidad, $locNombre) && $idLoc <> $locIdLoc) {
echo "La localidad ya existe."; exit;
}
}
}
if($ctaIdWeb){
if(count($ctaIdWeb) != count(array_unique($ctaIdWeb))){
echo "Existen excepciones duplicadas"; exit;
}
//La zona de excepción debe ser diferente a la zona de la localidad
if(in_array($zonaVSelect, $zonaVExcWeb)){
echo "Las zonas de excepción deben ser diferentes a la localidad."; exit;
}
}
//-----------//
// GUARDAR //
$localObject = ($idLoc) ? DataManager::newObjectOfClass('TLocalidad', $idLoc) : DataManager::newObjectOfClass('TLocalidad');
$localObject->__set('IDProvincia' , $provincia);
$localObject->__set('Localidad' , $localidad);
$localObject->__set('CP' , $codigoPostal);
$localObject->__set('ZonaVenta' , $zonaVSelect);
$localObject->__set('ZonaEntrega' , $zonaDSelect);
if ($idLoc) {
DataManagerHiper::updateSimpleObject($localObject, $idLoc);
DataManager::updateSimpleObject($localObject);
//--------------//
// MOVIMIENTO //
$movimiento = 'LOCALIDAD';
$movTipo = 'UPDATE';
} else {
$localObject->__set('ID' , $localObject->__newID());
DataManagerHiper::_getConnection('Hiper'); //Controla conexión a HiperWin
$idLoc = DataManager::insertSimpleObject($localObject);
DataManagerHiper::insertSimpleObject($localObject, $idLoc);
//--------------//
// MOVIMIENTO //
$movimiento = 'LOCALIDAD';
$movTipo = 'INSERT';
}
dac_registrarMovimiento($movimiento, $movTipo, "TLocalidad", $idLoc);
//CONTROLAR DIFERENCIA ENTRE EXCEPCIONES
$zeCtaIdDDBB= [];
$zeZonaDDBB = [];
$zonasExpecion = DataManager::getZonasExcepcion($idLoc);
if(count($zonasExpecion)){
foreach ($zonasExpecion as $k => $ze) {
$zeCtaIdDDBB[] = $ze['zeCtaId'];
$zeZonaDDBB[] = $ze['zeZona'];
}
}
//ACTUALIZAR EXCEPCIONES
if(count($zeCtaIdDDBB)){
//Recooro DDBB
for ($k=0; $k < count($zeCtaIdDDBB); $k++){
$zonaDefinida = 0;
if(count($ctaIdWeb)){
//SI ZONA está en DDBB y WEB, es UPDATE
if(in_array($zeCtaIdDDBB[$k], $ctaIdWeb)){
$key = array_search($zeCtaIdDDBB[$k], $ctaIdWeb);
//SOLO Si ZONA DDBB != A WEB es UPDATE
if($zeZonaDDBB[$k] != $zonaVExcWeb[$key]){
DataManager::deletefromtabla('zona_excepcion', 'zeCtaId', $zeCtaIdDDBB[$k]);
$campos = 'zeIdLoc, zeCtaId, zeZona';
$values = $idLoc.",".$zeCtaIdDDBB[$k].",".$zonaVExcWeb[$key];
DataManager::insertToTable('zona_excepcion', $campos, $values);
//DEFINE ÉSTA ZONA PARA LA CUENTA
$zonaDefinida = $zonaVExcWeb[$key];
}
//SI ZONA está en DDBB y NO WEB, es DELETE
} else {
//DELETE
DataManager::deletefromtabla('zona_excepcion', 'zeCtaId', $zeCtaIdDDBB[$k]);
//DEFINE ZONA ORIGINAL DE LA LOCALIDAD PARA LA CUENTA
$zonaDefinida = $zonaVSelect;
}
} else {
//DELETE
DataManager::deletefromtabla('zona_excepcion', 'zeCtaId', $zeCtaIdDDBB[$k]);
//DEFINE ZONA ORIGINAL DE LA LOCALIDAD PARA LA CUENTA
$zonaDefinida = $zonaVSelect;
}
//SI SE DEFINIO UNA ZONA PARA CUENTA, se modifica en la cuenta.
if($zonaDefinida){
$ctaObject = DataManager::newObjectOfClass('TCuenta', $zeCtaIdDDBB[$k]);
$ctaObject->__set('Zona', $zonaDefinida);
$ctaObjectHiper = DataManagerHiper::newObjectOfClass('THiperCuenta', $zeCtaIdDDBB[$k]);
$ctaObjectHiper->__set('Zona', $zonaDefinida);
DataManagerHiper::updateSimpleObject($ctaObjectHiper, $zeCtaIdDDBB[$k]);
DataManager::updateSimpleObject($ctaObject);
//----------------------------------
}
}
}
//se procede a los INSERTAR si hay excepciones en WEB que no estén en DDBB
if(count($ctaIdWeb)){
for($k=0; $k<count($ctaIdWeb); $k++) {
//si hay excepciones en DDBB
if(empty($zeCtaIdDDBB)){ $insertar = TRUE;
} else {
if(!in_array($ctaIdWeb[$k], $zeCtaIdDDBB)){
$insertar = TRUE;
} else {
$insertar = FALSE;
}
}
if($insertar){
$ctaExiste = DataManager::getZonasExcepcion(NULL, NULL, $ctaIdWeb[$k]);
if(count($ctaExiste) > 0){
$idCuenta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $ctaIdWeb[$k]);
echo "La cuenta ".$idCuenta." ya existe cargada como excepción en otra localidad."; exit;
}
//INSERT
$campos = 'zeIdLoc, zeCtaId, zeZona';
$values = $idLoc.",".$ctaIdWeb[$k].",".$zonaVExcWeb[$k];
DataManager::insertToTable('zona_excepcion', $campos, $values);
//--------------------------------
//UPDATE EN ZONA DE LA CUENTA
$ctaObject = DataManager::newObjectOfClass('TCuenta', $ctaIdWeb[$k]);
$ctaObject->__set('Zona' , $zonaVExcWeb[$k]);
$ctaObjectHiper = DataManagerHiper::newObjectOfClass('THiperCuenta', $ctaIdWeb[$k]);
$ctaObjectHiper->__set('Zona' , $zonaVExcWeb[$k]);
DataManagerHiper::updateSimpleObject($ctaObjectHiper, $ctaIdWeb[$k]);
DataManager::updateSimpleObject($ctaObject);
//----------------------------------
}
}
}
echo '1'; exit; ?><file_sep>/pedidos/logica/ajax/controlPedido.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//------------------------------//
// Controles Generales //
if(empty($idCondComercial) && empty($propuesta) && empty($tipoPedido) && empty($lista)){
echo "Seleccione Condición Comercial o indique como Propuesta."; exit;
}
if(!empty($propuesta)){ $idCondComercial = 0;}
if(empty($usrAsignado)){echo "Seleccione usuario asignado."; exit;}
if(empty($empresa)) { echo "Seleccione una empresa."; exit; }
if(empty($laboratorio)) { echo "Indique un laboratorio."; exit; }
if(empty($idCuenta)) { echo "Seleccione una cuenta"; exit; }
if(!empty($nroOrden) && !is_numeric($nroOrden)){ echo "El Número de Orden debe ser numérico"; exit; }
//------------------------//
// Control COND DE PAGO //
if(empty($condPago)){
echo "Seleccione condición de pago"; exit;
} else {
//controla si la condición de pago de cond fechas para modificar los días según fecha actual
$condicionPago = DataManager::getCondicionesDePago(0,0,1,$condPago);
if (count($condicionPago)) {
foreach ($condicionPago as $k => $condP) {
$condPagoId = $condP['condid'];
$condDecrece = $condP['conddecrece'];
if($condDecrece == 'S'){
//Al ser con fechas controla la vigencia de las mismas y resta los días en caso
//calcular días que restan
$dateFrom = new DateTime();
for($k=1; $k <= 5; $k++){
$condFechasDec[$k] = ($condP["condfechadec$k"] == '2001-01-01') ? '' : $condP["condfechadec$k"];
$condDias[$k] = ($condP["Dias".$k."CP"]) ? $condP["Dias".$k."CP"] : '' ;
if(!empty($condFechasDec[$k])){
$dateTo = new DateTime(dac_invertirFecha($condFechasDec[$k]));
$dateFrom->setTime($dateTo->format('H'), $dateTo->format('m'), $dateTo->format('s'));
if($dateTo < $dateFrom){
echo "La fecha de condición de pago a finalizado."; exit;
}
//Controla los días para editar a la fecha actual
$dateFrom->modify('-1 day');
$interval = $dateFrom->diff($dateTo);
if($interval->format('%R%a') != $condDias[$k]){
//si es distinto se hará el update
$condObject = DataManager::newObjectOfClass('TCondicionPago', $condPagoId);
if($k == 1){
$condObject->__set('Dias' , $interval->format('%R%a'));
} else {
$condObject->__set("Dias$k" , $interval->format('%R%a'));
}
DataManager::updateSimpleObject($condObject);
DataManagerHiper::updateSimpleObject($condObject, $condPagoId);
}
}
}
}
}
} else {
echo "La condción de pago seleccionada a sido desactivada."; exit;
}
}
//------------------//
// Nro de Orden //
$categoria = DataManager::getCuenta('ctacategoriacomercial', 'ctaidcuenta', $idCuenta, $empresa);
if ($categoria) {
//SI Cuenta ES DROGUERÍA o COOPERATIVA (Categoría 1), nro de Orden de compra es obligatorio
if ($categoria == 1 && empty($nroOrden) && $empresa == 3){
echo "Indique número de orden de compra."; exit;
}
} else {
echo "La categorí comercial no es correcta."; exit;
}
//----------------------//
// Artículos cargados //
if(!count($articulosIdArt)){ echo "Debe cargar artículos"; exit; }
$precioIva = 0;
for($i = 0; $i < count($articulosIdArt); $i++){
//----------------------//
// Artículos repetidos //
for($j = 0; $j < count($articulosIdArt); $j++){
if ($i != $j){
if ($articulosIdArt[$i] == $articulosIdArt[$j]){
echo "Artículo ".$articulosIdArt[$i]." repetido."; exit;
}
}
}
// Cantidad del Artículo //
if(empty($articulosCant[$i]) || $articulosCant[$i] <= 0){
echo "Indique una cantidad correcta al artículo ".$articulosIdArt[$i]; exit;
}
// Controla Bonificacion //
if($articulosB1[$i] < $articulosB2[$i]){
echo "Bonificación del artículo ".$articulosIdArt[$i]." incorrecta."; exit;
}
// Control de MONTO_MAXIMO //
$medicinal = DataManager::getArticulo('artmedicinal', $articulosIdArt[$i], $empresa, $laboratorio);
$medicinal = ($medicinal == 'S') ? 0 : 1;
$precioIva += dac_calcularPrecio($articulosCant[$i], $articulosPrecio[$i], $medicinal, $articulosD1[$i], $articulosD2[$i]);
}
//***********************//
// Condicion Comercial //
if($idCondComercial){
$condicion = DataManager::newObjectOfClass('TCondicionComercial', $idCondComercial);
$cuentas = $condicion->__get('Cuentas');
$tipo = $condicion->__get('Tipo');
$condCondPago = $condicion->__get('CondicionPago');
$cantMinima = ($condicion->__get('CantidadMinima')) ? $condicion->__get('CantidadMinima') : '';
$minReferencias = ($condicion->__get('MinimoReferencias')) ? $condicion->__get('CantidadMinima') : '';
$minMonto = ($condicion->__get('MinimoMonto') == '0.000') ? '' : $condicion->__get('MinimoMonto');
// Controles Condición Comercial //
if(!empty($cuentas)){
$cuentasId = explode(',', $cuentas);
$ctaID = DataManager::getCuenta('ctaid', 'ctaidcuenta', $idCuenta, $empresa);
if(!in_array($ctaID, $cuentasId)){
echo "Cuenta seleccionada no válida."; exit;
}
} else {
$condiciones = DataManager::getCondiciones(0, 0, 1, $empresa, $laboratorio, date("Y-m-d"));
if (count($condiciones)) {
foreach ($condiciones as $k => $cond) {
$cond = $condiciones[$k];
$condId = $cond['condid'];
$condCuentas = $cond['condidcuentas'];
$condNombre = $cond['condnombre'];
if($condCuentas){
if($condId != $idCondComercial){
$arrayCondIdCtas = explode(",", $condCuentas);
$ctaID = DataManager::getCuenta('ctaid', 'ctaidcuenta', $idCuenta, $empresa);
if(in_array($ctaID, $arrayCondIdCtas)){
echo "La cuenta utilizada corresponde a la condición comercial --> $condNombre."; exit;
}
}
}
}
}
}
if($condCondPago){
$condicionesPago = explode(',', $condCondPago);
if(!in_array($condPago, $condicionesPago)){
echo "Condición de pago no válida."; exit;
}
} else {
//Si no se definió condición de pago, deberá respetar las siguientes condiciones respecto a la condición de pago de la cuenta:
// 1) tenga <= cantidad de días. SIN cambiar tipo de condición
// 2) SI es FIRMA, acepta cambio de tipo a CONTRARREMBOLSO además de cumplir el punto 1
// Si se desea cambiar la condición de la cuenta, deberá pasar el pedido como propuesta y pedir en observación aprobar el cambio de condición de la cuenta.
$condPagoCuenta = DataManager::getCuenta('ctacondpago', 'ctaidcuenta', $idCuenta, $empresa);
if($condPago != $condPagoCuenta) {
//Busca condicion de pago de la cuenta
$condicionesPagoCuenta = DataManager::getCondicionesDePago(0, 0, 1, $condPagoCuenta);
if (count($condicionesPagoCuenta)) {
$condDiasCuenta = [];
foreach ($condicionesPagoCuenta as $k => $cond) {
$condTipoCuenta = $cond['condtipo'];
$condDiasCuenta = array($cond['Dias1CP'], $cond['Dias2CP'], $cond['Dias3CP'], $cond['Dias4CP'], $cond['Dias5CP']);
$condDiasCuenta = array_filter($condDiasCuenta);
$maxDiasCuenta = (count($condDiasCuenta) > 0) ? max($condDiasCuenta) : 0;
}
} else {
echo "La condicion de pago de la cuenta debe actualizarse antes de realizar un pedido."; exit;
}
//Busca condicion de pago seleccionada
$condicionesPago = DataManager::getCondicionesDePago(0, 0, 1, $condPago);
if (count($condicionesPago)) {
$condDias = [];
foreach ($condicionesPago as $k => $cond) {
$condTipo = $cond['condtipo'];
$condDias = array($cond['Dias1CP'], $cond['Dias2CP'], $cond['Dias3CP'], $cond['Dias4CP'], $cond['Dias5CP']);
$condDias = array_filter($condDias);
$maxDias = (count($condDias) > 0) ? max($condDias) : 0;
}
} else {
echo "Error al intentar consultar la condición de pago seleccionada."; exit;
}
//Controla diferencia de tipo
if($condTipoCuenta == 3 && $condTipo != 3){
echo "La condición de pago debe ser CONTRAREEMBOLSO."; exit;
}
//Controla diferencia de días
if($maxDias > $maxDiasCuenta){
echo "La condición de pago seleccionada es mayor a la permitida."; exit;
}
}
}
if($cantMinima){
if(array_sum($articulosCant) < $cantMinima){
echo "La cantidad de unidades no válida."; exit;
}
}
if($minReferencias){
if($minReferencias < count($articulosIdArt)){
echo "Cantidad de referencias no válida."; exit;
}
}
$montoFinal = 0;
$articulosCond = DataManager::getCondicionArticulos($idCondComercial);
if (count($articulosCond)) {
foreach ($articulosCond as $j => $artCond) {
$condArtIdArt = $artCond['cartidart'];
$condArtPrecio = $artCond["cartprecio"];
$condArtPrecioDigit = ($artCond["cartpreciodigitado"] == '0.000')? '' : $artCond["cartpreciodigitado"];
$precioArt = ($artCond["cartpreciodigitado"] == '0.000')? $condArtPrecio : $condArtPrecioDigit;
$condArtCantMin = empty($artCond['cartcantmin'])? '' : $artCond['cartcantmin'];
//Control de datos por artículo
if(in_array($condArtIdArt, $articulosIdArt)){
$key = array_search($condArtIdArt, $articulosIdArt);
if($key >= 0){
//Controlo Precio
if($precioArt > $articulosPrecio[$key]){
echo "Precio de artículo ".$articulosIdArt[$key]." no válido."; exit;
}
//Controlo Cantidad mínima
if($condArtCantMin){
if($articulosCant[$key] < $condArtCantMin){
echo "La cantidad mínima del artículo ".$articulosIdArt[$key]." debe ser ".$condArtCantMin; exit;
}
}
//**************************************//
// Calculo Condiciones del Vendedor //
$articulosBonifB1 = ($articulosB1[$key]) ? $articulosB1[$key] : 1;
$articulosBonifB2 = ($articulosB2[$key]) ? $articulosB2[$key] : 1;
$articulosBonifD1 = ($articulosD1[$key]) ? $articulosD1[$key] : 0;
$articulosBonifD2 = ($articulosD2[$key]) ? $articulosD2[$key] : 0;
$cantBonificada = ($articulosBonifB1 * $articulosCant[$key]) / $articulosBonifB2;
$cantEnteraBonificada = dac_extraer_entero($cantBonificada);
$precioUno = $articulosCant[$key] * $articulosPrecio[$key];
$precioDos = $precioUno / $cantEnteraBonificada;
$precioDesc1 = $precioDos - ($precioDos * $articulosBonifD1/100);
$precioDesc2 = $precioDesc1 - ($precioDesc1 * $articulosBonifD2/100);
$precioFinalVendido = $precioDesc2;
//NO CONTROLO EXACTAMENTE LAS BONIFICACIONES y DESCUENTOS
//YA QUE solo basta que EL RESULTADO NO SEa MENOR A X
//**************************************//
// Calculo Condiciones de la Empresa // según la cantidad pedida por el vendedor!
$artBonifCant = 1;
$artBonifB1 = 1;
$artBonifB2 = 1;
$artBonifD1 = 0;
$artBonifD2 = 0;
$articulosBonif = DataManager::getCondicionBonificaciones($idCondComercial, $condArtIdArt);
//importante que la función devuelva los valores ordenados
if (count($articulosBonif)){
foreach ($articulosBonif as $i => $artBonif){
//$artBonifCant = $artBonif['cbcant'];
if($articulosCant[$key] >= $artBonif['cbcant']){
$artBonifCant = ($artBonif['cbcant']) ? $artBonif['cbcant'] : '1';
$artBonifB1 = ($artBonif['cbbonif1']) ? $artBonif['cbbonif1'] : '1';
$artBonifB2 = ($artBonif['cbbonif2']) ? $artBonif['cbbonif2'] : '1';
$artBonifD1 = ($artBonif['cbdesc1']) ? $artBonif['cbdesc1'] : '0';
$artBonifD2 = ($artBonif['cbdesc2']) ? $artBonif['cbdesc2'] : '0';
}
}
}
$cantBonificada = ($artBonifB1 * $articulosCant[$key]) / $artBonifB2;
$cantEnteraBonificada = dac_extraer_entero($cantBonificada);
$precioUno = $articulosCant[$key] * $precioArt;
$precioDos = $precioUno / $cantEnteraBonificada;
$precioDesc1 = $precioDos - ($precioDos * $artBonifD1/100);
$precioDesc2 = $precioDesc1 - ($precioDesc1 * $artBonifD2/100);
$precioFinalEmpresa = $precioDesc2;
//y el IVA ???? $articulosIva[$key];
//CONTROLAR QUE POR EJEMPLO $articulosBonifB1 NO PUEDA SER CERO y que sea 1 en su defecto
//*************************************//
if($precioFinalVendido < $precioFinalEmpresa){
//Si precio final vendido < precio final de empresa, estará mal
if($tipo == 'CondicionEspecial' && $condArtIdArt >= 600){
//Para ésta condición comercial se hace una excepción para:
//Artículos código >= 600. El precio final podrá ser menor si,
//si se coloca al menos descuento que exista comobonificación de ese artícuulo
$condicionesBonif = DataManager::getCondiciones(0, 0, 1, $empresa, $laboratorio, date("Y-m-d"), 'Bonificacion');
if (count($condicionesBonif)) {
foreach ($condicionesBonif as $k => $condBonif) {
$condIdBonif = $condBonif['condid'];
$articulosCondBonif = DataManager::getCondicionArticulos($condIdBonif);
if (count($articulosCondBonif)) {
foreach ($articulosCondBonif as $q => $artCondBonif) {
$condArtIdArtBonif = $artCondBonif['cartidart'];
$condArtPrecioBonif = $artCondBonif["cartprecio"];
$condArtPrecioDigitBonif = ($artCondBonif["cartpreciodigitado"] == '0.000')? '' : $artCondBonif["cartpreciodigitado"];
$precioArtBonif = ($artCondBonif["cartpreciodigitado"] == '0.000')? $condArtPrecioBonif : $condArtPrecioDigitBonif;
if($condArtIdArt == $condArtIdArtBonif){
$articulosBonif = DataManager::getCondicionBonificaciones($condIdBonif, $condArtIdArtBonif);
if (count($articulosBonif)) {
foreach ($articulosBonif as $l => $artBonif) {
$artB1 = ($artBonif['cbbonif1']) ? $artBonif['cbbonif1'] : 1;
$artB2 = ($artBonif['cbbonif2']) ? $artBonif['cbbonif2'] : 1;
$artD1 = ($artBonif['cbdesc1']) ? $artBonif['cbdesc1'] : 0;
$artD2 = ($artBonif['cbdesc1']) ? $artBonif['cbdesc1'] : 0;
$cantBonif = ($artB1 * $articulosCant[$key]) / $artB2;
$cantEnteraBonificada = dac_extraer_entero($cantBonif);
$precioUno = $articulosCant[$key] * $precioArtBonif;
$precioDos = $precioUno / $cantEnteraBonificada;
$precioDesc1 = $precioDos - ($precioDos * $artD1/100);
$precioDesc2 = $precioDesc1 - ($precioDesc1 * $artD2/100);
$precioFinalEmpresa2 = $precioDesc2;
if($l == 0 && $precioFinalVendido < $precioFinalEmpresa2){
echo "Las condiciones del artículo ".$articulosIdArt[$key]." dan precio menor al acordado. "; exit;
}
}
} else {
echo "Las condiciones del artículo ".$articulosIdArt[$key]." dan precio menor al acordado. "; exit;
}
}
}
}
}
} else {
echo "Las condiciones del artículo ".$articulosIdArt[$key]." dan precio menor al acordado. "; exit;
}
} else {
echo "Las condiciones del artículo ".$articulosIdArt[$key]." dan precio menor al acordado. "; exit; //$precioFinalVendido < $precioFinalEmpresa
}
}
//----------------
//Sumo monto final
$montoFinal += $precioFinalVendido * $articulosCant[$key];
}
}
}
}
}
//Control de archivo
$filePeso = $_FILES["file"]["size"];
$fileType = $_FILES["file"]["type"];
$fileNombre = $_FILES["file"]["name"];
$fileTempName = $_FILES["file"]["tmp_name"];
//Control de archivo por orden de compra
if ($filePeso != 0){
if($filePeso > MAX_FILE){
echo "El archivo Orden de compra no debe superar los 4MB"; exit;
}
if(!dac_fileFormatControl($fileType, 'imagen')){
echo "El archivo debe tener formato imagen." ; exit;
}
} ?><file_sep>/condicion/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$condId = empty($_GET['condid']) ? 0 : $_GET['condid'];
if ($condId) {
$condicionObject= DataManager::newObjectOfClass('TCondicionComercial', $condId);
$empresa = $condicionObject->__get('Empresa');
$laboratorio = $condicionObject->__get('Laboratorio');
//$cuentas = $condicionObject->__get('Cuentas');
$nombre = $condicionObject->__get('Nombre');
$tipo = $condicionObject->__get('Tipo');
$condPago = $condicionObject->__get('CondicionPago');
$cantMinima = ($condicionObject->__get('CantidadMinima')) ? $condicionObject->__get('CantidadMinima') : '';
$minReferencias = ($condicionObject->__get('MinimoReferencias')) ? $condicionObject->__get('MinimoReferencias') : '';
$minMonto = ($condicionObject->__get('MinimoMonto') == '0.000') ? '' : $condicionObject->__get('MinimoMonto');
$fechaInicio = dac_invertirFecha( $condicionObject->__get('FechaInicio'));
$fechaFin = dac_invertirFecha($condicionObject->__get('FechaFin'));
$observacion = $condicionObject->__get('Observacion');
$habitualCant = ($condicionObject->__get('Cantidad') == '0') ? '' : $condicionObject->__get('Cantidad');
$habitualBonif1 = ($condicionObject->__get('Bonif1') == '0') ? '' : $condicionObject->__get('Bonif1');
$habitualBonif2 = ($condicionObject->__get('Bonif2') == '0') ? '' : $condicionObject->__get('Bonif2');
$habitualDesc1 = ($condicionObject->__get('Desc1') == '0.00') ? '' : $condicionObject->__get('Desc1');
$habitualDesc2 = ($condicionObject->__get('Desc2') == '0.00') ? '' : $condicionObject->__get('Desc2');
$lista = $condicionObject->__get('Lista');
} else {
$empresa = 1;
$laboratorio = 1;
$lista = 0;
//$cuentas =
$nombre =
$tipo =
$cantMinima =
$minReferencias =
$minMonto =
$condPago =
$fechaInicio =
$fechaFin =
$observacion =
$habitualCant =
$habitualBonif1 =
$habitualBonif2 =
$habitualDesc1 =
$habitualDesc2 = "";
}
$btnAltasCondiciones = sprintf("<input type=\"button\" id=\"btAltaCondiciones\" value=\"Actualizar Alta Condiciones\" title=\"Actualizar Alta en Condiciones Comerciales\"/>");
?>
<!doctype html>
<html xml:lang='es'>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
<script src="logica/jquery/jqueryHeaderEdit.js"></script>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = 'condiciones';
$_subsection = '';
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<form method="POST">
<div class="box_body">
<input type="text" id="condid" name="condid" value="<?php echo $condId;?>" hidden="hidden"/>
<fieldset>
<legend>Condición Comercial</legend>
<div class="bloque_1">
<fieldset id='box_observacion' class="msg_alerta">
<div id="msg_atencion" align="center"></div>
</fieldset>
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<div class="bloque_5">
<label for="empselect">Empresa</label>
<select id="empselect" name="empselect" onchange="javascript:dac_changeLaboratorio(this.value, labselect.value);"><?php
$empresas = DataManager::getEmpresas(1);
if (count($empresas)) {
foreach ($empresas as $k => $_emp) {
$_idemp = $_emp["empid"];
$_nombreemp = $_emp["empnombre"];
?><option id="<?php echo $_idemp; ?>" value="<?php echo $_idemp; ?>" <?php if ($empresa == $_idemp){ echo "selected"; } ?>><?php echo $_nombreemp; ?></option><?php
}
echo "<script>";
echo "javascript:dac_changeLaboratorio($empresa, $laboratorio)";
echo "</script>";
} ?>
</select>
</div>
<div class="bloque_5">
<label for="labselect">Laboratorio</label>
<select id="labselect" name="labselect" onchange="javascript:dac_changeLaboratorio(empselect.value, this.value);"><?php
$laboratorios = DataManager::getLaboratorios();
if (count($laboratorios)) {
foreach ($laboratorios as $k => $lab) {
$idLab = $lab["idLab"];
$nombreLab = $lab["Descripcion"];
?><option id="<?php echo $idLab; ?>" value="<?php echo $idLab; ?>" <?php if ($laboratorio == $idLab){ echo "selected"; }?> ><?php echo $nombreLab; ?></option><?php
}
echo "<script>";
echo "javascript:dac_changeLaboratorio($empresa, $laboratorio)";
echo "</script>";
} ?>
</select>
</div>
<div class="bloque_5">
<label for="tiposelect">Tipo</label>
<select id="tiposelect" name="tiposelect">
<option id=0 value=0 <?php if ($tipo == 0){ echo "selected"; } ?>></option>
<option id=1 value='Pack' <?php if ($tipo == 'Pack'){ echo "selected"; } ?>>Pack</option>
<option id=2 value='ListaEspecial' <?php if ($tipo == 'ListaEspecial'){ echo "selected"; } ?>>Lista Especial</option>
<option id=3 value='CondicionEspecial' <?php if ($tipo == 'CondicionEspecial'){ echo "selected"; } ?>>Condición Especial</option>
<option id=4 value='Propuesta' <?php if ($tipo == 'Propuesta'){ echo "selected"; } ?>>Propuesta</option>
<option id=5 value='Bonificacion' <?php if ($tipo == 'Bonificacion'){ echo "selected"; } ?>>Bonificación</option>
</select>
</div>
<div class="bloque_5">
<label for="nombre">Nombre</label>
<input name="nombre" id="nombre" type="text" maxlength="50" value="<?php echo $nombre; ?>"/>
</div>
<div class="bloque_7">
<label for="minMonto">Monto mínimo</label>
<input name="minMonto" id="minMonto" type="text" maxlength="10" value="<?php echo $minMonto;?>"/>
</div>
<div class="bloque_7">
<label for="cantMinima">Cantidad Mínima</label>
<input name="cantMinima" id="cantMinima" type="text" maxlength="10" value="<?php echo $cantMinima;?>"/>
</div>
<div class="bloque_7">
<label for="minReferencias">Min de Referencias</label>
<input name="minReferencias" id="minReferencias" type="text" maxlength="5" value="<?php echo $minReferencias;?>"/>
</div>
<div class="bloque_7">
<label for="listaPrecio">Lista</label>
<select id="listaPrecio" name="listaPrecio"/>
<?php
$listas = DataManager::getListas();
if (count($listas)) { ?>
<option value="0" selected></option><?php
foreach ($listas as $k => $list) {
$listId = $list["IdLista"];
$listNombre = $list["NombreLT"];
$selected = ($listId == $lista) ? 'selected' : ''; ?>
<option value="<?php echo $listId; ?>" <?php echo $selected; ?>><?php echo $listNombre; ?></option> <?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<label for="fechaInicio">Fecha Inicio</label>
<input name="fechaInicio" id="fechaInicio" type="text" value="<?php echo $fechaInicio;?>" readonly/>
</div>
<div class="bloque_7">
<label for="fechaFin">Fecha Fin</label>
<input name="fechaFin" id="fechaFin" type="text" value="<?php echo $fechaFin;?>" readonly/>
</div>
<?php if($tipo == 'Bonificacion') { ?>
<div class="bloque_6"> <br><?php echo $btnAltasCondiciones; ?> </div>
<?php } ?>
<div class="bloque_1">
<label for="observacion">Observación</label>
<textarea name="observacion" id="observacion" maxlength="500" onkeyup="javascript:dac_LimitaCaracteres(event, 'observacion', 500);" onkeydown="javascript:dac_LimitaCaracteres(event, 'observacion', 500);" value="<?php echo $observacion;?>"/><?php echo $observacion;?></textarea>
<fieldset id='box_informacion' class="msg_informacion">
<div id="msg_informacion" align="center"></div>
</fieldset>
</div>
<div class="bloque_7">
<input id="btsend" type="button" value="Enviar" title="Enviar"/>
</div>
</fieldset>
<fieldset>
<legend>Condición de Pago</legend>
<div id="detalle_condpago"></div>
<?php
if ($condId) {
if(!empty($condPago)){
$condicionesPago = explode(",", $condPago);
foreach ($condicionesPago as $condicionPago) {
$condicionesPago = DataManager::getCondicionesDePago(0, 0, NULL, $condicionPago);
if (count($condicionesPago)) {
foreach ($condicionesPago as $k => $condPago) {
$condPagoNombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condPago['condtipo']);
$condPagoDias = "(";
$condPagoDias .= empty($condPago['Dias1CP']) ? '0' : $condPago['Dias1CP'];
$condPagoDias .= empty($condPago['Dias2CP']) ? '' : ', '.$condPago['Dias2CP'];
$condPagoDias .= empty($condPago['Dias3CP']) ? '' : ', '.$condPago['Dias3CP'];
$condPagoDias .= empty($condPago['Dias4CP']) ? '' : ', '.$condPago['Dias4CP'];
$condPagoDias .= empty($condPago['Dias5CP']) ? '' : ', '.$condPago['Dias5CP'];
$condPagoDias .= " Días)";
$condPagoDias .= ($condPago['Porcentaje1CP'] == '0.00') ? '' : ' '.$condPago['Porcentaje1CP'].' %';
}
}
echo "<script>";
echo "javascript:dac_cargarCondicionPago('".$condicionPago."', '".$condPagoNombre."', '".$condPagoDias."')";
echo "</script>";
}
}
} ?>
</fieldset>
<fieldset>
<legend>Condición Habitual</legend>
<div class="bloque_8">
<label for="habitualCant">Cantidad</label>
<input name="habitualCant" id="habitualCant" type="text" maxlength="2" value="<?php echo $habitualCant; ?>"/>
</div>
<div class="bloque_8">
<label for="habitualBonif1">B1</label>
<input name="habitualBonif1" id="habitualBonif1" type="text" maxlength="2" value="<?php echo $habitualBonif1; ?>"/>
</div>
<div class="bloque_8">
<label for="habitualBonif2">B2</label>
<input name="habitualBonif2" id="habitualBonif2" type="text" maxlength="2" value="<?php echo $habitualBonif2; ?>"/>
</div>
<div class="bloque_8">
<label for="habitualDesc1">D1</label>
<input name="habitualDesc1" id="habitualDesc1" type="text" maxlength="5" value="<?php echo $habitualDesc1; ?>" onkeydown="ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);" onKeyUp="javascript:ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);"/>
</div>
<div class="bloque_8">
<label for="habitualDesc2">D2</label>
<input name="habitualDesc2" id="habitualDesc2" type="text" maxlength="5" value="<?php echo $habitualDesc2; ?>" onkeydown="ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);" onKeyUp="javascript:ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);"/>
</div>
</fieldset>
<!--fieldset>
<legend>Cuentas</legend>
<div id="detalle_cuenta"></div>
</fieldset-->
<?php
/*if ($condId) {
if(!empty($cuentas)){
$cuentasCondiciones = explode(",", $cuentas);
foreach ($cuentasCondiciones as $ctaCond) {
$ctaCondIdCta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $ctaCond, $empresa);
$ctaCondNombre = DataManager::getCuenta('ctanombre', 'ctaid', $ctaCond, $empresa);
echo "<script>";
echo "javascript:dac_cargarCuentaCondicion('".$ctaCond."', '".$ctaCondIdCta."', '".$ctaCondNombre."')";
echo "</script>";
}
}
}*/ ?>
</div> <!-- END box_body -->
<div class="box_seccion">
<!--div class="barra">
<div class="bloque_5">
<h2>Cuentas</h2>
</div>
<div class="bloque_5">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn" type="text" value="tblCuentas" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<!--div class="lista">
<div id='tablacuentas'></div>
</div> <!-- Fin listar -->
<div class="barra">
<div class="bloque_5">
<h2>Condiciones de Pago</h2>
</div>
<div class="bloque_5">
<input id="txtBuscar3" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn3" type="text" value="tblCondicionesPago" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista"><?php
$condicionesDePago = DataManager::getCondicionesDePago(0,0,1);
if (count($condicionesDePago)) {
echo '<table id="tblCondicionesPago" style=\"table-layout:fixed\">';
echo '<thead><tr align="left"><th>Cod</th><th>Nombre</th><th>Días</th></tr></thead>';
echo '<tbody>';
foreach ($condicionesDePago as $k => $condDePago) {
$condCod = $condDePago['IdCondPago'];
$nombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condDePago['condtipo']);
$dias = "(";
$dias .= empty($condDePago['Dias1CP']) ? '0' : $condDePago['Dias1CP'];
$dias .= empty($condDePago['Dias2CP']) ? '' : ', '.$condDePago['Dias2CP'];
$dias .= empty($condDePago['Dias3CP']) ? '' : ', '.$condDePago['Dias3CP'];
$dias .= empty($condDePago['Dias4CP']) ? '' : ', '.$condDePago['Dias4CP'];
$dias .= empty($condDePago['Dias5CP']) ? '' : ', '.$condDePago['Dias5CP'];
$dias .= " Días)";
$dias .= ($condDePago['Porcentaje1CP'] == '0.00') ? '' : ' '.$condDePago['Porcentaje1CP'].' %';
((($k % 2) == 0)? $clase="par" : $clase="impar");
if($condCod != 0){
echo "<tr id=condPago".$condCod." class=".$clase." style=\"cursor:pointer;\" onclick=\"javascript:dac_cargarCondicionPago('$condCod', '$nombre', '$dias')\">";
echo "<td>".$condCod."</td><td>".$nombre."</td><td>".$dias."</td>";
echo "</tr>";
}
}
echo "</tbody></table>";
} else {
echo '<table><thead><tr><th align="center">No hay registros activos.</th></tr></thead></table>'; exit;
} ?>
</div> <!-- fin lista -->
<div class="barra">
<div class="bloque_5">
<h2>Artículos</h2>
</div>
<div class="bloque_5">
<input id="txtBuscar2" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn2" type="text" value="tblArticulos" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<div id='tablaarticulos'></div>
</div> <!-- fin lista -->
</div> <!-- Fin box_seccion -->
<hr>
<div class="box_down">
<fieldset>
<legend>Artículos</legend>
<div id="detalle_articulo"></div>
</fieldset>
<?php
if ($condId) {
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
foreach ($articulosCond as $k => $artCond) {
$artCond = $articulosCond[$k];
$condArtId = $artCond['cartid'];
$condArtIdArt = $artCond['cartidart'];
$condArtNombre = DataManager::getArticulo('artnombre', $condArtIdArt, $empresa, $laboratorio);
// --> precio original de la tabla artículos
$condArtPrecio = $artCond["cartprecio"];
// --> precio de Lista
$condArtMedicinal= DataManager::getArticulo('artmedicinal', $condArtIdArt, $empresa, $laboratorio);
$condArtIva = DataManager::getArticulo('artiva', $condArtIdArt, $empresa, $laboratorio);
$condArtGanancia = DataManager::getArticulo('artganancia', $condArtIdArt, $empresa, $laboratorio);
//--> precio digitado o precio de venta.
$condArtPrecioDigit = ($artCond["cartpreciodigitado"] == '0.000')? '' : $artCond["cartpreciodigitado"];
$condArtCantMin = empty($artCond['cartcantmin'])? '' : $artCond['cartcantmin'];
$condArtOAM = $artCond["cartoam"];
$condArtOferta = $artCond["cartoferta"];
echo "<script>";
echo "javascript:dac_cargarArticuloCondicion('".$condArtId."', '".$condArtIdArt."', '".$condArtNombre."', '".$condArtPrecio."', '".$condArtCantMin."', '".$condArtPrecioDigit."', '".$condArtOAM."', '".$condArtMedicinal."', '".$condArtIva."', '".$empresa."', '".$condArtGanancia."', '".$condArtOferta."')";
echo "</script>";
//Controlo si tiene Bonificaciones para cargar
$articulosBonif = DataManager::getCondicionBonificaciones($condId, $condArtIdArt);
if (count($articulosBonif)) {
foreach ($articulosBonif as $j => $artBonif) {
$artBonifId = empty($artBonif['cbid']) ? '' : $artBonif['cbid'];
$artBonifCant = empty($artBonif['cbcant']) ? '' : $artBonif['cbcant'];
$artBonifB1 = empty($artBonif['cbbonif1']) ? '' : $artBonif['cbbonif1'];
$artBonifB2 = empty($artBonif['cbbonif2']) ? '' : $artBonif['cbbonif2'];
$artBonifD1 = empty($artBonif['cbdesc1']) ? '' : $artBonif['cbdesc1'];
$artBonifD2 = empty($artBonif['cbdesc2']) ? '' : $artBonif['cbdesc2'];
echo "<script>";
echo "javascript:dac_addBonificacion('".($k+1)."', '".$condArtId."', '".$condArtIdArt."', '".$artBonifCant."', '".$artBonifB1."', '".$artBonifB2."', '".$artBonifD1."', '".$artBonifD2."', '".$artBonifId."')";
echo "</script>";
}
}
}
}
} ?>
</div> <!-- Fin box_down -->
</form>
<hr>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html>
<script src="logica/jquery/jqueryFooterEdit.js"></script><file_sep>/includes/menu.accord.php
<script>
$(function() {
$("#accordion").accordion({
//active: 0 inicia con el número de barra desplegado que elija desde el 0 (primero por defecto) en adelante
//animate: 200 tiempo de animación para pasar de una barra a la otra
//disabled: true //desabilita el acorde de menues
//event: "mouseover" se activan con mouseover en vez del click
icons: { "header": "ui-icon-plus", "activeHeader": "ui-icon-minus" },
heightStyle: "content" //"auto" //"fill" / "content"
});
});
function dacCloseDialog(){
$("#dialog").dialog("close");
location.reload();
}
</script>
<script>
function dac_showDialog(dialo_type){
$( "#dialog" ).empty();
var origen = document.getElementById('origen').value;
var idorigen = document.getElementById('idorigen').value;
var title = '';
switch (dialo_type){
case 'new':
title = 'Nuevo Contacto';
ctoid = 0;
dac_crearDialog(ctoid, idorigen, origen, title);
break;
case 'edit':
title = 'Editar Contacto';
if ( document.getElementById( 'contactos' )) {
var posicion = document.getElementById('contactos').options.selectedIndex;
var ctoid = document.getElementById('contactos').options[posicion].value;
dac_crearDialog(ctoid, idorigen, origen, title);
} else { return false; }
break;
case 'delete':
title = 'Eliminar Contacto';
if ( document.getElementById( 'contactos' )) {
var posicion = document.getElementById('contactos').options.selectedIndex; //posicion
var ctoid = document.getElementById('contactos').options[posicion].value;
if(confirm("\u00BFSeguro que desea eliminar el contacto?")){
dac_deleteContacto(ctoid); //al borrar contacto, hay que tener en cuenta todos sus domicilios, cuando los tenga.
}
} else { return false; }
break;
default: break;
}
}
function dac_crearDialog(ctoid, idorigen, origen, title){
$("#dialog").dialog({
modal: true, title: 'Mensaje', zIndex: 10000, autoOpen: true,
resizable: false,
width: 380, //40 mas que el iframe
height: 440, //90 más que el iframe
});
$( "#dialog" ).dialog( "option", "title", title );
$('<input id=\"closeDialog\" onClick=\"javascript:dacCloseDialog()\" value=\"cerrar\" type=\"button\" hidden >').appendTo('#dialog');
$('<iframe name=\"dialog_iframe\" src=\"/pedidos/contactos/editar.php?origenid='+idorigen+'&origen='+origen+'&ctoid='+ctoid+'\" height=\"350\" width=\"100%\" frameborder=\"0\" scrolling=\"auto\"></iframe>').appendTo('#dialog');
}
</script>
<script language="JavaScript" type="text/javascript">
function dac_deleteContacto(ctoid) {
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/contactos/logica/ajax/delete.contacto.php',
data: { ctoid : ctoid },
beforeSend: function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
$('#box_cargando').css({'display':'none'});
if (resultado){
location.reload();
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al intentar eliminar el contacto.");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al intentar eliminar el contacto.");
}
});
}
</script>
<script language="JavaScript" type="text/javascript">
function dac_cambiarContacto() {
var posicion = document.getElementById('contactos').options.selectedIndex; //posicion
var ctoid = document.getElementById('contactos').options[posicion].value;
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/contactos/logica/ajax/cargar.contacto.php',
data: { ctoid : ctoid },
beforeSend: function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
$('#box_cargando').css({'display':'none'});
if (resultado){
var json = eval(resultado);
document.getElementById('ctoapellido').value = json[0].apellido;
document.getElementById('ctonombre').value = json[0].nombre;
document.getElementById('ctotelefono').value = json[0].telefono;
document.getElementById('ctointerno').value = json[0].interno;
document.getElementById('ctosector').value = json[0].sector;
document.getElementById('ctocorreo').value = json[0].correo;
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar el contacto.");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al intentar consultar el contacto.");
}
});
}
</script>
<div id="dialog" style="display:none;"> </div>
<div id="accordion" align="left">
<?php $_contactos = DataManager::getContactosPorCuenta( $_idorigen, $_origen, 1); ?>
<h3>Contactos <?php echo "(".count($_contactos).")"; ?></h3>
<div>
<div class="bloque_1">
<fieldset id='box_observacion' class="msg_alerta">
<div id="msg_atencion" align="center"></div>
</fieldset>
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<input id="idorigen" type="text" value="<?php echo $_idorigen;?>" hidden/>
<input id="origen" type="text" value="<?php echo $_origen;?>" hidden/>
<?php
if (count($_contactos)) { ?>
<div class="bloque_1">
<select id="contactos" name="contactos" onchange="javascript:dac_cambiarContacto()"> <?php
foreach ($_contactos as $k => $_cont){
$_ctoid = $_cont["ctoid"];
if ($k == 0){
$_ctoapellido = $_cont["ctoapellido"];
$_ctonombre = $_cont["ctonombre"];
$_ctotelefono = $_cont["ctotelefono"];
$_ctointerno = $_cont["ctointerno"];
$_sector = $_cont["ctosector"];
$_sectores = DataManager::getSectores(1);
if($_sectores){
foreach ($_sectores as $k => $_sect) {
$_sectid = $_sect['sectid'];
if($_sectid == $_sector){
$_sectnombre = $_sect['sectnombre'];
}
}
}
$_ctocorreo = $_cont["ctocorreo"]; ?>
<option value="<?php echo $_ctoid; ?>" selected><?php echo strtoupper($_cont["ctoapellido"]).", ".$_cont["ctonombre"]; ?></option><?php
} else { ?>
<option value="<?php echo $_ctoid; ?>"><?php echo strtoupper($_cont["ctoapellido"]).", ".$_cont["ctonombre"]; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_5">
<label><strong>Apellido </strong></label>
<input id="ctoapellido" type="text" value="<?php echo $_ctoapellido;?>" readonly/>
</div>
<div class="bloque_5">
<label><strong>Nombre </strong></label>
<input id="ctonombre" type="text" value="<?php echo $_ctonombre;?>" readonly/>
</div>
<div class="bloque_5" >
<label><strong>Teléfono </strong></label>
<input id="ctotelefono" type="text" value="<?php echo $_ctotelefono;?>" readonly/>
</div>
<div class="bloque_5" >
<label><strong>Interno </strong></label>
<input id="ctointerno" type="text" value="<?php echo $_ctointerno;?>" readonly/>
</div>
<div class="bloque_5" >
<label><strong>Sector/Dpto </strong></label>
<input id="ctosector" type="text" value="<?php echo $_sectnombre;?>" readonly />
</div>
<div class="bloque_5" >
<label><strong>Correo </strong></label>
<input id="ctocorreo" type="text" value="<?php echo $_ctocorreo;?>" readonly/>
</div>
<?php
} ?>
<hr>
<div class="bloque_1">
<img class="icon-new2" onclick="javascript:dac_showDialog('new')"/>
<img class="icon-edit" onclick="javascript:dac_showDialog('edit')"/>
<img class="icon-delete" onclick="javascript:dac_showDialog('delete')"/>
</div>
</div>
</div> <!-- fin accordion --><file_sep>/soporte/tickets/nuevo/logica/jquery/script.js
$(function(){"use strict"; $('#btsend').click(sendForm); });
/********************/
// SUBIR INFORMES UNICOS //
/********************/
function sendForm(){
"use strict";
var archivos= document.getElementById("imagen");
var archivo = archivos.files;
archivos = new FormData();
for(var i=0; i<archivo.length; i++){
archivos.append('archivo'+i,archivo[i]);
}
var idtipo = document.getElementById("tkidtipo").value;
var tipo = document.getElementById("tktipo").value;
var mensaje = document.getElementById("tkmensaje").value;
var copia = document.getElementById("tkcopia").value;
archivos.append('idtipo' , idtipo);
archivos.append('tipo' , tipo);
archivos.append('mensaje' , mensaje);
archivos.append('copia' , copia);
$.ajax({
url :'/pedidos/soporte/tickets/nuevo/logica/update.ticket.php',
type :'POST',
contentType :false,
data :archivos,
processData :false,
cache :false,
beforeSend : function () {
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
afterSend : function() {
$('#box_cargando').css({'display':'none'});
},
success : function(result) {
if(result){
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
} else {
//reenvía al inicia
}
},
});
}<file_sep>/soporte/tickets/nuevo/logica/update.ticket.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo "SU SESIÓN HA EXPIRADO."; exit;
}
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/soporte/tickets/nuevo/editar.php': $_REQUEST['backURL'];
$idSector = empty($_POST['tkidsector']) ? 0 : $_POST['tkidsector'];
$motivo = empty($_POST['tkmotivo']) ? "" : $_POST['tkmotivo'];
$mensaje = empty($_POST['tkmensaje']) ? "" : $_POST['tkmensaje'];
$correo = empty($_POST['tkcopia']) ? "" : $_POST['tkcopia'];
if (empty($idSector)) {
echo "Error al seleccionar un motivo de consulta."; exit;
}
if (empty($motivo)) {
echo "Seleccione un motivo de servicio."; exit;
}
if (empty($mensaje)) {
echo "Indique un mensaje."; exit;
}
if (!empty($correo)) {
$correo = trim($correo, ' ');
if (!dac_validateMail($correo)) {
echo "El corréo es incorrecto."; exit;
}
}
$imagenNombre = $_FILES["imagen"]["name"];
$imagenPeso = $_FILES["imagen"]["size"];
if ($imagenPeso != 0){
if($imagenPeso > MAX_FILE){
echo "El archivo no debe superar los 4 MB"; exit;
}
}
if ($imagenPeso != 0){
if(dac_fileFormatControl($_FILES["imagen"]["type"], 'imagen')){
$ext = explode(".", $imagenNombre);
$name = dac_sanearString($ext[0]);
} else {
echo "La imagen debe ser .JPG o .PDF"; exit;
}
}
$objectTicket = DataManager::newObjectOfClass('TTicket');
$objectTicket->__set('Sector' , $idSector);
$objectTicket->__set('IDMotivo' , $motivo);
$objectTicket->__set('Prioridad' , 1);
$objectTicket->__set('Estado' , 1); //1 ACTIVO //2PENDIENTE //0 CERRADO
$objectTicket->__set('UsrCreated' , $_SESSION["_usrid"]);
$objectTicket->__set('UsrUpdate' , $_SESSION["_usrid"]);
$objectTicket->__set('LastUpdate' , date("Y-m-d H:m:s"));
$objectTicket->__set('DateCreated' , date("Y-m-d H:m:s"));
$objectTicket->__set('Activo' , 1);
$objectTicket->__set('ID' , $objectTicket->__newID());
$IDTicket = DataManager::insertSimpleObject($objectTicket);
$objectMsg = DataManager::newObjectOfClass('TTicketMensaje');
$objectMsg->__set('IDTicket' , $IDTicket);
$objectMsg->__set('Descripcion' , $mensaje);
$objectMsg->__set('UsrCreated' , $_SESSION["_usrid"]);
$objectMsg->__set('DateCreated' , date("Y-m-d H:m:s"));
$objectMsg->__set('Activo' , 1);
$objectMsg->__set('ID' , $objectMsg->__newID());
$IDMsg = DataManager::insertSimpleObject($objectMsg);
echo "1"; exit;
?><file_sep>/includes/class/class.condicioncomercial.php
<?php
require_once('class.PropertyObject.php');
class TCondicionComercial extends PropertyObject {
protected $_tablename = 'condicion';
protected $_fieldid = 'condid';
protected $_fieldactivo = 'condactiva';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'condid';
$this->propertyTable['Empresa'] = 'condidemp';
$this->propertyTable['Laboratorio'] = 'condidlab';
$this->propertyTable['Cuentas'] = 'condidcuentas';
/*Se trata de condicionde uso único para los clientes separados por coma indicados en un string (Cuentas)*/
$this->propertyTable['Nombre'] = 'condnombre';
$this->propertyTable['Tipo'] = 'condtipo'; /*Pack, listas, condiciones, kits, etc*/
$this->propertyTable['CondicionPago'] = 'condcondpago';
$this->propertyTable['CantidadMinima'] = 'condcantmin'; //Cantidad de unidades mñínima por condición
$this->propertyTable['MinimoReferencias'] = 'condminreferencias';
$this->propertyTable['MinimoMonto'] = 'condminmonto';
$this->propertyTable['FechaInicio'] = 'condfechainicio';
$this->propertyTable['FechaFin'] = 'condfechafin';
$this->propertyTable['Observacion'] = 'condobservacion';
//Condición Habitual
$this->propertyTable['Cantidad'] = 'condhabcant';
$this->propertyTable['Bonif1'] = 'condhabbonif1';
$this->propertyTable['Bonif2'] = 'condhabbonif2';
$this->propertyTable['Desc1'] = 'condhabdesc1';
$this->propertyTable['Desc2'] = 'condhabdesc2';
$this->propertyTable['UsrUpdate'] = 'condusrupdate';
$this->propertyTable['LastUpdate'] = 'condlastupdate';
$this->propertyTable['Activa'] = 'condactiva';
$this->propertyTable['Lista'] = 'condlista';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/llamada/logica/update.llamada.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$_origen = (isset($_POST['origen'])) ? $_POST['origen'] : NULL;
$_idorigen = (isset($_POST['idorigen'])) ? $_POST['idorigen'] : NULL;
$_nroRel = (isset($_POST['nroRel'])) ? $_POST['nroRel'] : NULL;
$_telefono = (isset($_POST['telefono'])) ? $_POST['telefono'] : NULL;
$_tiporesultado = (isset($_POST['tiporesultado']))? $_POST['tiporesultado'] : NULL;
$_resultado = (isset($_POST['resultado'])) ? $_POST['resultado'] : NULL;
$_observacion = (isset($_POST['observacion'])) ? $_POST['observacion'] : NULL;
if (empty($_origen ) || empty($_idorigen) || empty($_nroRel) || empty($_tiporesultado)) {
echo "Error al leer los datos de registro."; exit;
}
if($_tiporesultado == 'incidencia'){
switch($_resultado){
case '0':
echo "Debe indicar el tipo de incidencia"; exit;
break;
case 'otras':
if (empty($_observacion)){
echo "Debe indicar el motivo de la incidencia"; exit;
}
break;
default: break;
}
}
if(empty($_resultado)){
echo "Debe indicar un resultado de llamada"; exit;
}
$_llamobject = DataManager::newObjectOfClass('TLlamada');
$_llamobject->__set('ID' , $_llamobject->__newID());
$_llamobject->__set('Origen' , $_origen);
$_llamobject->__set('IDOrigen' , $_idorigen);
$_llamobject->__set('Telefono' , $_telefono);
$_llamobject->__set('Fecha' , date("Y-m-d H:i:s"));
$_llamobject->__set('TipoResultado' , $_tiporesultado);
$_llamobject->__set('Resultado' , $_resultado);
$_llamobject->__set('Observacion' , $_observacion);
$_llamobject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$_llamobject->__set('LastUpdate' , date("Y-m-d H:i:s"));
$_llamobject->__set('Activa' , 0);
$ID = DataManager::insertSimpleObject($_llamobject);
echo "1"; exit;
?><file_sep>/transfer/gestion/abmtransfer/logica/changestatus.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_mes = empty($_REQUEST['mes']) ? 0 : $_REQUEST['mes'];
$_anio = empty($_REQUEST['anio']) ? 0 : $_REQUEST['anio'];
$_drogid = empty($_REQUEST['drogid']) ? 0 : $_REQUEST['drogid'];
$_activo = empty($_REQUEST['activo']) ? 0 : $_REQUEST['activo'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/transfer/gestion/abmtransfer/' : $_REQUEST['backURL'];
if ($_mes && $_anio && $_drogid) {
if($_activo == 0){ //Activar
//1er Consulto los abm activos de la droguería para desactivarlos
$_abms = DataManager::getDetalleAbmDrogueria($_drogid, 1);
if ($_abms) {
foreach ($_abms as $k => $_abm){
$_abm = $_abms[$k];
$_abmID = $_abm['abmid'];
//desactivo
$_abmobject= DataManager::newObjectOfClass('TAbm', $_abmID);
$_abmobject->__set('Activo', 0);
$ID = DataManager::updateSimpleObject($_abmobject);
}
}
//2do Activo los abm de la drog, mes y año indicado.
$_abms = DataManager::getDetalleAbm($_mes, $_anio, $_drogid, 'TL');
if ($_abms) {
foreach ($_abms as $k => $_abm){
$_abm = $_abms[$k];
$_abmID = $_abm['abmid'];
/*****************************/
$_abmobject = DataManager::newObjectOfClass('TAbm', $_abmID);
$_abmobject->__set('Activo', 1);
$ID = DataManager::updateSimpleObject($_abmobject);
}
}
} else { //Desactivar // Solo desactivo los abm's del mes indicado
$_abms = DataManager::getDetalleAbm($_mes, $_anio, $_drogid, 'TL');
if ($_abms) {
foreach ($_abms as $k => $_abm){
$_abm = $_abms[$k];
$_abmID = $_abm['abmid'];
/*****************************/
$_abmobject = DataManager::newObjectOfClass('TAbm', $_abmID);
$_abmobject->__set('Activo', 0);
$ID = DataManager::updateSimpleObject($_abmobject);
}
}
}
}
/***************************************************************/
header('Location: '.$backURL.'?fecha_abm='.$_mes.'-'.$_anio."&drogid=".$_drogid);
?><file_sep>/includes/class/class.condicioncomercial.art.php
<?php
require_once('class.PropertyObject.php');
class TCondicionComercialArt extends PropertyObject {
protected $_tablename = 'condicion_art';
protected $_fieldid = 'cartid';
protected $_fieldactivo = 'cartactivo';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'cartid';
$this->propertyTable['Condicion'] = 'cartidcond';
$this->propertyTable['Articulo'] = 'cartidart';
$this->propertyTable['Precio'] = 'cartprecio';
$this->propertyTable['Digitado'] = 'cartpreciodigitado';
$this->propertyTable['CantidadMinima'] = 'cartcantmin'; //Cantidad de unidades mínima por artículo
$this->propertyTable['OAM'] = 'cartoam'; //Oferta, Alta y/o Modificación
$this->propertyTable['Activo'] = 'cartactivo';
$this->propertyTable['Oferta'] = 'cartoferta';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/includes/class/class.contacto.php
<?php
require_once('class.PropertyObject.php');
class TContacto extends PropertyObject {
protected $_tablename = 'contacto';
protected $_fieldid = 'ctoid';
protected $_fieldactivo = 'ctoactivo';
protected $_timestamp = 0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'ctoid';
$this->propertyTable['Origen'] = 'ctoorigen'; //De donde sale el contacto (nombre Tabla) ejemplo, de un proveedor (tabla TProveedor)
$this->propertyTable['IDOrigen'] = 'ctoorigenid'; // id de la tabla Origen
$this->propertyTable['Domicilio'] = 'ctodomicilioid';
$this->propertyTable['Sector'] = 'ctosector';
$this->propertyTable['Puesto'] = 'ctopuesto';
$this->propertyTable['Nombre'] = 'ctonombre';
$this->propertyTable['Apellido'] = 'ctoapellido';
$this->propertyTable['Genero'] = 'ctogenero';
$this->propertyTable['Telefono'] = 'ctotelefono';
$this->propertyTable['Interno'] = 'ctointerno';
$this->propertyTable['Email'] = 'ctocorreo';
$this->propertyTable['Activo'] = 'ctoactivo';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->propertyTable['ID']);
}
public function __validate() {
return true;
}
}
?><file_sep>/zonas/logica/eliminar.zona.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_zid = empty($_REQUEST['zid']) ? 0 : $_REQUEST['zid'];
$_nrozona = empty($_REQUEST['nrozona']) ? 0 : $_REQUEST['nrozona'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/zonas/': $_REQUEST['backURL'];
if ($_zid) {
$_zobject = DataManager::newObjectOfClass('TZonas', $_zid);
$_zobject->__set('ID', $_zid );
$ID = DataManager::deleteSimpleObject($_zobject);
//lo siguiente borra la relación que tenga esa zona con los vendedores
$_tabla = "zonas_vend";
DataManager::deletefromtabla($_tabla, 'zona', $_nrozona);
}
header('Location: '.$backURL);
?><file_sep>/transfer/logica/ajax/getArticulos.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
//*************************************************
$laboratorio = (isset($_POST['laboratorio'])) ? $_POST['laboratorio'] : NULL;
$empresa = (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
$condicion = (isset($_POST['condicion'])) ? $_POST['condicion'] : NULL;
//*************************************************
if (empty($laboratorio)) {
echo '<table><tr><td align="center">Error al seleccionar el laboratorio</td></tr></table>'; exit;
}
if(!$condicion){
$articulos = DataManager::getArticulos(0, 0, FALSE, 1, $laboratorio, $empresa);
if (count($articulos)) {
echo '<table id="tblTablaArt" align="center">';
echo '<thead><tr align="left"><th>Id</th><th>Nombre</th><th>Precio</th></tr></thead>';
echo '<tbody>';
foreach ($articulos as $k => $art) {
$art = $articulos[$k];
$ean = $art["artcodbarra"];
$idArt = $art['artidart'];
$nombre = $art["artnombre"];
$precio = str_replace('"', '', json_encode($art["artpreciolista"])); $art["artpreciolista"];
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class=".$clase." onclick=\"javascript:dac_CargarArticulo('$idArt', '$ean', '$nombre', '$precio')\"><td>".$idArt."</td><td>".$nombre."</td><td>".$precio."</td></tr>";
}
echo '</tbody></table>';
exit;
} else {
echo '<table><tr><td align="center">No hay registros activos.</td></tr></table>'; exit;
}
}
?><file_sep>/condicion/logica/ajax/getArticulos.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$laboratorio = (isset($_POST['idlab'])) ? $_POST['idlab'] : NULL;
$empresa = (isset($_POST['idemp'])) ? $_POST['idemp'] : NULL;
if (!empty($laboratorio)) {
$articulos = DataManager::getArticulos(0, 1000, NULL, 1, $laboratorio, $empresa);
if (count($articulos)) {
echo '<table id="tblArticulos" border="0" align="center" style=\"table-layout:fixed\">';
echo '<thead><tr align="left"><th>Id</th><th>Nombre</th><th>Precio</th></tr></thead>';
echo '<tbody>';
foreach ($articulos as $k => $art) {
$art = $articulos[$k];
$id = $art['artid'];
$idArt = $art['artidart'];
$nombre = $art['artnombre'];
$precio = str_replace('"', '', json_encode($art["artprecio"]));
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr id=art".$id." class=".$clase." style=\"cursor:pointer;\" onclick=\"javascript:dac_cargarArticuloCondicion('$id', '$idArt', '$nombre', '$precio', '', '', '', ''); dac_alertaDuplicar()\"><td>".$idArt."</td><td>".$nombre."</td><td>".$precio."</td></tr>";
}
echo '</tbody></table>';
} else {
echo '<table><thead><tr><th align="center">No hay registros activos.</th></tr></thead></table>'; exit;
}
} else {
echo '<table><tr><th align="center">Error al seleccionar el laboratorio. </th></tr></table>'; exit;
}
?><file_sep>/acciones/logica/update.accion.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_acid = empty($_REQUEST['acid']) ? 0 : $_REQUEST['acid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/acciones/': $_REQUEST['backURL'];
$_nombre = $_POST['acnombre'];
$_sigla = $_POST['acsigla'];
$_SESSION['s_nombre'] = $_nombre;
$_SESSION['s_sigla'] = $_sigla;
if (empty($_nombre)) {
$_goURL = sprintf("/pedidos/acciones/editar.php?acid=%d&sms=%d", $_acid, 1);
header('Location:' . $_goURL);
exit;
}
if (empty($_sigla)) {
$_goURL = sprintf("/pedidos/acciones/editar.php?acid=%d&sms=%d", $_acid, 2);
header('Location:' . $_goURL);
exit;
}
$_acobject = ($_acid) ? DataManager::newObjectOfClass('TAccion', $_acid) : DataManager::newObjectOfClass('TAccion');
$_acobject->__set('Nombre', $_nombre);
$_acobject->__set('Sigla', $_sigla);
if ($_acid) {
$ID = DataManager::updateSimpleObject($_acobject);
} else {
$_acobject->__set('ID', $_acobject->__newID());
$_acobject->__set('Activa', 1);
$ID = DataManager::insertSimpleObject($_acobject);
}
unset($_SESSION['s_nombre']);
unset($_SESSION['s_sigla']);
header('Location:' . $backURL);
?><file_sep>/proveedores/logica/eliminar.archivo.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_archivo = empty($_REQUEST['archivo']) ? 0 : $_REQUEST['archivo'];
$_provid = empty($_REQUEST['provid']) ? 0 : $_REQUEST['provid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/proveedores/': $_REQUEST['backURL'];
if ($_provid) {
//Elimina documentación del proveedor
$dir = $_SERVER['DOCUMENT_ROOT']."/pedidos/login/registrarme/archivos/proveedor/".$_provid;
if (!@unlink($dir.'/'.$_archivo)) {
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d&sms=%d", $_provid, 13);
header('Location:' . $_goURL);
exit;
} else {
$_goURL = sprintf("/pedidos/proveedores/editar.php?provid=%d", $_provid);
header('Location:' . $_goURL);
exit;
}
}
header('Location: '.$backURL);
?><file_sep>/articulos/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$artId = empty($_REQUEST['artid']) ? 0 : $_REQUEST['artid'];
$artIdFamilia = '';
if ($artId) {
$artObject = DataManager::newObjectOfClass('TArticulo', $artId);
$artIdEmpresa = $artObject->__get('Empresa');
$artIdLab = $artObject->__get('Laboratorio');
$artIdArt = $artObject->__get('Articulo');
$artNombre = $artObject->__get('Nombre');
$artDescripcion = $artObject->__get('Descripcion');
$artPrecio = $artObject->__get('Precio');//PrecioART
$artGanancia = $artObject->__get('Ganancia');
$artPrecioLista = $artObject->__get('PrecioLista');
$artEan = $artObject->__get('CodigoBarra');
$artMedicinal = ($artObject->__get('Medicinal') == 'S') ? 1 : 0;
$artImagen = $artObject->__get('Imagen');
$imagenObject = DataManager::newObjectOfClass('TImagen', $artImagen);
$imagen = $imagenObject->__get('Imagen');
$img = ($imagen) ? "/pedidos/images/imagenes/".$imagen : "/pedidos/images/sin_imagen.png";
$artIdRubro = $artObject->__get('Rubro');
$artIdDispone = $artObject->__get('Dispone');
$artIdFamilia = $artObject->__get('Familia');
$artIdLista = $artObject->__get('Lista');
$artIva = ($artObject->__get('IVA') == 'S') ? 1 : 0;
$artFechaCompra = new DateTime($artObject->__get('FechaCompra'));
//Calcular Precios
if($artPrecio){
$artPrecioVenta = floatval($artPrecioLista)*floatval(1.450);
if($artIva == 0) {
$artPrecioVenta = $artPrecioVenta * floatval(1.210);
}
if($artMedicinal == 0){
$artPrecioVenta = $artPrecioVenta * floatval(1.210);
}
if($artIdEmpresa == 3){
if($artIva == 0) {
$artPrecioVenta = $artPrecioVenta * floatval(1.210);
}
if($artMedicinal == 1){
$artPrecioVenta = $artPrecioVenta * floatval(1.210);
}
}
if($artGanancia <> "0.00"){
$porcGanancia = ($artGanancia / 100) + 1;
$artPrecioVenta = $artPrecioVenta / $porcGanancia;
}
$artPrecioVenta = number_format($artPrecioVenta,2,'.','');
}
//consulta datos dispone
if($artIdDispone){
$dispObject = DataManager::newObjectOfClass('TArticuloDispone', $artIdDispone);
if($dispObject) {
$dispNombre = $dispObject->__get('NombreGenerico');
$dispVia = $dispObject->__get('Via');
$dispForma = $dispObject->__get('Forma');
$dispEnvase = $dispObject->__get('Envase');
$dispUnidad = $dispObject->__get('Unidades');
$dispCantidad = $dispObject->__get('Cantidad');
$dispUnidadMedida = $dispObject->__get('UnidadMedida');
$dispAccion = $dispObject->__get('Accion');
$dispUso = $dispObject->__get('Uso');
$dispNoUsar = $dispObject->__get('NoUsar');
$dispCuidadosPre = $dispObject->__get('CuidadosPre');
$dispCuidadosPost = $dispObject->__get('CuidadosPost');
$dispComoUsar = $dispObject->__get('ComoUsar');
$dispConservacion = $dispObject->__get('Conservacion');
$dispFechaUltVersion = $dispObject->__get('FechaUltVersion');
}
} else {
$dispNombre = $dispVia =
$dispForma = $dispEnvase =
$dispUnidad = $dispCantidad =
$dispUnidadMedida = $dispAccion =
$dispUso = $dispNoUsar =
$dispCuidadosPre = $dispCuidadosPost =
$dispComoUsar = $dispConservacion =
$dispFechaUltVersion = "";
}
} else {
$img = ($imagen) ? "/pedidos/images/imagenes/".$imagen : "/pedidos/images/sin_imagen.png";
$artGanancia = "0.00";
$artPrecioVenta =
$artPrecio =
$artMedicinal =
$artImagen =
$imagen =
$artIdLista =
$artIva =
$artIdDispone = 0;
$artIdEmpresa =
$artIdLab = $artIdArt =
$artNombre = $artDescripcion =
$artEan = $artIdRubro =
$dispNombre = $dispVia =
$dispForma = $dispEnvase =
$dispUnidad =
$dispCantidad = $dispUnidadMedida =
$dispAccion = $dispUso =
$dispNoUsar = $dispCuidadosPre =
$dispCuidadosPost = $dispComoUsar =
$dispConservacion = $dispFechaUltVersion =
$artFechaCompra = "";
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
<script language="javascript" type="text/javascript">
$(document).on('change','input[type="checkbox"]' ,function(e) {
if(this.id=="artiva" || this.id=="artmedicinal") {
dac_calcularPrecios();
}
});
$(document).on('change','input[id="artprecioVenta"]' ,function(e) {
dac_calcularPrecios();
});
$(document).on('change','input[id="artporcentaje"]' ,function(e) {
dac_calcularPrecios();
});
function dac_calcularPrecios(){
"use strict";
var iva = $("#artiva").prop('checked');
var medicinal = $('#artmedicinal').prop('checked');
var precioVenta = $('#artprecioVenta').val();
var empresa = $('#artidempresa').val();
var laboratorio = $('#artidlab').val();
var artId = $('#artidart').val();
var porcentaje = $('#artporcentaje').val();
$.ajax({
type : 'POST',
cache : false,
url : '/pedidos/articulos/logica/ajax/calcularPrecios.php',
data : {
artId : artId,
empresa : empresa,
laboratorio : laboratorio,
iva : iva,
medicinal : medicinal,
precioVenta : precioVenta,
porcentaje : porcentaje,
},
beforeSend : function () {
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
$('#box_cargando').css({'display':'none'});
if (result){
var results = result.split("/");
if(results.length === 1){
$('#box_error').css({'display':'block'});
$("#msg_error").html(results);
} else {
$('#artpreciolista').val(results[0]) ;
$('#artpreciocompra').val(results[1]);
$('#artprecioreposicion').val(results[2]);
$('#artprecio').val(results[3]) ;
}
} else {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
},
});
}
</script>
<script language="javascript" type="text/javascript">
//---------------------//
// Crea Div de Formula //
var nextFormula = 0;
function dac_cargarFormula(idForm, ifa, cant, medida, ifaComo, cantComo, medidaComo){
nextFormula++;
campo = '<div id="rutformula'+nextFormula+'">';
campo +='<input id="formId'+nextFormula+'" name="formId[]" value="'+idForm+'" hidden="hidden" >';
campo +='<div class="bloque_5"><label for="formIfa">IFA</label> <input id="formIfa'+nextFormula+'" name="formIfa[]" type="text" maxlength="10" value="'+ifa+'" ></div>';
campo +='<div class="bloque_8"><label for="formCant">Cant.</label><input id="formCant'+nextFormula+'" name="formCant[]" type="number" value='+cant+'></div>';
campo +='<div class="bloque_7"><label for="formMedida">Medida</label><input id="formMedida'+nextFormula+'" name="formMedida[]" type="text" value="'+medida+'" ></div>';
campo +='<div class="bloque_8"><br><input id="btmenos" type="button" value=" - " onClick="dac_deleteFormula('+nextFormula+')"></div>';
campo +='</div><hr>';
$("#tablaFormula").append(campo);
}
// Botón eliminar registro
function dac_deleteFormula(nextFormula){
elemento = document.getElementById('rutformula'+nextFormula);
elemento.parentNode.removeChild(elemento);
}
// Botón insertar registro
function dac_insertFormula(){
dac_cargarFormula('', '', '0', '', '', '0', '');
}
</script>
<script type ="text/javascript">
function dac_changeEmpresa(idEmpresa){
$('#artfamilia').find('option').remove();
$.getJSON('/pedidos/articulos/logica/json/getFamilia.php?idEmpresa='+idEmpresa, function(datos) {
idFamilias = datos;
$('#artfamilia').append("<option value='' selected></option>");
$.each( idFamilias, function( key, value ) {
var arr = value.split('-');
familia = document.getElementById('artfamilia').value;
if(arr[0] == familia){
$('#artfamilia').append("<option value='" + arr[0] + "' selected>" + arr[1] + "</option>");
} else {
$('#artfamilia').append("<option value='" + arr[0] + "'>" + arr[1] + "</option>");
}
});
});
dac_calcularPrecios();
}
</script>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "articulos";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<div class="box_body">
<form id="fmArticulo" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Artículo</legend>
<input type="hidden" name="artid" value="<?php echo $artId;?>" />
<div class="bloque_1" align="center">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
<fieldset id='box_informacion' class="msg_informacion">
<div id="msg_informacion" align="center"></div>
</fieldset>
</div>
<div class="bloque_1">
<?php $urlSend = '/pedidos/articulos/logica/update.articulo.php';?>
<img class="icon-send" onclick="javascript:dac_sendForm(fmArticulo, '<?php echo $urlSend;?>');"/>
</div>
<div class="bloque_5">
<label for="artidempresa">Empresa</label>
<select id="artidempresa" name="artidempresa" onchange="javascript:dac_changeEmpresa(this.value);"> <?php
$empresas = DataManager::getEmpresas(1);
if (count($empresas)) { ?>
<option value="" selected></option> <?php
foreach ($empresas as $k => $emp) {
$idEmp = $emp["empid"];
$nombreEmp = $emp["empnombre"];
if ($idEmp == $artIdEmpresa){ ?>
<option value="<?php echo $idEmp; ?>" selected><?php echo $nombreEmp; ?></option><?php
} else { ?>
<option value="<?php echo $idEmp; ?>"><?php echo $nombreEmp; ?></option><?php
}
}
} ?>
</select>
</div>
<div class="bloque_5">
<label for="artidlab">Laboratorio</label>
<select id="artidlab" name="artidlab" onchange="javascript:dac_calcularPrecios();"><?php
$laboratorios = DataManager::getLaboratorios();
if (count($laboratorios)) { ?>
<option value="" selected></option>
<?php
foreach ($laboratorios as $k => $lab) {
$idLab = $lab["idLab"];
$nombreLab = $lab["Descripcion"];
$selected = ($artIdLab == $idLab) ? "selected" : "";
?><option value="<?php echo $idLab; ?>" <?php echo $selected; ?> ><?php echo $nombreLab; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_8">
<label for="artidart">Artículo</label>
<input name="artidart" id="artidart" type="text" maxlength="10" value="<?php echo $artIdArt;?>"/>
</div>
<div class="bloque_2">
<label for="artnombre">Nombre</label>
<input name="artnombre" id="artnombre" type="text" maxlength="50" value="<?php echo $artNombre;?>" onkeypress="return dac_ValidarCaracteres(event)" />
</div>
<div class="bloque_5">
<label for="artrubro">Rubro</label>
<select name="artrubro"><?php
$rubros = DataManager::getRubros();
if (count($rubros)) { ?>
<option value="0" selected></option> <?php
foreach ($rubros as $k => $rub) {
$idRubro = $rub["IdRubro"];
$descripcion= $rub["Descripcion"];
$selected = ($idRubro == $artIdRubro) ? "selected" : "";
?><option value="<?php echo $idRubro; ?>" <?php echo $selected; ?> ><?php echo $descripcion; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_5">
<label for="artfamilia">Familia</label>
<select id="artfamilia" name="artfamilia">
<option value="0" selected></option> <?php
$familias = DataManager::getCodFamilias(0,0,$artIdEmpresa);
if (count($familias)) { ?>
<option value="" selected></option> <?php
foreach ($familias as $k => $flia) {
$idFlia = $flia["IdFamilia"];
$nombreFlia = $flia["Nombre"];
$selected = ($artIdFamilia == $idFlia) ? "selected" : ""; ?>
<option value="<?php echo $idFlia; ?>" <?php echo $selected; ?> ><?php echo $nombreFlia; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_5">
<label for="artlista">Lista</label>
<select name="artlista"><?php
$listas = DataManager::getListas();
if (count($listas)) { ?>
<option value="0" selected></option> <?php
foreach ($listas as $k => $list) {
$idLista = $list["IdLista"];
$nombreLista= $list["NombreLT"];
$selected = ($artIdLista == $idLista) ? "selected" : ""; ?>
<option value="<?php echo $idLista; ?>" <?php echo $selected; ?> ><?php echo $nombreLista; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_5">
<label for="artean">Código de Barras</label>
<input name="artean" id="artean" type="text" maxlength="20" value="<?php echo $artEan;?>"/>
</div>
<hr>
<div class="bloque_7">
<label for="artprecioVenta">Precio Venta Público</label>
<input name="artprecioVenta" id="artprecioVenta" type="text" maxlength="8" onkeydown="javascript:ControlComa(this.id, this.value);" onkeyup="javascript:ControlComa(this.id, this.value);" value="<?php echo $artPrecioVenta;?>">
</div>
<div class="bloque_8">
<label for="artporcentaje">% Gcia.</label>
<input id="artporcentaje" name="artporcentaje" type="text" maxlength="6" onkeydown="javascript:ControlComa(this.id, this.value);" onkeyup="javascript:ControlComa(this.id, this.value);" value="<?php echo $artGanancia;?>" >
</div>
<div class="bloque_7">
<label for="artprecio">Precio Artículo</label>
<input id="artprecio" name="artprecio" type="text" value="<?php echo $artPrecio;?>" readonly>
</div>
<div class="bloque_8">
<label for="artiva">IVA</label></br>
<input name="artiva" id="artiva" type="checkbox" <?php if($artIva){echo "checked='checked'";};?>>
</div>
<div class="bloque_8">
<label for="artmedicinal">Medicinal</label></br>
<input name="artmedicinal" id="artmedicinal" type="checkbox" <?php if($artMedicinal){echo "checked='checked'";};?> >
</div>
<div class="bloque_8">
<label for="artoferta">Oferta</label></br>
<input name="artoferta" id="artoferta" type="checkbox" checked >
</div>
<hr>
<div class="bloque_7">
<label for="artpreciocompra">Precio Compra</label>
<input id="artpreciocompra" name="artpreciocompra" type="text" readonly>
</div>
<div class="bloque_7">
<label for="artfechacompra">Fecha Compra</label>
<input name="artfechacompra" type="text" value="<?php if($artFechaCompra) { echo $artFechaCompra->format("d-m-Y"); } ?>" readonly>
</div>
<div class="bloque_7">
<label for="artpreciolista">Precio Lista</label>
<input id="artpreciolista" name="artpreciolista" type="text" readonly>
</div>
<div class="bloque_7">
<label for="artprecioreposicion">Precio Reposición</label>
<input id="artprecioreposicion" name="artprecioreposicion" type="text" readonly>
</div>
<?php
echo "<script>";
echo "javascript:dac_calcularPrecios();";
echo "</script>";
?>
<hr>
<div class="bloque_1">
<label for="artdescripcion">Descripción</label>
<textarea name="artdescripcion" id="artdescripcion" type="text" onkeyup="javascript:dac_LimitaCaracteres(event, 'artdescripcion', 240);" onkeydown="javascript:dac_LimitaCaracteres(event, 'artdescripcion', 240);" onkeypress="return dac_ValidarCaracteres(event)" value="<?php echo $artDescripcion;?>"/><?php echo $artDescripcion;?></textarea>
</div>
<div class="bloque_5">
<label for="imagen">Subir nueva imagen</label><br/>
<input name="artimagen" id="artimagen" type="text" value="<?php echo $artImagen;?>" hidden/>
<input name="imagen" class="file" type="file"/>
</div>
<div class="bloque_7">
<img src="<?php echo $img; ?>" alt="Imagen" width="100"/>
</div>
<div class="bloque_7">
La IMAGEN debe ser PNG y fondo transparente (preferentemente 384 x 295)
</div>
</fieldset>
<fieldset>
<legend>Dispone</legend>
<input name="artiddispone" type="text" value="<?php echo $artIdDispone;?>" hidden >
<div class="bloque_5">
<label for="artnombregenerico">Nombre Genérico</label>
<input name="artnombregenerico" type="text" maxlength="50" value="<?php echo $dispNombre;?>" onkeypress="return dac_ValidarCaracteres(event)" />
</div>
<div class="bloque_7">
<label for="artforma">Forma Farmacéutica</label>
<select name="artforma">
<?php //echo $dispForma; ?>
<option value="" selected></option>
<option value="gel" >Gel</option>
<option value="liquido" >Líquido</option>
<option value="solido" >Sólido</option>
<option value="shampoo" >Shampoo</option>
</select>
</div>
<div class="bloque_7">
<label for="artfechaultversion">Última Versión</label>
<input id="artfechaultversion" name="artfechaultversion" type="text" size="15" maxlength="10" value="<?php echo $dispFechaUltVersion;?>" />
</div>
<div class="bloque_7">
<label for="artvia">Vía</label>
<select name="artvia">
<?php //echo $dispVia; ?>
<option value="" selected></option>
<option value="oral" >Oral</option>
<option value="inhalatoria" >Inhalatoria</option>
<option value="nasal" >Nasal</option>
<option value="oftalmica" >Oftálmica</option>
<option value="oftalmica" >Oftálmica</option>
<option value="otica" >Ótica</option>
<option value="topica" >Tópica</option>
<option value="rectal" >Rectal</option>
<option value="vaginal" >Vaginal</option>
</select>
</div>
<div class="bloque_7">
<label for="artenvase">Envase</label>
<select name="artenvase">
<?php //echo $dispEnvase; ?>
<option value="" selected></option>
<option value="frasco">Frasco</option>
<option value="blister">Blister</option>
</select>
</div>
<div class="bloque_8">
<label for="artunidad">Unidad</label>
<input name="artunidad" type="number" value="<?php echo $dispUnidad;?>" />
</div>
<div class="bloque_8">
<label for="artcantidad">Cantidad</label>
<input name="artcantidad" type="number" value="<?php echo $dispCantidad;?>" />
</div>
<div class="bloque_7">
<label for="artmedida">Medida</label>
<select name="artmedida">
<?php //echo $dispUnidadMedida; ?>
<option value="" selected></option>
<option value="g">g</option>
<option value="mg">mg</option>
<option value="ml">ml</option>
</select>
</div>
<div class="bloque_1">
<label for="artaccion">Acción Terapéutica</label>
<input name="artaccion" type="text" maxlength="250" value="<?php echo $dispAccion;?>" onkeypress="return dac_ValidarCaracteres(event)" />
</div>
<div class="bloque_5">
<label for="artuso">Uso</label>
<textarea name="artuso" id="artuso" type="text" onkeyup="javascript:dac_LimitaCaracteres(event, 'artuso', 240);" onkeydown="javascript:dac_LimitaCaracteres(event, 'artuso', 240);" onkeypress="return dac_ValidarCaracteres(event)" value="<?php echo $dispUso;?>"/><?php echo $dispUso; ?></textarea>
</br>
<fieldset id='box_informacion' class="msg_informacion">
<div id="msg_informacion" align="center"></div>
</fieldset>
</div>
<div class="bloque_5">
<label for="artnousar">No Usar</label>
<textarea name="artnousar" id="artnousar" type="text" onkeyup="javascript:dac_LimitaCaracteres(event, 'artnousar', 240);" onkeydown="javascript:dac_LimitaCaracteres(event, 'artnousar', 240);" onkeypress="return dac_ValidarCaracteres(event)" value="<?php echo $dispNoUsar; ?>"/><?php echo $dispNoUsar; ?></textarea>
</br>
<fieldset id='box_informacion' class="msg_informacion">
<div id="msg_informacion" align="center"></div>
</fieldset>
</div>
<div class="bloque_5">
<label for="artcuidadospre">Cuidados Pre</label>
<textarea name="artcuidadospre" id="artcuidadospre" type="text" onkeyup="javascript:dac_LimitaCaracteres(event, 'artcuidadospre', 240);" onkeydown="javascript:dac_LimitaCaracteres(event, 'artcuidadospre', 240);" onkeypress="return dac_ValidarCaracteres(event)" value="<?php echo $dispCuidadosPre; ?>"/><?php echo $dispCuidadosPre;?></textarea>
</br>
<fieldset id='box_informacion' class="msg_informacion">
<div id="msg_informacion" align="center"></div>
</fieldset>
</div>
<div class="bloque_5">
<label for="artcuidadospost">Cuidados Post</label>
<textarea name="artcuidadospost" id="artcuidadospost" type="text" onkeyup="javascript:dac_LimitaCaracteres(event, 'artcuidadospost', 240);" onkeydown="javascript:dac_LimitaCaracteres(event, 'artcuidadospost', 240);" onkeypress="return dac_ValidarCaracteres(event)" value="<?php echo $dispCuidadosPost; ?>"/><?php echo $dispCuidadosPost; ?></textarea>
</br>
<fieldset id='box_informacion' class="msg_informacion">
<div id="msg_informacion" align="center"></div>
</fieldset>
</div>
<div class="bloque_5">
<label for="artcomousar">Cómo Usar?</label>
<textarea name="artcomousar" id="artcomousar" type="text" onkeyup="javascript:dac_LimitaCaracteres(event, 'artcomousar', 240);" onkeydown="javascript:dac_LimitaCaracteres(event, 'artcomousar', 240);" onkeypress="return dac_ValidarCaracteres(event)" value="<?php echo $dispComoUsar; ?>"/><?php echo $dispComoUsar; ?></textarea>
</br>
<fieldset id='box_informacion' class="msg_informacion">
<div id="msg_informacion" align="center"></div>
</fieldset>
</div>
<div class="bloque_5">
<label for="artconservacion">Conservación</label>
<input name="artconservacion" type="text" maxlength="250" value="<?php echo $dispConservacion; ?>" onkeypress="return dac_ValidarCaracteres(event)" />
</div>
</fieldset>
<fieldset id='tablaFormula'>
<legend>Fórmula</legend>
<input id="btnew" type="button" value=" + " onClick="dac_insertFormula()"><hr>
<?php
//Fórmula
if(isset($artIdDispone)){
$formulas = DataManager::getArticuloFormula( $artIdDispone );
if (count($formulas)) {
foreach ($formulas as $k => $form) {
$fmId = $form["afid"];
$fmIfa = $form["afifa"];
$fmCant = $form["afcantidad"];
$fmMedida = $form["afumedida"];
$fmIfaComo = $form["afifacomo"];
$fmCantComo = $form["afcantidadcomo"];
$fmMedidaComo = $form["afumedidacomo"];
echo "<script>";
echo "javascript:dac_cargarFormula('".$fmId."', '".$fmIfa."', '".$fmCant."', '".$fmMedida."', '".$fmIfaComo."', '".$fmCantComo."', '".$fmMedidaComo."');";
echo "</script>";
}
}
}?>
</fieldset>
</form>
</div> <!-- FIN box_body -->
<div class="box_seccion">
<div class="barra">
<h2>Presupuesto de Ventas</h2> <hr>
</div> <!-- Fin barra -->
<div class="lista">
</div> <!-- Fin listar -->
</div> <!-- Fin box_seccion -->
<hr>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html>
<script language="javascript" type="text/javascript">
new JsDatePick({
useMode: 2,
target:"artfechaultversion",
dateFormat:"%d-%M-%Y"
});
</script>
<file_sep>/droguerias/logica/update.drogueria.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$empresa = (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
//Id tabla drogueriaCAD para buscar los datos en tabla droguerías, columna drgdcadId
$drogCADId = (isset($_POST['drogid'])) ? $_POST['drogid'] : NULL;
$nombre = (isset($_POST['nombre'])) ? $_POST['nombre'] : NULL; // nombre drog CAD
// id tabla drogueria de la columna drogid
$drogCuentaId = (isset($_POST['drogtid'])) ? $_POST['drogtid'] : NULL;
$cuenta = (isset($_POST['drogtcliid'])) ? $_POST['drogtcliid'] : NULL; //cuenta relacionada
$correotrans = (isset($_POST['drogtcorreotrans'])) ? $_POST['drogtcorreotrans'] : NULL;
$tipotrans = (isset($_POST['drogttipotrans'])) ? $_POST['drogttipotrans'] : NULL;
$rentTl = (isset($_POST['rentTl'])) ? $_POST['rentTl'] : NULL;
$rentTd = (isset($_POST['rentTd'])) ? $_POST['rentTd'] : NULL;
if (empty($empresa)) {
echo "Seleccione una empresa."; exit;
}
if(empty($nombre)){
echo "Indique el nombre de la droguería."; exit;
}
if(empty($cuenta) || !is_numeric($cuenta)){
echo "Indique un número de cuenta de droguería."; exit;
} else {
//controlar que la cuenta exista
$ctaId = DataManager::getCuenta('ctaid', 'ctaidcuenta', $cuenta, $empresa);
if(empty($ctaId)){
echo "La cuenta indicada no existe registrada en ésta empresa."; exit;
}
//controlar que la cuenta no esté ya cargada
if(empty($drogCuentaId)){
$drogId = DataManager::getDrogueria(NULL, $empresa, NULL, NULL, $cuenta);
if($drogId){
echo "La cuenta indicada ya existe registrada."; exit;
}
}
}
if (empty($correotrans) || !preg_match( "/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,4})$/", $correotrans )) {
echo "El correo transfer es incorrecto."; exit;
}
if (empty($tipotrans) || is_numeric($tipotrans)) {
echo "Indique el tipo de transfer."; exit;
}
if (empty($rentTl) || !is_numeric($rentTl)) {
echo "Indique la rentabilidad TL correcta."; exit;
}
if (empty($rentTd) || !is_numeric($rentTd)) {
echo "Indique la rentabilidad TD correcta."; exit;
}
//drogueriasCAD
$objectDrogCAD = ($drogCADId) ? DataManager::newObjectOfClass('TDrogueriaCAD', $drogCADId) : DataManager::newObjectOfClass('TDrogueriaCAD');
$objectDrogCAD->__set('Empresa' , $empresa);
$objectDrogCAD->__set('Nombre' , strtoupper($nombre));
$objectDrogCAD->__set('LastUpdate' , date("Y-m-d H:m:s"));
$objectDrogCAD->__set('UserUpdate' , $_SESSION["_usrid"]);
if ($drogCADId) { //UPDATE
DataManagerHiper::updateSimpleObject($objectDrogCAD, $drogCADId);
DataManager::updateSimpleObject($objectDrogCAD);
$IDCad = $drogCADId;
// MOVIMIENTO //
$movTipo = 'UPDATE';
} else { //INSERT
$objectDrogCAD->__set('ID' , $objectDrogCAD->__newID());
$objectDrogCAD->__set('Activa' , 1);
DataManagerHiper::_getConnection('Hiper'); //Controla conexión a HiperWin
$IDCad = DataManager::insertSimpleObject($objectDrogCAD);
DataManagerHiper::insertSimpleObject($objectDrogCAD, $IDCad);
// MOVIMIENTO //
$movTipo = 'INSERT';
}
$movimiento = 'drogCADId';
dac_registrarMovimiento($movimiento, $movTipo, 'TDrogueriaCAD', $IDCad);
//-----------------//
//droguerias
$objectDrog = ($drogCuentaId) ? DataManager::newObjectOfClass('TDrogueria', $drogCuentaId) : DataManager::newObjectOfClass('TDrogueria');
$objectDrog->__set('IDEmpresa' , $empresa);
$objectDrog->__set('Cliente' , $cuenta);
$objectDrog->__set('CorreoTransfer' , $correotrans);
$objectDrog->__set('TipoTransfer' , $tipotrans);
$objectDrog->__set('RentabilidadTL' , $rentTl);
$objectDrog->__set('RentabilidadTD' , $rentTd);
$objectDrog->__set('CadId' , $IDCad); // = $drogCADId
if ($drogCuentaId) { //UPDATE
DataManagerHiper::updateSimpleObject($objectDrog, $drogCuentaId);
DataManager::updateSimpleObject($objectDrog);
// MOVIMIENTO //
$movTipo = 'UPDATE';
} else { //INSERT
$objectDrog->__set('CorreoAbm' , $correotrans);
$objectDrog->__set('TipoAbm' , $tipotrans);
$objectDrog->__set('ID', $objectDrog->__newID());
$objectDrog->__set('Activa', 1);
DataManagerHiper::_getConnection('Hiper'); //Controla conexión a HiperWin
$drogCuentaId = DataManager::insertSimpleObject($objectDrog);
DataManagerHiper::insertSimpleObject($objectDrog, $drogCuentaId);
// MOVIMIENTO //
$movTipo = 'INSERT';
}
$movimiento = 'drogId';
dac_registrarMovimiento($movimiento, $movTipo, 'TDrogueria', $drogCuentaId);
echo 1; exit;
?><file_sep>/soporte/mensajes/logica/update.mensaje.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
echo "SU SESIÓN HA EXPIRADO."; exit;
}
$tkid = empty($_POST['tkid']) ? 0 : $_POST['tkid'];
$idSector = empty($_POST['tkidsector']) ? 0 : $_POST['tkidsector'];
$idMotivo = empty($_POST['tkidmotivo']) ? "" : $_POST['tkidmotivo'];
$mensaje = empty($_POST['tkmensaje']) ? "" : $_POST['tkmensaje'];
$estado = empty($_POST['tkestado']) ? "" : $_POST['tkestado'];
$usrCreated = empty($_POST['usrCreated']) ? "" : $_POST['usrCreated'];
//$correo = empty($_POST['tkcopia']) ? "" : $_POST['tkcopia'];
if (empty($idSector)) {
echo "Error al seleccionar un motivo de consulta."; exit;
}
if (empty($idMotivo)) {
echo "Seleccione un motivo de servicio."; exit;
}
if (empty($mensaje)) {
echo "Indique un mensaje."; exit;
}
$imagenNombre = $_FILES["imagen"]["name"];
$imagenPeso = $_FILES["imagen"]["size"];
if ($imagenPeso != 0){
if($imagenPeso > MAX_FILE){
echo "El archivo no debe superar los 4 MB"; exit;
}
}
if ($imagenPeso != 0){
if(dac_fileFormatControl($_FILES["imagen"]["type"], 'imagen')){
$ext = explode(".", $imagenNombre);
$name = dac_sanearString($ext[0]);
} else {
echo "La imagen debe ser .JPG o .PDF"; exit;
}
}
$objectMsg = DataManager::newObjectOfClass('TTicketMensaje');
$objectMsg->__set('IDTicket' , $tkid);
$objectMsg->__set('Descripcion' , $mensaje);
$objectMsg->__set('UsrCreated' , $_SESSION["_usrid"]);
$objectMsg->__set('DateCreated' , date("Y-m-d H:m:s"));
$objectMsg->__set('Activo' , 1);
$objectMsg->__set('ID' , $objectMsg->__newID());
$IDMsg = DataManager::insertSimpleObject($objectMsg);
if($usrCreated == $_SESSION["_usrid"]){
//Si es el mismo que lo creó, se envía un mail al responsable del sector
switch($estado){
case 0: //RESPONDIDO
$estado = 1;
break;
case 1: //ACTIVO
$estado = 1;
break;
}
} else {
//Si es distinto, se envía un mail al creador
switch($estado){
case 1: //ACTIVO
$estado = 2;
break;
case 0: //RESPONDIDO
$estado = 2;
break;
}
}
$objectTicket = DataManager::newObjectOfClass('TTicket', $tkid);
$objectTicket->__set('Estado' , $estado); //1 ACTIVO //0 RESPONDIDO
$objectTicket->__set('UsrUpdate' , $_SESSION["_usrid"]);
$objectTicket->__set('LastUpdate' , date("Y-m-d H:m:s"));
$IDTicket = DataManager::updateSimpleObject($objectTicket);
//**********//
// CORREO //
//**********//
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$sectores = DataManager::getTicketSector();
foreach( $sectores as $k => $sec ) {
$id = $sec['tksid'];
if($id == $idSector){
$sector = $sec['tksnombre'];
}
}
$headMail = '
<html>
<head>
<title>CONSULTA Nro. '.$tkid.'</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 580px;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>';
$pieMail = '
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Gracias por confiar en nosotros.<br/>
Le saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">' . $pie . '</td>
</tr>
</table>
<div/>
</body>
</html>
';
if($usrCreated != $_SESSION["_usrid"]){
//*******************
$mail->From = "<EMAIL>";
$mail->FromName = "Soporte Neo-farma";
$mail->Subject = "Respuesta a tu consulta Nro: ". $tkid;
$cuerpoMail_1 = '
<body>
<div align="center">
<table width="580" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Nuestro equipo de soporte respondió a tu consulta Nro. '.$tkid.'<br/><br/>
<div />
</td >
</tr>
<tr>
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight:bold; background-color:#117db6">
<strong>Detalles:</strong>
</div>
</td>
</tr>
';
$cuerpoMail_2 = '
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Sector </th>
<td align="left" width="400"> '.$sector.' </td>
</tr>
<tr>
<th align="left" width="200"> Detalles </th>
<td align="left" width="400"> '.$mensaje.' </td>
</tr>
</table>
</div>
</td>
</tr>
';
$usrEmail = DataManager::getUsuario('uemail', $usrCreated);
$mail->AddAddress($usrEmail);
} else {
//*******************
$mail->From = "<EMAIL>";
$mail->FromName = "Consulta a Soporte Neo-farma";
$mail->Subject = "Tiene la consulta Nro: " . $tkid . "pendiente.";
$cuerpoMail_1 = '
<body>
<div align="center">
<table width="580" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Nueva consulta Nro. '.$tkid.'<br/><br/>
<div />
</td >
</tr>
<tr>
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight:bold; background-color:#117db6">
<strong>Detalles:</strong>
</div>
</td>
</tr>
';
$cuerpoMail_2 = '
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Sector </th>
<td align="left" width="400"> '.$sector.' </td>
</tr>
</table>
</div>
</td>
</tr>
';
//email al responsable del sector
$motivos = DataManager::getTicketMotivos();
if (count($motivos)) {
foreach ($motivos as $k => $mot) {
$id = $mot['tkmotid'];
$usrResponsable = $mot['tkmotusrresponsable'];
if($id == $idMotivo){
$usrEmail = DataManager::getUsuario('uemail', $usrResponsable);
$mail->AddAddress($usrEmail);
}
}
}
}
$cuerpoMail = $headMail.$cuerpoMail_1.$cuerpoMail_2.$pieMail;
$mail->msgHTML($cuerpoMail);
$mail->AddBCC("<EMAIL>");
if($mail){
if(!$mail->Send()) {
echo 'Fallo en el envío de notificación por mail'; exit;
}
}
echo "1"; exit;
?><file_sep>/articulos/logica/ajax/getFiltroArticulos.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO. A</td></tr></table>'; exit;
}
$field = (isset($_POST['tipo'])) ? $_POST['tipo'] : NULL;
$filtro = (isset($_POST['filtro'])) ? $_POST['filtro'] : '';
if(empty($filtro)){
echo "Debe indicar un texto para filtrar la búsqueda"; exit;
} else {
$filtro = '%'.$filtro.'%';
}
//------------------------------------
$articulos = DataManager::getArticuloAll('*', $field, $filtro);
echo "<table id=\"tblFiltroArticulos\" >";
if (count($articulos)) {
echo "<thead><tr align=\"left\" width=\"20%\"><th>Emp</th><th width=\"15%\">Art</th><th width=\"40%\">Nombre</th><th width=\"15%\">Laboratorio</th><th width=\"15%\"></th></tr></thead>";
echo "<tbody>";
foreach ($articulos as $k => $art) {
$id = $art['artid'];
$idArticulo = $art['artidart'];
$idEmpresa = $art['artidempresa'];
$empresa = substr(DataManager::getEmpresa('empnombre', $idEmpresa), 0, 3);
$idLaboratorio = $art['artidlab'];
$laboratorio = DataManager::getLaboratorio('Descripcion', $idLaboratorio);
$nombre = $art['artnombre'];
$_editar = sprintf( "onclick=\"window.open('editar.php?artid=%d')\" style=\"cursor:pointer;\"",$id);
/*$_status = ($art['artactivo']) ? "<img class=\"icon-status-active\" title=\"Desactivar\"/>" : "<img class=\"icon-status-inactive\" title=\"Activar\"/>";
$_borrar = sprintf( "<a href=\"logica/changestatus.php?artid=%d\" title=\"borrar articulo\">%s</a>", $art['artid'], $_status);*/
$_status = ($art['artactivo']) ? "<a title=\"Activo\" onclick=\"javascript:dac_changeStatus('/pedidos/articulos/logica/changestatus.php', $id)\"> <img class=\"icon-status-active\"/></a>" : "<a title=\"Inactivo\" onclick=\"javascript:dac_changeStatus('/pedidos/articulos/logica/changestatus.php', $id)\"> <img class=\"icon-status-inactive\" /></a>";
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class=".$clase.">";
echo "<td ".$_editar.">".$empresa."</td><td ".$_editar.">".$idArticulo."</td><td ".$_editar.">".$nombre."</td><td ".$_editar.">".$laboratorio."</td><td align=\"center\">".$_status."</td>";
echo "</tr>";
}
} else {
echo "<tbody>";
echo "<thead><tr><th colspan=\"5\" align=\"center\">No hay registros relacionadas</th></tr></thead>"; exit;
}
echo "</tbody></table>";
?><file_sep>/droguerias/logica/update.lista.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
//Id tabla drogueriaCAD para buscar los datos en tabla droguerías, columna drgdcadId
$drogCADId = (isset($_POST['drogid'])) ? $_POST['drogid'] : NULL;
$nombre = (isset($_POST['nombre'])) ? $_POST['nombre'] : NULL; // nombre drog CAD
// id tabla drogueria de la columna drogid
$drogCuentaId = (isset($_POST['drogtid'])) ? $_POST['drogtid'] : NULL;
$rentTl = (isset($_POST['rentTl'])) ? $_POST['rentTl'] : NULL;
$rentTd = (isset($_POST['rentTd'])) ? $_POST['rentTd'] : NULL;
if(empty($drogCADId) || empty($nombre)){
echo "Indique datos de la droguería."; exit;
}
if($drogCADId){
//drogueriasCAD
$objectDrogCAD = DataManager::newObjectOfClass('TDrogueriaCAD', $drogCADId);
$objectDrogCAD->__set('Nombre' , strtoupper($nombre));
$objectDrogCAD->__set('LastUpdate' , date("Y-m-d H:m:s"));
$objectDrogCAD->__set('UserUpdate' , $_SESSION["_usrid"]);
DataManagerHiper::updateSimpleObject($objectDrogCAD, $drogCADId);
DataManager::updateSimpleObject($objectDrogCAD);
//--------------//
// MOVIMIENTO //
$movimiento = 'drogCADId';
$tipoMov = 'UPDATE';
dac_registrarMovimiento($movimiento, $tipoMov, 'TDrogueriaCAD', $drogCADId);
if(count($drogCuentaId) > 0){
for($k=0; $k < count($drogCuentaId); $k++){
//-----------------//
// UPDATE droguerias
$objectDrog = DataManager::newObjectOfClass('TDrogueria', $drogCuentaId[$k]);
$objectDrog->__set('RentabilidadTL' , $rentTl[$k]);
$objectDrog->__set('RentabilidadTD' , $rentTd[$k]);
DataManagerHiper::updateSimpleObject($objectDrog, $drogCuentaId[$k]);
DataManager::updateSimpleObject($objectDrog);
}
//--------------//
// MOVIMIENTO //
$movimiento = 'drogId';
$tipoMov = 'UPDATE';
dac_registrarMovimiento($movimiento, $tipoMov, 'TDrogueria', $drogCADId);
}
} else {
echo "Error al intentar actualizar los datos."; exit;
}
echo 1; exit;
?><file_sep>/usuarios/logica/eliminar.usuario.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_uid = empty($_REQUEST['uid']) ? 0 : $_REQUEST['uid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/usuarios/': $_REQUEST['backURL'];
if ($_uid) {
$_uobject = DataManager::newObjectOfClass('TUsuario', $_uid);
$_uobject->__set('ID', $_uid );
$ID = DataManager::deleteSimpleObject($_uobject);
//lo siguiente borra las zonas que pueda tener el vendedor
$_tabla = "zonas_vend";
DataManager::deletefromtabla($_tabla, 'uid', $_uid);
}
header('Location: '.$backURL);
?><file_sep>/transfer/gestion/abmtransfer/logica/ajax/duplicar.abm.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$_mes = empty($_POST['mes']) ? date("m") : $_POST['mes'];
$_anio = empty($_POST['anio']) ? date("Y") : $_POST['anio'];
$_mes_sig = $_POST['mes_sig'];
$_anio_sig = $_POST['anio_sig'];
$_drogid = $_POST['drogid'];
$_toAll = $_POST['toAll'];
if(empty($_mes_sig) || empty($_anio_sig)){echo "Error al cargar el mes o año de destino."; exit;}
if(($_anio == $_anio_sig) && ($_anio_sig == $_mes)){echo "El mes y año deben ser diferentes al ABM a suplicar."; exit;}
if($_toAll == 0){ //duplico solo la droguería en custión al mes y anio indicado
//borro cualquier registro que encuentre en el mes y anio siguiente
$_abms_siguientes = DataManager::getDetalleAbm($_mes_sig, $_anio_sig, $_drogid, 'TL');
if ($_abms_siguientes) {
foreach ($_abms_siguientes as $k => $_abmsig){
$_abmsig = $_abms_siguientes[$k];
$_abmsigID = $_abmsig['abmid'];
$_abmobject = DataManager::newObjectOfClass('TAbm', $_abmsigID);
$_abmobject->__set('ID', $_abmsigID );
$ID = DataManager::deleteSimpleObject($_abmobject);
}
}
//Recorro la abm actual para grabarla en la abm siguiente como nueva
$_abms = DataManager::getDetalleAbm($_mes, $_anio, $_drogid, 'TL');
if ($_abms) {
foreach ($_abms as $k => $_abm){
$_abm = $_abms[$k];
$_abmID = $_abm['abmid'];
//Creo el objeto nuevo para cargar la abm nueva
$_abmobjectcopy = DataManager::newObjectOfClass('TAbm');
$_abmobjectcopy->__set('Drogueria' , $_abm['abmdrogid']);
$_abmobjectcopy->__set('Tipo' , 'TL');
$_abmobjectcopy->__set('Mes' , $_mes_sig);
$_abmobjectcopy->__set('Anio' , $_anio_sig);
$_abmobjectcopy->__set('Articulo' , $_abm['abmartid']);
$_abmobjectcopy->__set('Descuento' , $_abm['abmdesc']);
$_abmobjectcopy->__set('Plazo' , $_abm['abmcondpago']);
$_abmobjectcopy->__set('Diferencia' , $_abm['abmdifcomp']);
$_abmobjectcopy->__set('Empresa' , 1);
$_abmobjectcopy->__set('Activo' , 0);
//Inserto la abm nueva
$_abmobjectcopy->__set('ID', $_abmobjectcopy->__newID());
$ID = DataManager::insertSimpleObject($_abmobjectcopy);
}
//**********************//
//Registro de movimiento//
//**********************//
$movimiento = 'ABM_TL_DUPLICATE_DROG_'.$_drogid."_".$_mes."-".$_anio."_TO_".$_mes_sig."-".$_anio_sig;
$movTipo = 'INSERT';
dac_registrarMovimiento($movimiento, $movTipo, "TAbm");
echo "1"; exit;
}
} else { //Duplica el abm a todas las droguerías existentes como transfers al mes y anio indicado
$_droguerias = DataManager::getDrogueria('');
if ($_droguerias) {
foreach ($_droguerias as $j => $_drogueria){
$_drogueria = $_droguerias[$j];
$_drogueriaID = $_drogueria['drogtcliid'];
//borro cualquier registro que encuentre en el mes y anio siguiente de la droguería.
$_abms_siguientes = DataManager::getDetalleAbm($_mes_sig, $_anio_sig, $_drogueriaID, 'TL');
if ($_abms_siguientes) {
foreach ($_abms_siguientes as $k => $_abmsig){
$_abmsig = $_abms_siguientes[$k];
$_abmsigID = $_abmsig['abmid'];
$_abmobject = DataManager::newObjectOfClass('TAbm', $_abmsigID);
$_abmobject->__set('ID', $_abmsigID );
$ID = DataManager::deleteSimpleObject($_abmobject);
}
}
//Recorro la abm actual de cada droguería para grabarla en la abm de la dorgueria
$_abms = DataManager::getDetalleAbm($_mes, $_anio, $_drogueriaID, 'TL'); //$_drogid ==> esta es si quiero que la drogueria seleccionada se copie a todas las droguerias por igual.
if ($_abms) {
foreach ($_abms as $k => $_abm){
$_abm = $_abms[$k];
$_abmID = $_abm['abmid'];
//Creo el objeto nuevo para cargar la abm nueva
$_abmobjectcopy = DataManager::newObjectOfClass('TAbm');
$_abmobjectcopy->__set('Drogueria', $_drogueriaID);
$_abmobjectcopy->__set('Tipo' , 'TL');
$_abmobjectcopy->__set('Mes', $_mes_sig);
$_abmobjectcopy->__set('Anio', $_anio_sig);
$_abmobjectcopy->__set('Articulo', $_abm['abmartid']);
$_abmobjectcopy->__set('Descuento', $_abm['abmdesc']);
$_abmobjectcopy->__set('Plazo', $_abm['abmcondpago']);
$_abmobjectcopy->__set('Diferencia',$_abm['abmdifcomp']);
$_abmobjectcopy->__set('Empresa' , 1);
$_abmobjectcopy->__set('Activo' , 0);
//Inserto la abm nueva a cada drogueria
$_abmobjectcopy->__set('ID', $_abmobjectcopy->__newID());
$ID = DataManager::insertSimpleObject($_abmobjectcopy);
}
}
}
//**********************//
//Registro de movimiento//
//**********************//
$movimiento = 'ABM_TL_DUPLICATE_TO_ALL_DROG_'.$_drogid."__".$_mes."-".$_anio."_TO_".$_mes_sig."-".$_anio_sig;
$movTipo = 'INSERT';
dac_registrarMovimiento($movimiento, $movTipo, "TAbm");
echo "1"; exit;
}
}
echo "Error. No hay datos de ABM en la página actual para duplicar.";
?><file_sep>/agenda/ajax/getEvents.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//--------------------------------------------------------------------------------------------//
// This script reads event data from a JSON file and outputs those events which are within the range//
// supplied by the "start" and "end" GET parameters.
//
// An optional "timezone" GET parameter will force all ISO8601 date stings to a given timezone.
//
// Requires PHP 5.2.0 or higher.
//--------------------------------------------------------------------------------------------------//
// Require our Event class and datetime utilities
//require dirname(__FILE__) . '/utils.php';
date_default_timezone_set('UTC');
// Short-circuit if the client did not give us a date range.
/*
No se cómo pasar las variables desde y hasta para hacer dinámico por mes (o años!)
if (!isset($_GET['start']) || !isset($_GET['end'])) {
die("Please provide a date range."); exit;
}
$range_start = date('Y-m-d h:m', $_GET['start']);
$range_end = date('Y-m-d h:m', $_GET['end']);
$range_start = '2016-12-03 00:00';
$range_end = '2017-01-19 00:00';*/
// Analiza el parámetro de zona horaria si está presente.
/*$timezone = NULL;
if (isset($_GET['timezone'])) {
$timezone = new DateTimeZone($_GET['timezone']);
}*/
//ACÁ DEBO LEER LA BASE DE DATOS Select all from ssbb where fecha BETWEEN fecha inicio AND fecha Fin
$eventos = DataManager::getEventos($_SESSION["_usrid"]); //, $range_start, $range_end
if ($eventos){
$input_arrays = array();
foreach ($eventos as $k => $even) {
//Si el EVENTO solo tiene START, es un evento de todo un día.
$ideven = $even["agid"]; //"id": "999",
$title = $even["agtitle"]; //"title": "Long Event",
$texto = $even["agtexto"];
$url = $even["agurl"];
$start = $even["agstartdate"]; //"start": "2016-12-07", //"start": "2016-12-09T16:00:00-05:00"
$end = $even["agenddate"]; //"end": "2016-12-10", //
$color = $even["agcolor"];
$restringido = $even["agrestringido"]; //(empty($even["agrestringido"])) ? NULL : "Restringido";
//$tipo = $even["agrectype"];
//"url": "http://google.com/"
//EVENTO ALL DAY --> Cuando FECHA INICIO O FIN no tiene horas seteadas,
//les quito esa parte del string para que reconozca como EVENTO ALL DAY
if(substr($start, 11, 18) == '00:00:00'){
$start = substr($start, 0, 10);
}
if(substr($end, 11, 18) == '00:00:00'){
$end = substr($end, 0, 10);
}
//****************//
//Si la fecha de inicio o fin no tienen hora, se supone que es un evento de TODO EL DIA
if(strlen($start) == 10 || strlen($end) == 10){
//ALL DAY --> CUANDO NO TIENE HORA:MINUTO
if($end == "0000-00-00"){
//ALL DAY para un solo día
$array = array(
"id" => $ideven,
"title" => $title,
"texto" => $texto,
"url" => $url,
"start" => $start,
"color" => $color,
"constraint" => $restringido,
//Un evento de TODO EL DIA implica no tener fecha de FIN, para que funcione, no debe cargarse en el array
//if(!empty($end)) {"end" => $end,} // substr($end, 0, 10)
);
} else {
//ALL DAY desde INICIO hasta un día antes del FIN (por que sería HASTA las 00:01 del último día)
$array = array(
"id" => $ideven,
"title" => $title,
"texto" => $texto,
"url" => $url,
"start" => $start,
"end" => $end,
"color" => $color,
"constraint" => $restringido,
);
}
} else {
$array = array(
"id" => $ideven,
"title" => $title,
"texto" => $texto,
"url" => $url,
"start" => $start,
"end" => $end,
"color" => $color,
"constraint" => $restringido,
);
}
//Cargo el array de eventos para la Agenda
array_push($input_arrays, $array);
}
//CODIGO PARA PRUEBAS
/*$array = array(
"id" => 999,
"title" => 'All Day Event',
"start" => '2017-01-07',
"end" => '2017-01-10',
//"color" => '#ff9f89', //COLOR DEL EVENTO
//"backgroundColor" => '#ff9f89', //COLOR DE FONDO DE ¿TEXTO? del EVENTO, que es casi lo mismo que color
//borderColor
//textColor
//className
//editable
//startEditable
//start, end, callback
//--------------
//title/allDay/start/end/url
);
array_push($input_arrays, $array);*/
//*******************
}
// Send JSON to the client.
echo json_encode($input_arrays);
/*events: [
//PAra que el evento sea ALL DAY NO DEBE TENER HORAS Y MINUTOS
{
id: 1,
title: 'All Day Event',
start: '2016-12-01'
},
{
id: 2,
title: 'Long Event',
start: '2016-12-07',
end: '2016-12-10'
},
//Si no se carga horario, será todo el día.
//Si carga horas, tendrá también hora de inicio y fin
{
title: 'Conference',
start: '2016-12-11',
end: '2016-12-13'
},
//Evento repetido sería si se repite el id!!!
//Este ejemplo no se va a utilizar ya que en ddbb Agenda no permite repetir ID
{
id: 999,
title: 'Repeating Event',
start: '2016-12-09T16:00:00',
},
{
id: 999,
title: 'Repeating Event',
start: '2016-12-16T16:00:00'
},
// rendering: AREA MARCADA EN COLOR DE FONDO, NO DEL EVENTO
// overlap: NO SE PUEDEN ARRASTRAR EVENTOS (aunque sí crearlos)
// Si se realiza con hora y minuto, no se verá en el mensual, sino que solo donde corresponda
{
start: '2016-12-24',
end: '2016-12-28',
overlap: false, //No permite que otros evento, se coloquen en el día donde está éste
rendering: 'background', //Hace que todo el día tenga color de fonto "color" //Sin ésto, el color de fondo irá al evento solamente.
color: '#ff9f89'
},
//constraint: NO PERMITE MOVERLO DE FECHA Y HORA
//NULL si se quiere que no se tenga en cuenta d
{
title: 'Meeting',
start: '2016-12-12T10:30:00',
end: '2016-12-12T12:30:00',
//restricción para una reunión.
//ESTO PODRÍA USARSE TAMBIÉN COMO FERIADOS??
constraint: 'availableForMeeting', // defined below
color: '#257e4a'
},
// El evento linkéa a la página que se indicó
{
title: 'Click for Google',
url: 'http://google.com/',
start: '2016-12-28'
}
],*/
<file_sep>/pedidos/logica/ajax/generarPedido.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M") {
echo 'SU SESION HA EXPIRADO.'; exit;
}
//----------------------------------
//SE AGREGA ARTICULO PROMOCIONAL OBLIGATORIO A LAS SIGUIENTES CUENTAS CON
//se aplica aquí y en editar.cadena.php
//categoría sea <> 1 (distintas de droguerías) AND
$categoria = DataManager::getCuenta('ctacategoriacomercial', 'ctaidcuenta', $idCuenta, $empresa);
//empresa == 1 AND
//$idCondComercial <> de ListaEspecial DR AHORRO, FARMACITY, FARMACITY 2
// originalmente $idCondComercial != 1764 && $idCondComercial != 1765 && $idCondComercial != 1761
$condBonificar = 0;
$condiciones = DataManager::getCondiciones(0, 0, 1, $empresa, $laboratorio, NULL, NULL, NULL, NULL, $idCondComercial);
if (count($condiciones) > 0) {
foreach ($condiciones as $i => $cond) {
$condTipo = $cond['condtipo'];
$condNombre = $cond['condnombre'];
if($condTipo == 'ListaEspecial' && ($condNombre == 'DR AHORRO' || $condNombre == 'FARMACITY' || $condNombre == 'FARMACITY 2')){
$condBonificar = 1;
}
}
}
if($empresa == 1 && $categoria <> 1 && $laboratorio == 1 && $condBonificar == 0){
array_unshift ( $articulosIdArt , 3801 );
array_unshift ( $articulosCant , 1 );
array_unshift ( $articulosPrecio, 0 );
array_unshift ( $articulosB1 , 0 );
array_unshift ( $articulosB2 , 0 );
array_unshift ( $articulosD1 , 0 );
array_unshift ( $articulosD2 , 0 );
}
//-------------------------------------
//TIPO DE PEDIDOS ADMINISTRACIÓN PARA VALES, SALIDAS PROMOCION, ETC
$nombre = '';
$provincia = '';
$localidad = '';
$direccion = '';
$cp = '';
$telefono = '';
if($tipoPedido == 'PARTICULAR') {
$nombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $idCuenta, $empresa);
$idProv = DataManager::getCuenta('ctaidprov', 'ctaidcuenta', $idCuenta, $empresa);
$provincia = DataManager::getProvincia('provnombre', $idProv);
$idLoc = DataManager::getCuenta('ctaidloc', 'ctaidcuenta', $idCuenta, $empresa);
$localidad = DataManager::getLocalidad('locnombre', $idLoc);
$domicilio = DataManager::getCuenta('ctadireccion', 'ctaidcuenta', $idCuenta, $empresa);
$numero = DataManager::getCuenta('ctadirnro', 'ctaidcuenta', $idCuenta, $empresa);
$piso = DataManager::getCuenta('ctadirpiso', 'ctaidcuenta', $idCuenta, $empresa);
$dpto = DataManager::getCuenta('ctadirdpto', 'ctaidcuenta', $idCuenta, $empresa);
$direccion = $domicilio.' '.$numero.' '.$piso.' '.$dpto;
$direccion = str_replace(" ", " ", $direccion);
$cp = DataManager::getCuenta('ctacp', 'ctaidcuenta', $idCuenta, $empresa);
$telefono = DataManager::getCuenta('ctatelefono', 'ctaidcuenta', $idCuenta, $empresa);
}
$items = 0;
$maxItems = ($empresa == 3) ? 8 : 14; // Máxima can de Items por Pedido //
$limiteContado = MONTO_MINIMO - (MONTO_MINIMO * PORC_RETENCION); // CONTADO Limita por % Retención //
$contado = 0; //($condPago == 3 || $condPago == 5) ? 1 : 0 ;
$limiteFactura = ($contado) ? $limiteContado : MONTO_MAXIMO;
$nroPedido = 0;
$precioArt = 0;
$totalFactura = 0;
$cantFacturas = 0;
$ultimaFactura = 0;
$contadorFacturas = 0; // control
unset($IdPedido);
for($i = 0; $i < count($articulosIdArt); $i++){
$cant = $articulosCant[$i];
$idArt = $articulosIdArt[$i];
$b1 = empty($articulosB1[$i]) ? 0 : $articulosB1[$i];
$b2 = empty($articulosB2[$i]) ? 0 : $articulosB2[$i];
$d1 = empty($articulosD1[$i]) ? 0 : $articulosD1[$i];
$d2 = empty($articulosD2[$i]) ? 0 : $articulosD2[$i];
$precio = empty($articulosPrecio[$i]) ? 0 : $articulosPrecio[$i];
$medicinal = DataManager::getArticulo('artmedicinal', $idArt, $empresa, $laboratorio);
$medicinal = ($medicinal == 'S') ? 0 : 1;
$precioArt = dac_calcularPrecio($cant, $precio, $medicinal, $d1, $d2);
if ($precioArt > $limiteFactura && $contadorFacturas == 0) {
$cantBonificar = empty($b2) ? 0 : dac_extraer_entero((($cant / $b2) * ($b1 - $b2)));
$cantFacturas = ceil($precioArt / $limiteFactura);
$unidXFactura = floor($cant / $cantFacturas);
$unidBonifXFactura = floor($cantBonificar / $cantFacturas);
$precioArt = dac_calcularPrecio($unidXFactura, $precio, $medicinal, $d1, $d2);
$cantPendiente = $cant;
$cantBonifPend = $cantBonificar - $unidBonifXFactura;
$observacion = " [Art:$idArt - Cant:$cant ($b1 X $b2)] ".$observacion;
$cant = $unidXFactura;
$b1 = 0;
$b2 = 0;
}
$totalFactura = $totalFactura + $precioArt;
// CONTROL ITEMS POR ARTICULOS // (BONIFICADOS vale x 2)
$items = ($b1 == 0 && $b2 == 0) ? $items + 1 : $items + 2;
// DEFINE NUEVA FACTURAs
if($items > $maxItems || ($totalFactura > $limiteFactura && $contado == 1) || ($totalFactura > $limiteFactura && $contadorFacturas == 0 && $contado == 0)) {
//$observacion = "DESG $nroPedido.".$observacion;
$items = ($items > $maxItems) ? $items - $maxItems : $maxItems - $items;
//$items = $items - $maxItems;
$nroPedido = 0;
$ultimaFactura = 0;
$totalFactura = $precioArt;
$contadorFacturas = ($contado == 0) ? 1 : 0;
}
// NUEVO NUMERO PEDIDO //
if ($nroPedido == 0) {
$fechaPedido = date("Y-m-d H:i:s");
$nroPedido = dac_controlNroPedido();
$IdPedido[] = $nroPedido;
}
// GRABAR //
do {
$nombreArt = DataManager::getArticulo('artnombre', $idArt, $empresa, $laboratorio);
if (empty($nombreArt)){
echo "Error con el artículo $idArt. Póngase en contacto con el administrador de la web"; exit;
}
$nroOrden = (empty($nroOrden)) ? 0 : $nroOrden;
$pedidoObject = DataManager::newObjectOfClass('TPedido');
$pedidoObject->__set('Usuario' , $_SESSION["_usrid"]);
$pedidoObject->__set('Pedido' , $nroPedido);
$pedidoObject->__set('Cliente' , $idCuenta);
$pedidoObject->__set('Empresa' , $empresa);
$pedidoObject->__set('Laboratorio' , $laboratorio);
$pedidoObject->__set('IDArt' , $idArt);
$pedidoObject->__set('Articulo' , $nombreArt);
$pedidoObject->__set('Cantidad' , $cant);
$pedidoObject->__set('Precio' , $precio);
$pedidoObject->__set('Bonificacion1' , $b1);
$pedidoObject->__set('Bonificacion2' , $b2);
$pedidoObject->__set('Descuento1' , $d1);
$pedidoObject->__set('Descuento2' , $d2);
$pedidoObject->__set('Descuento3' , 0);
$pedidoObject->__set('CondicionPago' , $condPago);
$pedidoObject->__set('OrdenCompra' , $nroOrden);
$pedidoObject->__set('Lista' , 0);
$pedidoObject->__set('Pack' , 0);
$pedidoObject->__set('IDAdmin' , 0);
$pedidoObject->__set('Administrador' , 0);
$pedidoObject->__set('FechaExportado' , date("2001-01-01"));
$pedidoObject->__set('IDResp' , 0);
$pedidoObject->__set('Responsable' , '');
$pedidoObject->__set('FechaAprobado' , date("2001-01-01"));
$pedidoObject->__set('Aprobado' , 0);
$pedidoObject->__set('Propuesta' , $idPropuesta);
$pedidoObject->__set('CondicionComercial',$idCondComercial);
$pedidoObject->__set('Negociacion' , $idPropuesta); //Negociaciones sería la nueva opción de PROPUESTA
$pedidoObject->__set('Aprobado' , ($estado == 2) ? 0 : $estado); //Aprobado sería el nuevo Estado del pedido
$observacion = substr($observacion, 0, 250);
$pedidoObject->__set('Observacion' , $observacion);
$pedidoObject->__set('FechaPedido' , $fechaPedido);
$pedidoObject->__set('Activo' , 1); //Queda activo porque aún no está exportado
$pedidoObject->__set('Tipo' , $tipoPedido);
$pedidoObject->__set('Nombre' , $nombre);
$pedidoObject->__set('Provincia' , $provincia);
$pedidoObject->__set('Localidad' , $localidad);
$pedidoObject->__set('Direccion' , $direccion);
$pedidoObject->__set('CP' , $cp);
$pedidoObject->__set('Telefono' , $telefono);
$pedidoObject->__set('ID' , $pedidoObject->__newID());
if ($cant != 0){
$ID = DataManager::insertSimpleObject($pedidoObject);
if(empty($ID)){
echo "Error. No se grabó el pedido $nroPedido. Póngase en contacto con el administrador de la web"; exit;
}
}
// División de Facturas //
if($cantFacturas > 0){
$observacion = substr($observacion, 0, 250);
$pedidoObject = DataManager::newObjectOfClass('TPedido');
$pedidoObject->__set('Usuario' , $_SESSION["_usrid"]);
$pedidoObject->__set('Pedido' , $nroPedido);
$pedidoObject->__set('Cliente' , $idCuenta);
$pedidoObject->__set('Empresa' , $empresa);
$pedidoObject->__set('Laboratorio' , $laboratorio);
$pedidoObject->__set('IDArt' , $idArt);
$pedidoObject->__set('Articulo' , $nombreArt);
$pedidoObject->__set('Cantidad' , $unidBonifXFactura);
$pedidoObject->__set('Precio' , 0);
$pedidoObject->__set('Bonificacion1' , $b1);
$pedidoObject->__set('Bonificacion2' , $b2);
$pedidoObject->__set('Descuento1' , $d1);
$pedidoObject->__set('Descuento2' , $d2);
$pedidoObject->__set('Descuento3' , 0);
$pedidoObject->__set('CondicionPago' , $condPago);
$pedidoObject->__set('OrdenCompra' , $nroOrden);
$pedidoObject->__set('Lista' , 0);
$pedidoObject->__set('Pack' , 0);
$pedidoObject->__set('IDAdmin' , 0);
$pedidoObject->__set('Administrador' , '');
$pedidoObject->__set('FechaExportado' , date("2001-01-01"));
$pedidoObject->__set('IDResp' , 0);
$pedidoObject->__set('Responsable' , '');
$pedidoObject->__set('FechaAprobado' , date("2001-01-01"));
$pedidoObject->__set('Aprobado' , 0);
$pedidoObject->__set('Propuesta' , $idPropuesta);
$pedidoObject->__set('CondicionComercial',$idCondComercial);
$pedidoObject->__set('Negociacion' , $idPropuesta);
$pedidoObject->__set('Aprobado' , ($estado == 2) ? 0 : $estado);
$pedidoObject->__set('Observacion' , $observacion);
$pedidoObject->__set('FechaPedido' , $fechaPedido);
$pedidoObject->__set('Activo' , 1); //Queda activo porque aún no está exportado
$pedidoObject->__set('Tipo' , $tipoPedido);
$pedidoObject->__set('Nombre' , $nombre);
$pedidoObject->__set('Provincia' , $provincia);
$pedidoObject->__set('Localidad' , $localidad);
$pedidoObject->__set('Direccion' , $direccion);
$pedidoObject->__set('CP' , $cp);
$pedidoObject->__set('Telefono' , $telefono);
$pedidoObject->__set('ID' , $pedidoObject->__newID());
if ($unidBonifXFactura != 0){
$ID = DataManager::insertSimpleObject($pedidoObject);
if(empty($ID)){
echo "Error. No se grabó el pedido $nroPedido. Póngase en contacto con el administrador de la web."; exit;
}
}
if($contado == 0 && $contadorFacturas == 0){
$cantFacturas = 1;
$ultimaFactura = 1;
$contadorFacturas = 1;
} else {
$cantFacturas = $cantFacturas - 1;
}
$cantPendiente = $cantPendiente - $unidXFactura;
$cantBonifPend = $cantBonifPend - $unidBonifXFactura;
//SI es la ULTIMA FACTURA
if($cantFacturas == 1) {
$cant = $cantPendiente;
$unidBonifXFactura = $unidBonifXFactura + $cantBonifPend;
$cantPendiente = 0;
$cantBonifPend = 0;
$unidXFactura = 0;
$precioArt = dac_calcularPrecio($cant, $precio, $medicinal, $d1, $d2);
if($precioArt > $limiteFactura && $contadorFacturas == 0){
$cantBonificar = $unidBonifXFactura;
$cantFacturas = 2; //redondea hacia arriba
$unidXFactura = floor($cant / $cantFacturas); //redondea hacia abajo
$unidBonifXFactura = floor($cantBonificar / $cantFacturas);
$cantPendiente = $cant;
$cantBonifPend = $cantBonificar - $unidBonifXFactura;
$observacion = $observacion." (desglose distinto)";
$cant = $unidXFactura;
$items = 0;
} else {
$unidXFactura = $cant;
$items = 2;
}
$nroPedido = dac_controlNroPedido();
$IdPedido[] = $nroPedido;
$precioArt = dac_calcularPrecio($cant, $precio, $medicinal, $d1, $d2);
$totalFactura = $precioArt;
//CAMBIO FACTURA A 2 PARA QUE SALGA
$ultimaFactura = 1;
}
if($ultimaFactura == 0){
$nroPedido = dac_controlNroPedido();
$IdPedido[] = $nroPedido;
}
}
} while ($cantFacturas > 0);
} //fin for articulos
//Al crear los pedidos, carga el archivo de la orden de compra.
if ($filePeso != 0){
$ctaId = DataManager::getCuenta('ctaid', 'ctaidcuenta', $idCuenta, $empresa);
$rutaFile = "/pedidos/cuentas/archivos/".$ctaId."/pedidos/".$nroPedido."/";
$ext = explode(".", $fileNombre);
$name = 'ordenCompra'.$nroOrden; //$ext[0];
$rutaFile = $_SERVER['DOCUMENT_ROOT'].$rutaFile;
if(file_exists($rutaFile) || @mkdir($rutaFile, 0777, true)) {
$origen = $fileTempName;
$ext = explode(".", $fileNombre);
$name = $name.".".$ext[1];
$destino = $rutaFile.$name; //nombre del archivo
# movemos el archivo
if(@move_uploaded_file($origen, $destino)) {
} else { echo "Error al intentar subir el archivo."; exit;}
} else { echo "Error al intentar subir el archivo."; exit; }
}
//------------------------
?><file_sep>/pedidos/logica/ajax/aprobar.propuesta.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="V"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$idPropuesta= (isset($_POST['propuesta'])) ? $_POST['propuesta'] : NULL;
$estado = (isset($_POST['estado'])) ? $_POST['estado'] : NULL;
$propuesta = DataManager::getPropuesta($idPropuesta);
if ($propuesta) {
foreach ($propuesta as $k => $prop) {
$empresa = $prop["propidempresa"];
$fecha = $prop['propfecha'];
$usrProp = $prop['propusr'];
$estadoDDBB = $prop["propestado"];
$activa = $prop["propactiva"];
$nroCuenta = $prop["propidcuenta"];
$propuestaObject = DataManager::newObjectOfClass('TPropuesta', $idPropuesta);
$propuestaObject->__set('Estado' , $estado);
$propuestaObject->__set('FechaCierre' , date("Y-m-d H:i:s"));
$propuestaObject->__set('LastUpdate' , date("Y-m-d H:i:s"));
$propuestaObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
switch ($estadoDDBB){
case 1: //PENDIENTE
if ($_SESSION["_usrid"]=="7" || $_SESSION["_usrid"]=="20" || $_SESSION["_usrid"]=="33" || $_SESSION["_usrid"]=="82" || $_SESSION["_usrid"]=="28" || $_SESSION["_usrid"]=="40" || $_SESSION["_usrid"]=="69"){
switch ($estado){
case 2:
/*if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo "No puede realizar el proceso."; exit;
} else {
$resultado = "APROBADA";
} */
$resultado = "APROBADA";
break;
case 3:
$resultado = "RECHAZADA";
$propuestaObject->__set('Activa' , 0);
break;
}
} else {
echo "No puede realizar el proceso."; exit;
}
break;
case 2: //APROBADA
switch ($estado){
case 2:
echo "No puede realizar el proceso."; exit;
break;
case 3:
$resultado = "RECHAZADA";
$propuestaObject->__set('Activa' , 0);
break;
}
break;
case 3: //rechazada
echo "No puede realizar el proceso."; exit;
break;
}
DataManager::updateSimpleObject($propuestaObject);
//Cargo NUEVO ESTADO Propuesta APROBADA/RECHAZADO
$estadoNombre = DataManager::getEstado('penombre', 'peid', $estado);
$estadoObject = DataManager::newObjectOfClass('TEstado');
$estadoObject->__set('Origen' , 'TPropuesta');
$estadoObject->__set('IDOrigen' , $idPropuesta);
$estadoObject->__set('Fecha' , date("Y-m-d H:i:s"));
$estadoObject->__set('UsrCreate', $_SESSION["_usrid"]);
$estadoObject->__set('Estado' , $estado); //rechazado o aceptado
$estadoObject->__set('Nombre' , $estadoNombre);
$estadoObject->__set('ID' , $estadoObject->__newID());
$IDEst = DataManager::insertSimpleObject($estadoObject);
if(empty($IDEst)){
echo "No se grabó correctamente el estado de la propuesta."; exit;
}
//**********//
// CORREO // Notifica aprobacion/Rechazo
//**********//
$cuentaName = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $nroCuenta, $empresa);
$empresaNombre = DataManager::getEmpresa('empnombre', $empresa);
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
$usrName = DataManager::getUsuario('unombre', $usrProp);
$usrMail = DataManager::getUsuario('uemail', $usrProp);
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = "<EMAIL>";
$mail->FromName = "InfoWeb GEZZI";
$mail->Subject = "La propuesta ".$idPropuesta." fue ".$resultado;
$headMail = '
<html>
<head>
<title>PROPUESTA '.$idPropuesta.' '.$resultado.'</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 580px;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>';
$cuerpoMail_1 = '
<body>
<div align="center">
<table width="580" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Se envían los datos de <strong>PROPUESTA '.$resultado.' </strong> correspondiente a:<br/><br/>
<div />
</td >
</tr>
<tr>
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight:bold; background-color:#117db6">
<strong>Datos de la solicitud</strong>
</div>
</td>
</tr>
';
$cuerpoMail_2 = '
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Usuario </th>
<td align="left" width="400"> '.$usrName.' </td>
</tr>
<tr>
<th align="left" width="200">Propuesta</th>
<td align="left" width="400">'.$idPropuesta.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$usrMail.'</td>
</tr>
<tr>
<th align="left" width="200">Fecha de pedido</th>
<td align="left" width="400">'.$fecha.'</td>
</tr>
<tr style="color:#FFFFFF; font-weight:bold;">
<th colspan="2" align="center">
Datos de la Propuesta
</th>
</tr>
<tr>
<th align="left" width="200">Estado</th>
<td align="left" width="400">'.$resultado.'</td>
</tr>
<tr>
<th align="left" width="200">Cuenta</th>
<td align="left" width="400">'.$nroCuenta.'</td>
</tr>
<tr>
<th align="left" width="200">Nombre</th>
<td align="left" width="400">'.$cuentaName.'</td>
</tr>
</table>
</div>
</td>
</tr>
';
$cuerpoMail_3 = '
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con la empresa al 4555-3366 de Lunes a Viernes de 10 a 17 horas.
</font>
<div style="color:#000000; font-size:12px;">
<strong>Puede reclamar reenviando éste mail a <EMAIL>. </strong></br></br>
</div>
</div>
</td>
</tr>
';
$pieMail = '
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Gracias por confiar en '.$empresaNombre.'<br/>
Le saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
</html>
';
$cuerpoMail = $headMail.$cuerpoMail_1.$cuerpoMail_2.$cuerpoMail_3.$pieMail;
$mail->msgHTML($cuerpoMail);
$mail->AddBCC("<EMAIL>", "Infoweb");
//$mail->AddBCC("<EMAIL>", "Control de Gestion");
$mail->AddAddress($usrMail, "$usrMail");
if(!$mail->Send()) {
echo 'Fallo en el envío de mail de la propuesta'; exit;
}
/*********************/
switch ($estado){
case 2:
case 3:
echo "1"; exit;
break;
default:
echo "Error al indicar el resultado."; exit;
break;
}
}
} else {
echo "No se encontró la propuesta para modificar."; exit;
}
?><file_sep>/pedidos/logica/eliminar.pedido.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_nropedido = empty($_REQUEST['nropedido']) ? 0 : $_REQUEST['nropedido'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/pedidos/ ': $_REQUEST['backURL'];
if ($_nropedido) {
//lo siguiente borra todos los registros de pedidos que tengan el mismo nro de pedido
$_tabla = "pedido";
DataManager::deletefromtabla($_tabla, 'pidpedido', $_nropedido);
}
header('Location: '.$backURL);
?><file_sep>/condicion/logica/export.condicion.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$condId = empty($_GET['condid']) ? 0 : $_GET['condid'];
$backURL = empty($_GET['backURL']) ? '/pedidos/condicion/': $_GET['backURL'];
if ($condId) {
$condicion = DataManager::newObjectOfClass('TCondicionComercial', $condId);
$empresa = $condicion->__get('Empresa');
$laboratorio = $condicion->__get('Laboratorio');
$cuentas = $condicion->__get('Cuentas');
$nombre = $condicion->__get('Nombre');
$tipo = $condicion->__get('Tipo');
$condPago = $condicion->__get('CondicionPago');
$cantMinima = ($condicion->__get('CantidadMinima')) ? $condicion->__get('CantidadMinima') : '';
$minReferencias = ($condicion->__get('MinimoReferencias')) ? $condicion->__get('MinimoReferencias') : '';
$minMonto = ($condicion->__get('MinimoMonto') == '0.000') ? '' : $condicion->__get('MinimoMonto');
$fechaInicio = dac_invertirFecha( $condicion->__get('FechaInicio'));
$fechaFin = dac_invertirFecha($condicion->__get('FechaFin'));
$observacion = utf8_decode($condicion->__get('Observacion'));
} else {
$empresa = 1;
$laboratorio = 1;
$cuentas = "";
$nombre = "";
$tipo = "";
$cantMinima = "";
$minReferencias = "";
$minMonto = "";
$condPago = "";
$fechaInicio = "";
$fechaFin = "";
$observacion = "";
}
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=".$tipo."-".date("d-m-Y").".xls"); ?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos .::</TITLE>
<head>
<style>
.datatab{
font-size:14px;
}
tr th {
font-weight:bold;
height: 20px;
}
td.par {
background-color: #fff;
height: 20px;
}
td.impar {
background-color: #cfcfcf;
height: 20px;
font-weight:bold;
}
</style>
</head>
<body>
<?php
switch($tipo){
case 'Pack': ?>
<table width="600">
<thead>
<tr>
<th scope="colgroup" colspan="7" align="center" style="height:100px;"><?php echo $cabecera; ?></th>
</tr>
<tr>
<th scope="colgroup" rowspan="2" colspan="2" align="center" style="font-size:24px; color:#117db6; border:1px solid #666" ><?php echo $tipo; ?></th>
<th scope="colgroup" colspan="5" align="center" style="font-size:24px; color:#117db6; border:1px solid #666"><?php echo $nombre; ?></th>
</tr>
<tr>
<th scope="colgroup" colspan="5" align="center" style="border:1px solid #666">
Vigencia: <?php echo " ".$fechaInicio." "; ?> / <?php echo " ".$fechaFin; ?>
</th>
</tr>
<tr>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">Art</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="250">Descripción</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">CantMín</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="100">PSL</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">Unid</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">Desc</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">Bonif</th>
</tr>
</thead>
<tbody> <?php
if ($condId) {
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
foreach ($articulosCond as $k => $artCond) {
$artCond = $articulosCond[$k];
//$condArtId = $artCond['cartid'];
$condArtIdArt = $artCond['cartidart'];
$condArtNombre = DataManager::getArticulo('artnombre', $condArtIdArt, $empresa, $laboratorio);
$condArtPrecio = $artCond["cartprecio"]; //(PSL)
//--> precio digitado o precio de venta. (PV)
$condArtPrecioDigit = ($artCond["cartpreciodigitado"] == '0.000')? '' : $artCond["cartpreciodigitado"];
$condArtCantMin = empty($artCond['cartcantmin'])? '' : $artCond['cartcantmin'];
$_estilo = (($k % 2) == 0)? "par" : "impar";
?>
<tr>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $condArtIdArt; ?></td>
<td class="<?php echo $_estilo; ?>" ><?php echo utf8_decode($condArtNombre); ?></td>
<td class="<?php echo $_estilo; ?>" ><?php echo $condArtCantMin; ?></td>
<td class="<?php echo $_estilo; ?>" align="right"><?php echo "$ ".$condArtPrecio; ?></td>
<?php
//Controlo si tiene Bonificaciones y dewscuentos para cargar
$articulosBonif = DataManager::getCondicionBonificaciones($condId, $condArtIdArt);
if (count($articulosBonif)) {
foreach ($articulosBonif as $j => $artBonif) {
$artBonifCant = empty($artBonif['cbcant']) ? '' : $artBonif['cbcant'];
$artBonifB1 = empty($artBonif['cbbonif1']) ? '' : $artBonif['cbbonif1'];
$artBonifB2 = empty($artBonif['cbbonif2']) ? '' : $artBonif['cbbonif2'];
$bonif = (empty($artBonifB1)) ? '' : $artBonifB1.' X '.$artBonifB2;
$artBonifD1 = ($artBonif['cbdesc1'] == '0.00') ? '' : $artBonif['cbdesc1'];
if($j == 0){ ?>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $artBonifCant; ?></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $artBonifD1; ?></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $bonif; ?></td>
</tr> <?php
} else { ?>
<tr>
<td class="<?php echo $_estilo; ?>" align="center"></td>
<td class="<?php echo $_estilo; ?>" ></td>
<td class="<?php echo $_estilo; ?>" ></td>
<td class="<?php echo $_estilo; ?>" align="center"></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $artBonifCant; ?></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $artBonifD1; ?></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $bonif; ?></td>
</tr> <?php
}
}
} else { ?>
<td class="<?php echo $_estilo; ?>" align="center"></td>
<td class="<?php echo $_estilo; ?>" align="center"></td>
<td class="<?php echo $_estilo; ?>" align="center"></td>
</tr> <?php
}
} ?>
<tr>
<td scope="colgroup" colspan="7"></td>
</tr>
<?php if($minMonto){?>
<tr>
<td scope="colgroup" colspan="2"></td>
<td scope="colgroup" colspan="3" style="font-weight:bold; text-align: right;">Monto Mínimo</td>
<td scope="colgroup" colspan="2" style="font-weight:bold;"><?php echo "$ ".$minMonto;?></td>
<td scope="colgroup" colspan="1"></td>
</tr>
<?php }?>
<?php if($cantMinima){?>
<tr>
<td scope="colgroup" colspan="2" ></td>
<td scope="colgroup" colspan="3" style="font-weight:bold; text-align: right;">Cantidad Total Mínima</td>
<td scope="colgroup" colspan="2" style="font-weight:bold;"><?php echo $cantMinima;?> </td>
<td scope="colgroup" colspan="1"></td>
</tr>
<?php }?>
<?php if($minReferencias){?>
<tr>
<td scope="colgroup" colspan="2" ></td>
<td scope="colgroup" colspan="3" style="font-weight:bold; text-align: right;">Mínimo de Referencias</td>
<td scope="colgroup" colspan="2" style="font-weight:bold;"><?php echo $minReferencias;?> </td>
<td scope="colgroup" colspan="1"></td>
</tr>
<?php }?>
<?php if($condPago){?>
<tr>
<td scope="colgroup" colspan="7" style="font-weight:bold;">CONDICIONES DE PAGO: </td>
</tr>
<?php
$condicionesPago = explode(",", $condPago);
if($condicionesPago){
for( $j=0; $j < count($condicionesPago); $j++ ) {
$condicionesDePago = DataManager::getCondicionesDePago(0, 0, NULL, $condicionesPago[$j]);
if (count($condicionesDePago)) {
foreach ($condicionesDePago as $k => $condPago) {
$condPagoCodigo = $condPago["IdCondPago"];
$nombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condPago['condtipo']);
$condPagoDias = "(";
$condPagoDias .= empty($condPago['Dias1CP']) ? '0' : $condPago['Dias1CP'];
$condPagoDias .= empty($condPago['Dias2CP']) ? '' : ', '.$condPago['Dias2CP'];
$condPagoDias .= empty($condPago['Dias3CP']) ? '' : ', '.$condPago['Dias3CP'];
$condPagoDias .= empty($condPago['Dias4CP']) ? '' : ', '.$condPago['Dias4CP'];
$condPagoDias .= empty($condPago['Dias5CP']) ? '' : ', '.$condPago['Dias5CP'];
$condPagoDias .= " Días)";
$condPagoDias .= ($condPago['Porcentaje1CP'] == '0.00') ? '' : ' '.$condPago['Porcentaje1CP'].' %';
$condNombre = $nombre." ".$condPagoDias;
}
}
?>
<tr>
<td scope="colgroup" colspan="1" ></td>
<td scope="colgroup" colspan="6" ><?php echo $condicionesPago[$j].' - '.utf8_decode($condNombre); ?></td>
</tr>
<?php
}
} ?>
<?php }?>
<?php if($observacion){?>
<tr>
<td scope="colgroup" colspan="7" style="font-weight:bold;">OBSERVACIÓN </td>
</tr>
<tr>
<td scope="colgroup" colspan="1" ></td>
<td scope="colgroup" colspan="6" style="height:50px;" ><?php echo $observacion; ?></td>
</tr>
<?php }?>
<tr>
<td scope="colgroup" colspan="7" ></td>
</tr>
<?php
}
} else { ?>
<tr>
<td scope="colgroup" colspan="7" style="border:1px solid #666">No se encontraron condiciones.</td>
</tr> <?php
} ?>
</tbody>
<tfoot>
<tr>
<th scope="colgroup" colspan="7" align="center" style="height:100px;"><?php echo $pie; ?></th>
</tr>
</tfoot>
</table> <?php
break;
/*case 'ListaEspecial': ?>
<table width="600">
<thead>
<tr>
<th scope="colgroup" colspan="8" align="center" style="height:100px;"><?php echo $cabecera; ?></th>
</tr>
<tr>
<th scope="colgroup" rowspan="2" colspan="2" align="center" style="font-size:24px; color:#117db6; border:1px solid #666" ><?php echo $tipo; ?></th>
<th scope="colgroup" colspan="6" align="center" style="font-size:24px; color:#117db6; border:1px solid #666"><?php echo $nombre; ?></th>
</tr>
<tr>
<th scope="colgroup" colspan="6" align="center" style="border:1px solid #666">
Vigencia: <?php echo " ".$fechaInicio." "; ?> / <?php echo " ".$fechaFin; ?>
</th>
</tr>
<tr>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">Art</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="250">Descripción</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">PVP</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">PSL</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">PV</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">Unid</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">Desc</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">Bonif</th>
</tr>
</thead>
<tbody> <?php
if ($condId) {
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
foreach ($articulosCond as $k => $artCond) {
$artCond = $articulosCond[$k];
//$condArtId = $artCond['cartid'];
$condArtIdArt = $artCond['cartidart'];
$condArtNombre = DataManager::getArticulo('artnombre', $condArtIdArt, $empresa, $laboratorio);
// --> precio original de la tabla artículos (droguería)
$condArtMedicinal = DataManager::getArticulo('artmedicinal', $condArtIdArt, $empresa, $laboratorio);
$condArtIva = DataManager::getArticulo('artiva', $condArtIdArt, $empresa, $laboratorio);
$condArtGanancia = DataManager::getArticulo('artganancia', $condArtIdArt, $empresa, $laboratorio);
$condArtPrecio = $artCond["cartprecio"]; //(PSL)
$condArtDigitado= ($artCond["cartpreciodigitado"] == '0.000') ? '' : $artCond["cartpreciodigitado"]; // (PVP)
$precio = (empty($condArtPrecio)) ? $condArtDigitado : $condArtPrecio;
/*$p1 = floatval($precio);//1.45 es el 45% que sale dividiendo PVP / PSL
$p2 = floatval(1.450);
$pvp = $p1*$p2;
$pvp = ($medicinal) ? $pvp*1.21 : $pvp;
$pvp = number_format($pvp,3,'.',''); // (PVP) */
//Calcular PVP
/* $pvp = dac_calcularPVP($precio, $condArtIva, $condArtMedicinal, $empresa, $condArtGanancia);
$condArtCantMin = empty($artCond['cartcantmin'])? '' : $artCond['cartcantmin'];
$_estilo = (($k % 2) == 0)? "par" : "impar"; ?>
<tr>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $condArtIdArt; ?></td>
<td class="<?php echo $_estilo; ?>" ><?php echo utf8_decode($condArtNombre); ?></td>
<td class="<?php echo $_estilo; ?>" align="right"><?php echo "$ ".$pvp; ?></td>
<td class="<?php echo $_estilo; ?>" align="right"><?php if($condArtPrecio){ echo "$ ".$condArtPrecio; } ?></td>
<td class="<?php echo $_estilo; ?>" align="right"><?php if($condArtDigitado){ echo "$ ".$condArtDigitado; } ?></td>
<?php
//Controlo si tiene Bonificaciones y dewscuentos para cargar
$articulosBonif = DataManager::getCondicionBonificaciones($condId, $condArtIdArt);
if (count($articulosBonif)) {
foreach ($articulosBonif as $j => $artBonif) {
//$artBonifId = empty($artBonif['cbid']) ? '' : $artBonif['cbid'];
$artBonifCant = empty($artBonif['cbcant']) ? '' : $artBonif['cbcant'];
$artBonifB1 = empty($artBonif['cbbonif1']) ? '' : $artBonif['cbbonif1'];
$artBonifB2 = empty($artBonif['cbbonif2']) ? '' : $artBonif['cbbonif2'];
$bonif = (empty($artBonifB1)) ? '' : $artBonifB1.' X '.$artBonifB2;
$artBonifD1 = ($artBonif['cbdesc1'] == '0.00') ? '' : $artBonif['cbdesc1'];
//$artBonifD2 = empty($artBonif['cbdesc2']) ? '' : $artBonif['cbdesc2'];
if($j == 0){ ?>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $artBonifCant; ?></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $artBonifD1; ?></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $bonif; ?></td>
</tr> <?php
} else { ?>
<tr>
<td class="<?php echo $_estilo; ?>" align="center"></td>
<td class="<?php echo $_estilo; ?>" ></td>
<td class="<?php echo $_estilo; ?>" ></td>
<td class="<?php echo $_estilo; ?>" align="center"></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $artBonifCant; ?></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $artBonifD1; ?></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $bonif; ?></td>
</tr> <?php
}
}
} else { ?>
<td class="<?php echo $_estilo; ?>" align="center"></td>
<td class="<?php echo $_estilo; ?>" align="center"></td>
<td class="<?php echo $_estilo; ?>" align="center"></td>
</tr> <?php
}
} ?>
<tr>
<td scope="colgroup" colspan="8"></td>
</tr>
<?php if($minMonto){?>
<tr>
<td scope="colgroup" colspan="2"></td>
<td scope="colgroup" colspan="4" style="font-weight:bold; text-align: right;">Monto Mínimo</td>
<td scope="colgroup" colspan="2" style="font-weight:bold;"><?php echo "$ ".$minMonto;?></td>
<td scope="colgroup" colspan="1"></td>
</tr>
<?php }?>
<?php if($cantMinima){?>
<tr>
<td scope="colgroup" colspan="2" ></td>
<td scope="colgroup" colspan="4" style="font-weight:bold; text-align: right;">Cantidad Total Mínima</td>
<td scope="colgroup" colspan="2" style="font-weight:bold;"><?php echo $cantMinima;?> </td>
<td scope="colgroup" colspan="1"></td>
</tr>
<?php }?>
<?php if($minReferencias){?>
<tr>
<td scope="colgroup" colspan="2" ></td>
<td scope="colgroup" colspan="4" style="font-weight:bold; text-align: right;">Mínimo de Referencias</td>
<td scope="colgroup" colspan="2" style="font-weight:bold;"><?php echo $minReferencias;?> </td>
<td scope="colgroup" colspan="1"></td>
</tr>
<?php }?>
<?php if($condPago){?>
<tr>
<td scope="colgroup" colspan="8" style="font-weight:bold;">CONDICIONES DE PAGO: </td>
</tr>
<?php
$condicionesPago = explode(",", $condPago);
if($condicionesPago){
for( $j=0; $j < count($condicionesPago); $j++ ) {
$condicionesDePago = DataManager::getCondicionesDePago(0, 0, NULL, $condicionesPago[$j]);
if (count($condicionesDePago)) {
foreach ($condicionesDePago as $k => $condPago) {
$condPagoCodigo = $condPago["IdCondPago"];
$nombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condPago['condtipo']);
$condPagoDias = "(";
$condPagoDias .= empty($condPago['Dias1CP']) ? '0' : $condPago['Dias1CP'];
$condPagoDias .= empty($condPago['Dias2CP']) ? '' : ', '.$condPago['Dias2CP'];
$condPagoDias .= empty($condPago['Dias3CP']) ? '' : ', '.$condPago['Dias3CP'];
$condPagoDias .= empty($condPago['Dias4CP']) ? '' : ', '.$condPago['Dias4CP'];
$condPagoDias .= empty($condPago['Dias5CP']) ? '' : ', '.$condPago['Dias5CP'];
$condPagoDias .= " Días)";
$condPagoDias .= ($condPago['Porcentaje1CP'] == '0.00') ? '' : ' '.$condPago['Porcentaje1CP'].' %';
$condNombre = $nombre." ".$condPagoDias;
}
}
?>
<tr>
<td scope="colgroup" colspan="1" ></td>
<td scope="colgroup" colspan="6" ><?php echo $condicionesPago[$j].' - '.utf8_decode($condNombre); ?></td>
</tr>
<?php
}
} ?>
<?php }?>
<?php if($observacion){?>
<tr>
<td scope="colgroup" colspan="8" style="font-weight:bold;">OBSERVACIÓN </td>
</tr>
<tr>
<td scope="colgroup" colspan="1" ></td>
<td scope="colgroup" colspan="7" style="height:50px;" ><?php echo $observacion; ?></td>
</tr>
<?php }?>
<tr>
<td scope="colgroup" colspan="8" ></td>
</tr>
<?php
}
if(!empty($cuentas)){ ?>
<tr>
<td scope="colgroup" colspan="8" style="font-weight:bold;">Cuentas Relacionadas</td>
</tr>
<?php
$cuentasCondiciones = explode(",", $cuentas);
foreach ($cuentasCondiciones as $ctaCond) {
$ctaCondIdCta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $ctaCond, $empresa);
$ctaCondNombre = DataManager::getCuenta('ctanombre', 'ctaid', $ctaCond, $empresa);
?>
<tr>
<th scope="colgroup" align="left" style="border:1px solid #666; background-color: #cfcfcf;" width="50"><?php echo $ctaCondIdCta; ?></th>
<th colspan="7" scope="colgroup" align="left" style="border:1px solid #666; background-color: #cfcfcf" width="250"><?php echo $ctaCondNombre; ?></th>
</tr>
<?php
}
}
} else { ?>
<tr>
<td scope="colgroup" colspan="8" style="border:1px solid #666">No se encontraron condiciones.</td>
</tr> <?php
} ?>
</tbody>
<tfoot>
<tr>
<th scope="colgroup" colspan="8" align="center" style="height:100px;"><?php echo $pie; ?></th>
</tr>
</tfoot>
</table> <?php
break; */
case 'CondicionEspecial':
case 'ListaEspecial': ?>
<table width="600">
<thead>
<tr>
<th scope="colgroup" colspan="8" align="center" style="height:100px;"><?php echo $cabecera; ?></th>
</tr>
<tr>
<th scope="colgroup" rowspan="2" colspan="2" align="center" style="font-size:24px; color:#117db6; border:1px solid #666" ><?php echo $tipo; ?></th>
<th scope="colgroup" colspan="6" align="center" style="font-size:24px; color:#117db6; border:1px solid #666"><?php echo $nombre; ?></th>
</tr>
<tr>
<th scope="colgroup" colspan="6" align="center" style="border:1px solid #666">
Vigencia: <?php echo " ".$fechaInicio." "; ?> / <?php echo " ".$fechaFin; ?>
</th>
</tr>
<tr>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">Art</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="250">Descripción</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">PVP</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">PSL</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">PV</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">Desc</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">Desc</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="50">Bonif</th>
</tr>
</thead>
<tbody> <?php
if ($condId) {
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
foreach ($articulosCond as $k => $artCond) {
$artCond = $articulosCond[$k];
$condArtIdArt = $artCond['cartidart'];
$condArtNombre = DataManager::getArticulo('artnombre', $condArtIdArt, $empresa, $laboratorio);
$medicinal = DataManager::getArticulo('artmedicinal', $condArtIdArt, $empresa, $laboratorio);
$condArtPrecio = $artCond["cartprecio"]; //(PSL)
$condArtDigitado= ($artCond["cartpreciodigitado"] == '0.000') ? '' : $artCond["cartpreciodigitado"]; // (PV) (Precio Venta)
//Calcular PVP
$condArtMedicinal= DataManager::getArticulo('artmedicinal', $condArtIdArt, $empresa, $laboratorio);
$condArtIva = DataManager::getArticulo('artiva', $condArtIdArt, $empresa, $laboratorio);
$condArtGanancia = DataManager::getArticulo('artganancia', $condArtIdArt, $empresa, $laboratorio);
$pvp = dac_calcularPVP($condArtPrecio, $condArtIva, $condArtMedicinal, $empresa, $condArtGanancia);
$condArtCantMin = empty($artCond['cartcantmin'])? '' : $artCond['cartcantmin'];
$_estilo = (($k % 2) == 0)? "par" : "impar";
?>
<tr>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $condArtIdArt; ?></td>
<td class="<?php echo $_estilo; ?>" ><?php echo utf8_decode($condArtNombre); ?></td>
<td class="<?php echo $_estilo; ?>" align="right"><?php echo "$ ".$pvp; ?></td>
<td class="<?php echo $_estilo; ?>" align="right"><?php echo "$ ".$condArtPrecio; ?></td>
<td class="<?php echo $_estilo; ?>" align="right"><?php if($condArtDigitado){ echo "$ ".$condArtDigitado; } ?></td>
<?php
//Controlo si tiene Bonificaciones y dewscuentos para cargar
$articulosBonif = DataManager::getCondicionBonificaciones($condId, $condArtIdArt);
if (count($articulosBonif)) {
foreach ($articulosBonif as $j => $artBonif) {
$artBonifCant = empty($artBonif['cbcant']) ? '' : $artBonif['cbcant'];
$artBonifB1 = empty($artBonif['cbbonif1']) ? '' : $artBonif['cbbonif1'];
$artBonifB2 = empty($artBonif['cbbonif2']) ? '' : $artBonif['cbbonif2'];
$bonif = (empty($artBonifB1)) ? '' : $artBonifB1.' X '.$artBonifB2;
$artBonifD1 = ($artBonif['cbdesc1'] == '0.00') ? '' : $artBonif['cbdesc1'];
$artBonifD2 = ($artBonif['cbdesc2'] == '0.00') ? '' : $artBonif['cbdesc2'];
if($j == 0){ ?>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $artBonifD1; ?></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $artBonifD2; ?></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $bonif; ?></td>
</tr> <?php
} else { ?>
<tr>
<td class="<?php echo $_estilo; ?>" align="center"></td>
<td class="<?php echo $_estilo; ?>" ></td>
<td class="<?php echo $_estilo; ?>" ></td>
<td class="<?php echo $_estilo; ?>" align="center"></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $artBonifD1; ?></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $artBonifD2; ?></td>
<td class="<?php echo $_estilo; ?>" align="center"><?php echo $bonif; ?></td>
</tr> <?php
}
}
} else { ?>
<td class="<?php echo $_estilo; ?>" align="center"></td>
<td class="<?php echo $_estilo; ?>" align="center"></td>
<td class="<?php echo $_estilo; ?>" align="center"></td>
</tr> <?php
}
} ?>
<tr>
<td scope="colgroup" colspan="8"></td>
</tr>
<?php if($minMonto){?>
<tr>
<td scope="colgroup" colspan="2"></td>
<td scope="colgroup" colspan="3" style="font-weight:bold; text-align: right;">Monto Mínimo</td>
<td scope="colgroup" colspan="2" style="font-weight:bold;"><?php echo "$ ".$minMonto;?></td>
<td scope="colgroup" colspan="2"></td>
</tr>
<?php }?>
<?php if($cantMinima){?>
<tr>
<td scope="colgroup" colspan="2" ></td>
<td scope="colgroup" colspan="3" style="font-weight:bold; text-align: right;">Cantidad Total Mínima</td>
<td scope="colgroup" colspan="2" style="font-weight:bold;"><?php echo $cantMinima;?> </td>
<td scope="colgroup" colspan="2"></td>
</tr>
<?php }?>
<?php if($minReferencias){?>
<tr>
<td scope="colgroup" colspan="2" ></td>
<td scope="colgroup" colspan="3" style="font-weight:bold; text-align: right;">Mínimo de Referencias</td>
<td scope="colgroup" colspan="2" style="font-weight:bold;"><?php echo $minReferencias;?> </td>
<td scope="colgroup" colspan="2"></td>
</tr>
<?php }?>
<?php if($condPago){?>
<tr>
<td scope="colgroup" colspan="8" style="font-weight:bold;">CONDICIONES DE PAGO: </td>
</tr>
<?php
$condicionesPago = explode(",", $condPago);
if($condicionesPago){
for( $j=0; $j < count($condicionesPago); $j++ ) {
$condicionesDePago = DataManager::getCondicionesDePago(0, 0, NULL, $condicionesPago[$j]);
if (count($condicionesDePago)) {
foreach ($condicionesDePago as $k => $condPago) {
$condPagoCodigo = $condPago["IdCondPago"];
$nombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condPago['condtipo']);
$condPagoDias = "(";
$condPagoDias .= empty($condPago['Dias1CP']) ? '0' : $condPago['Dias1CP'];
$condPagoDias .= empty($condPago['Dias2CP']) ? '' : ', '.$condPago['Dias2CP'];
$condPagoDias .= empty($condPago['Dias3CP']) ? '' : ', '.$condPago['Dias3CP'];
$condPagoDias .= empty($condPago['Dias4CP']) ? '' : ', '.$condPago['Dias4CP'];
$condPagoDias .= empty($condPago['Dias5CP']) ? '' : ', '.$condPago['Dias5CP'];
$condPagoDias .= " Días)";
$condPagoDias .= ($condPago['Porcentaje1CP'] == '0.00') ? '' : ' '.$condPago['Porcentaje1CP'].' %';
$condNombre = $nombre." ".$condPagoDias;
}
}
?>
<tr>
<td scope="colgroup" colspan="1" ></td>
<td scope="colgroup" colspan="7" ><?php echo $condicionesPago[$j].' - '.utf8_decode($condNombre); ?></td>
</tr>
<?php
}
} ?>
<?php }?>
<?php if($observacion){?>
<tr>
<td scope="colgroup" colspan="8" style="font-weight:bold;">OBSERVACIÓN </td>
</tr>
<tr>
<td scope="colgroup" colspan="1" ></td>
<td scope="colgroup" colspan="7" style="height:50px;" ><?php echo $observacion; ?></td>
</tr>
<?php }?>
<tr>
<td scope="colgroup" colspan="8" ></td>
</tr>
<?php
}
if(!empty($cuentas)){ ?>
<tr>
<td scope="colgroup" colspan="8" style="font-weight:bold;">Cuentas Relacionadas</td>
</tr>
<?php
$cuentasCondiciones = explode(",", $cuentas);
foreach ($cuentasCondiciones as $ctaCond) {
$ctaCondIdCta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $ctaCond, $empresa);
$ctaCondNombre = DataManager::getCuenta('ctanombre', 'ctaid', $ctaCond, $empresa);
?>
<tr>
<th scope="colgroup" align="left" style="border:1px solid #666; background-color: #cfcfcf;" width="50"><?php echo $ctaCondIdCta; ?></th>
<th colspan="7" scope="colgroup" align="left" style="border:1px solid #666; background-color: #cfcfcf" width="250"><?php echo $ctaCondNombre; ?></th>
</tr>
<?php
}
}
} else { ?>
<tr>
<td scope="colgroup" colspan="8" style="border:1px solid #666">No se encontraron condiciones.</td>
</tr> <?php
} ?>
</tbody>
<tfoot>
<tr>
<th scope="colgroup" colspan="8" align="center" style="height:100px;"><?php echo $pie; ?></th>
</tr>
</tfoot>
</table> <?php
break;
case 'Bonificacion': ?>
<table width="860" style="font-size:10px;">
<thead>
<tr>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="35"></th>
<th scope="colgroup" align="center" style="color:#117db6; border:1px solid #666" width="215">
<?php echo $tipo; ?> de <?php echo " ".$fechaInicio." "; ?> a <?php echo " ".$fechaFin; ?> </th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="65">PSL
</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="65">PVP</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="30">IVA</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="60">Digitado</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="30">O</th>
<th scope="colgroup" style="border:1px solid #666; background-color: #cfcfcf" width="30">AM</th>
<th scope="colgroup" colspan="3" style="border:1px solid #666; background-color: #cfcfcf" width="45">1</th>
<th scope="colgroup" colspan="3" style="border:1px solid #666; background-color: #cfcfcf" width="45">3</th>
<th scope="colgroup" colspan="3" style="border:1px solid #666; background-color: #cfcfcf" width="45">6</th>
<th scope="colgroup" colspan="3" style="border:1px solid #666; background-color: #cfcfcf" width="45">12</th>
<th scope="colgroup" colspan="3" style="border:1px solid #666; background-color: #cfcfcf" width="45">24</th>
<th scope="colgroup" colspan="3" style="border:1px solid #666; background-color: #cfcfcf" width="45">36</th>
<th scope="colgroup" colspan="3" style="border:1px solid #666; background-color: #cfcfcf" width="45">48</th>
<th scope="colgroup" colspan="3" style="border:1px solid #666; background-color: #cfcfcf" width="45">72</th>
</tr>
</thead>
<tbody> <?php
if ($condId) {
$articulosCond = DataManager::getCondicionArticulos($condId, 1);
if (count($articulosCond)) {
$arrayCantidades = array(1, 3, 6, 12, 24, 36, 48, 72);
foreach ($articulosCond as $k => $artCond) {
$artCond = $articulosCond[$k];
$condArtIdArt = $artCond['cartidart'];
$condArtNombre = DataManager::getArticulo('artnombre', $condArtIdArt, $empresa, $laboratorio);
$medicinal = DataManager::getArticulo('artmedicinal', $condArtIdArt, $empresa, $laboratorio);
$condArtPrecio = $artCond["cartprecio"]; //(PSL)
$condArtPrecioDigit = ($artCond["cartpreciodigitado"] == '0.000') ? '' : "$ ".$artCond["cartpreciodigitado"]; // (PV)
//Calcular PVP
$condArtMedicinal= DataManager::getArticulo('artmedicinal', $condArtIdArt, $empresa, $laboratorio);
$condArtIva = DataManager::getArticulo('artiva', $condArtIdArt, $empresa, $laboratorio);
$condArtGanancia = DataManager::getArticulo('artganancia', $condArtIdArt, $empresa, $laboratorio);
$pvp = dac_calcularPVP($condArtPrecio, $condArtIva, $condArtMedicinal, $empresa, $condArtGanancia);
$condArtCantMin = empty($artCond['cartcantmin'])? '' : $artCond['cartcantmin'];
$condArtOAM = substr($artCond['cartoam'], 0, 4);
$condArtOferta = ($artCond['cartoferta']) ? '*' : '';
$_estilo = (($k % 2) == 0)? "par" : "impar"; ?>
<tr>
<td class="<?php echo $_estilo; ?>" align="center" style="font-size:10px;"><?php echo $condArtIdArt; ?></td>
<td class="<?php echo $_estilo; ?>" style="font-size:10px;"><?php echo utf8_decode($condArtNombre); ?></td>
<td class="<?php echo $_estilo; ?>" align="right" style="font-size:10px;"><?php echo "$ ".$condArtPrecio; ?></td>
<td class="<?php echo $_estilo; ?>" align="right" style="font-size:10px;"><?php echo "$ ".$pvp; ?></td>
<td class="<?php echo $_estilo; ?>" align="center" style="font-size:10px;"><?php echo $medicinal; ?></td>
<td class="<?php echo $_estilo; ?>" align="right" style="font-size:10px;"><?php echo $condArtPrecioDigit; ?></td>
<td class="<?php echo $_estilo; ?>" align="center" style="font-size:10px;"><?php echo $condArtOferta; ?></td>
<td class="<?php echo $_estilo; ?>" style="font-size:10px; border-right: 1px solid #666;"><?php echo $condArtOAM; ?></td>
<?php
//Controlo si tiene Bonificaciones y dewscuentos para cargar
$articulosBonif = DataManager::getCondicionBonificaciones($condId, $condArtIdArt);
if (count($articulosBonif)) {
unset($arrayCant);
//unset($arrayBonif);
unset($array1);
unset($array2);
unset($array3);
foreach ($articulosBonif as $j => $artBonif) {
$artBonifCant = empty($artBonif['cbcant']) ? '' : $artBonif['cbcant'];
$artBonifB1 = empty($artBonif['cbbonif1']) ? '' : $artBonif['cbbonif1'];
$artBonifB2 = empty($artBonif['cbbonif2']) ? '' : $artBonif['cbbonif2'];
$artBonifD1 = ($artBonif['cbdesc1'] == '0.00') ? '' : ceil($artBonif['cbdesc1']);
if(empty($artBonifB1)){
$array1[] = '';
$array2[] = $artBonifD1;
$array3[] = ' %';
} else {
$array1[] = $artBonifB1;
$array2[] = 'X';
$array3[] = $artBonifB2;
}
$arrayCant[] = $artBonifCant;
}
//recorro el array para cargar
for($i=0; $i < count($arrayCantidades); $i++){
if(in_array($arrayCantidades[$i], $arrayCant)){
$key = array_search($arrayCantidades[$i], $arrayCant);
?>
<td class="<?php echo $_estilo; ?>" align="center" style="font-size:10px;"><?php echo $array1[$key]; ?></td>
<td class="<?php echo $_estilo; ?>" align="center" style="font-size:10px;"><?php echo $array2[$key]; ?></td>
<td class="<?php echo $_estilo; ?>" align="center" style="font-size:10px; border-right: 1px solid #666;"><?php echo $array3[$key] //$arrayBonif[$key]; ?></td> <?php
} else { ?>
<td class="<?php echo $_estilo; ?>"></td>
<td class="<?php echo $_estilo; ?>"></td>
<td class="<?php echo $_estilo; ?>" style="border-right: 1px solid #666;"></td> <?php
}
}
} else { ?>
<td class="<?php echo $_estilo; ?>" colspan="3" style="background-color:#333; border-right: 1px solid #666;"></td>
<td class="<?php echo $_estilo; ?>" colspan="3" style="background-color:#333; border-right: 1px solid #666;"></td>
<td class="<?php echo $_estilo; ?>" colspan="3" style="background-color:#333; border-right: 1px solid #666;"></td>
<td class="<?php echo $_estilo; ?>" colspan="3" style="background-color:#333; border-right: 1px solid #666;"></td>
<td class="<?php echo $_estilo; ?>" colspan="3" style="background-color:#333; border-right: 1px solid #666;"></td>
<td class="<?php echo $_estilo; ?>" colspan="3" style="background-color:#333; border-right: 1px solid #666;"></td>
<td class="<?php echo $_estilo; ?>" colspan="3" style="background-color:#333; border-right: 1px solid #666;"></td>
<td class="<?php echo $_estilo; ?>" colspan="3" style="background-color:#333; border-right: 1px solid #666;"></td>
<?php
} ?>
</tr> <?php
} ?>
<tr>
<td scope="colgroup" colspan="16"></td>
</tr>
<?php if($minMonto){?>
<tr>
<td scope="colgroup" colspan="2"></td>
<td scope="colgroup" colspan="3" style="font-weight:bold; text-align: right;">Monto Mínimo</td>
<td scope="colgroup" colspan="2" style="font-weight:bold;"><?php echo "$ ".$minMonto;?></td>
<td scope="colgroup" colspan="2"></td>
</tr>
<?php }?>
<?php if($cantMinima){?>
<tr>
<td scope="colgroup" colspan="2" ></td>
<td scope="colgroup" colspan="3" style="font-weight:bold; text-align: right;">Cantidad Total Mínima</td>
<td scope="colgroup" colspan="2" style="font-weight:bold;"><?php echo $cantMinima;?> </td>
<td scope="colgroup" colspan="2"></td>
</tr>
<?php }?>
<?php if($minReferencias){?>
<tr>
<td scope="colgroup" colspan="2" ></td>
<td scope="colgroup" colspan="3" style="font-weight:bold; text-align: right;">Mínimo de Referencias</td>
<td scope="colgroup" colspan="2" style="font-weight:bold;"><?php echo $minReferencias;?> </td>
<td scope="colgroup" colspan="2"></td>
</tr>
<?php }?>
<?php if($condPago){?>
<tr>
<td scope="colgroup" colspan="8" style="font-weight:bold;">CONDICIONES DE PAGO: </td>
</tr>
<?php
$condicionesPago = explode(",", $condPago);
if($condicionesPago){
for( $j=0; $j < count($condicionesPago); $j++ ) {
$condicionesDePago = DataManager::getCondicionesDePago(0, 0, NULL, $condicionesPago[$j]);
if (count($condicionesDePago)) {
foreach ($condicionesDePago as $k => $condPago) {
$condPagoCodigo = $condPago["IdCondPago"];
$nombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condPago['condtipo']);
$condPagoDias = "(";
$condPagoDias .= empty($condPago['Dias1CP']) ? '0' : $condPago['Dias1CP'];
$condPagoDias .= empty($condPago['Dias2CP']) ? '' : ', '.$condPago['Dias2CP'];
$condPagoDias .= empty($condPago['Dias3CP']) ? '' : ', '.$condPago['Dias3CP'];
$condPagoDias .= empty($condPago['Dias4CP']) ? '' : ', '.$condPago['Dias4CP'];
$condPagoDias .= empty($condPago['Dias5CP']) ? '' : ', '.$condPago['Dias5CP'];
$condPagoDias .= " Días)";
$condPagoDias .= ($condPago['Porcentaje1CP'] == '0.00') ? '' : ' '.$condPago['Porcentaje1CP'].' %';
$condNombre = $nombre." ".$condPagoDias;
}
}
?>
<tr>
<td scope="colgroup" colspan="1" ></td>
<td scope="colgroup" colspan="7" ><?php echo utf8_decode($condNombre); ?></td>
</tr>
<?php
}
}
}?>
<?php if($observacion){?>
<tr>
<td scope="colgroup" colspan="8" style="font-weight:bold;">OBSERVACIÓN</td>
</tr>
<tr>
<td scope="colgroup" colspan="1" ></td>
<td scope="colgroup" colspan="7" style="height:50px;" ><?php echo $observacion; ?></td>
</tr>
<?php }?>
<tr>
<td scope="colgroup" colspan="8" ></td>
</tr>
<?php
}
} else { ?>
<tr>
<td scope="colgroup" colspan="8" style="border:1px solid #666">No se encontraron condiciones.</td>
</tr> <?php
} ?>
</tbody>
</table> <?php
break;
case 'Propuesta': ?>
<table width="600">
<thead>
<tr>
<th scope="colgroup" colspan="9" align="center" style="height:100px;"><?php echo $cabecera; ?></th>
</tr>
<tr>
<th scope="colgroup" rowspan="2" colspan="3" align="center" style="font-size:24px; color:#117db6; border:1px solid #666" ><?php echo $tipo; ?></th>
<th scope="colgroup" colspan="6" align="center" style="font-size:24px; color:#117db6; border:1px solid #666"></th>
</tr>
<tr>
<th scope="colgroup" colspan="6" align="right" style="border:1px solid #666">
<?php echo "Buenos Aires, ".date("d")." de ".Mes(date("m"))." de ".date("Y"); ?>
</th>
</tr>
<tr><th scope="colgroup" colspan="9"></th></tr>
<tr><th scope="colgroup" colspan="9" align="left">Estimada Farmacia,</th></tr>
<tr><th scope="colgroup" colspan="9"></th></tr>
<tr><th scope="colgroup" colspan="9" align="left">Agradeciendo el tiempo dedicado y de cara a consolidar nuestra relación directa,</th></tr>
<tr><th scope="colgroup" colspan="9" align="left"> detallo a continuación la propuesta comercial:</th></tr>
<tr><th scope="colgroup" colspan="9"></th></tr>
<tr><th scope="colgroup" colspan="9" align="left">Modalidad: Transfer entregado a través de su droguería habitual.</th></tr>
<tr><th scope="colgroup" colspan="9"></th></tr>
<tr>
<td scope="colgroup" align="center" class="impar">Producto</td>
<td scope="colgroup" align="center" class="impar"></td>
<td scope="colgroup" align="center" class="impar"></td>
<td scope="colgroup" align="center" class="impar"></td>
<td scope="colgroup"></td>
<td scope="colgroup" align="center" class="impar">Producto</td>
<td scope="colgroup" align="center" class="impar"></td>
<td scope="colgroup" align="center" class="impar"></td>
<td scope="colgroup" align="center" class="impar"></td>
</tr>
</thead>
<tbody>
<?php
if ($condId) {
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
$style = 0;
for($k = 0; $k < count($articulosCond); $k++){
//foreach ($articulosCond as $k => $artCond) {
$rentabilidad = $rentabilidad2 = $pvp = $pvp2 = 0;
$artCond = $articulosCond[$k];
$condArtIdArt = $artCond['cartidart'];
$condArtPrecio = $artCond["cartprecio"]; //(PSL)
$medicinal = DataManager::getArticulo('artmedicinal', $condArtIdArt, $empresa, $laboratorio);
$condArtNombre = DataManager::getArticulo('artnombre', $condArtIdArt, $empresa, $laboratorio);
$condArtDescripcion = DataManager::getArticulo('artdescripcion', $condArtIdArt, $empresa, $laboratorio);
$artImagen = DataManager::getArticulo('artimagen', $condArtIdArt, $empresa, $laboratorio);
//$artImagen = $_articulo->__get('Imagen');
$imagenObject = DataManager::newObjectOfClass('TImagen', $artImagen);
$imagen = $imagenObject->__get('Imagen');
$producto = ($imagen) ? "https://www.neo-farma.com.ar/pedidos/images/imagenes/".$imagen : "/pedidos/images/sin_imagen.png";
//Calcular PVP
$condArtMedicinal= DataManager::getArticulo('artmedicinal', $condArtIdArt, $empresa, $laboratorio);
$condArtIva = DataManager::getArticulo('artiva', $condArtIdArt, $empresa, $laboratorio);
$condArtGanancia = DataManager::getArticulo('artganancia', $condArtIdArt, $empresa, $laboratorio);
$pvp = dac_calcularPVP($condArtPrecio, $condArtIva, $condArtMedicinal, $empresa, $condArtGanancia);
//$fechaInicio
$abmArt = DataManager::getDetalleArticuloAbm(8, date("Y"), 220181, $condArtIdArt, 'TL');
$abmDesc = ($abmArt[0]['abmdesc'] * $p1) / 100;
//$rentabilidad = (1 - ( ( $p1 - $abmDesc ) / $pvp)); EN EXCEL
$abmDesc = number_format($abmDesc,3,'.','');
$rentabilidad = $p1 - $abmDesc;
$rentabilidad = number_format($rentabilidad,3,'.','');
$rentabilidad = $rentabilidad / $pvp;
$rentabilidad = number_format($rentabilidad,3,'.','');
$rentabilidad = ceil((1 - $rentabilidad) * 100);
$rentabilidad = number_format($rentabilidad,0,'.','');
$condArtCantMin = empty($artCond['cartcantmin'])? '' : $artCond['cartcantmin'];
//*******************//
if($k+1 < count($articulosCond)){
$artCond2 = $articulosCond[$k+1];
$condArtIdArt2 = $artCond2['cartidart'];
$condArtPrecio2 = $artCond["cartprecio"]; //(PSL)
$condArtNombre2 = DataManager::getArticulo('artnombre', $condArtIdArt2, $empresa, $laboratorio);
$condArtDescripcion2 = DataManager::getArticulo('artdescripcion', $condArtIdArt, $empresa, $laboratorio);
$artImagen2 = DataManager::getArticulo('artimagen', $condArtIdArt2, $empresa, $laboratorio);
//$artImagen = $_articulo->__get('Imagen');
$imagenObject2 = DataManager::newObjectOfClass('TImagen', $artImagen2);
$imagen2 = $imagenObject2->__get('Imagen');
$producto2 = ($imagen2) ? "https://www.neo-farma.com.ar/pedidos/images/imagenes/".$imagen2 : "/pedidos/images/sin_imagen.png";
//Calcular PVP
$condArtMedicinal= DataManager::getArticulo('artmedicinal', $condArtIdArt2, $empresa, $laboratorio);
$condArtIva = DataManager::getArticulo('artiva', $condArtIdArt2, $empresa, $laboratorio);
$condArtGanancia = DataManager::getArticulo('artganancia', $condArtIdArt2, $empresa, $laboratorio);
$pvp2 = dac_calcularPVP($condArtPrecio2, $condArtIva, $condArtMedicinal, $empresa, $condArtGanancia);
//$fechaInicio
$abmArt2 = DataManager::getDetalleArticuloAbm(8, date("Y"), 220181, $condArtIdArt2, 'TL');
$abmDesc2 = ($abmArt2[0]['abmdesc'] * $condArtPrecio2) / 100;
//$rentabilidad = (1 - ( ( $p1 - $abmDesc ) / $pvp)); EN EXCEL
$abmDesc2 = number_format($abmDesc2,3,'.','');
$rentabilidad2 = $p12 - $abmDesc2;
$rentabilidad2 = number_format($rentabilidad2,3,'.','');
$rentabilidad2 = $rentabilidad2 / $pvp2;
$rentabilidad2 = number_format($rentabilidad2,3,'.','');
$rentabilidad2 = ceil((1 - $rentabilidad2) * 100);
$rentabilidad2 = number_format($rentabilidad2,0,'.','');
$condArtCantMin2 = empty($artCond2['cartcantmin'])? '' : $artCond2['cartcantmin'];
}
//********************//
$_estilo = (($style % 2) == 0)? "par" : "impar";
$style ++;
?>
<tr height="20"><td colspan="9"></td></tr>
<tr height="20">
<td width="180" class="<?php echo $_estilo; ?>" colspan="4" align="left" style="font-weight: bold;">
<?php echo $condArtIdArt." - ".utf8_decode($condArtNombre); ?>
</td>
<td width="20"></td>
<td width="180" class="<?php echo $_estilo; ?>" colspan="4" align="left" style="font-weight: bold;">
<?php echo $condArtIdArt2." - ".utf8_decode($condArtNombre2); ?>
</td>
</tr>
<tr height="25">
<td width="100" class="<?php echo $_estilo; ?>" rowspan="4" align="center">
<img src="<?php echo $producto; ?>" alt="Imagen" width="95" height="95"/>
</td>
<td width="120" class="<?php echo $_estilo; ?>" rowspan="4" colspan="2" valign="middle" style="font-size: 10px; font-weight:normal;">
<?php echo $condArtDescripcion; ?>
</td>
<td width="60" class="<?php echo $_estilo; ?>" align="left" style="font-size: 10; font-weight: bold;">
Rentab
</td>
<td width="20"></td>
<td width="100" class="<?php echo $_estilo; ?>" rowspan="4" align="center">
<img src="<?php echo $producto2; ?>" alt="Imagen" width="95" height="95"/>
</td>
<td width="120" class="<?php echo $_estilo; ?>" rowspan="4" colspan="2" valign="middle" style="font-size: 10px; font-weight:normal;">
<?php echo $condArtDescripcion2; ?>
</td>
<td width="60" class="<?php echo $_estilo; ?>" align="left" style="font-size: 10; font-weight: bold;">
Rentab
</td>
</tr>
<tr height="25">
<td class="<?php echo $_estilo; ?>" width="60" align="center" style="font-weight: bold;">
<?php echo $rentabilidad." %"; ?></td>
<td width="20"></td>
<td class="<?php echo $_estilo; ?>" width="60" align="center" style="font-weight: bold;">
<?php echo $rentabilidad2." %"; ?></td>
</tr>
<tr height="25">
<td class="<?php echo $_estilo; ?>" width="60" align="left" style="font-size: 10; font-weight: bold;">PVP</td>
<td width="20"></td>
<td class="<?php echo $_estilo; ?>" width="60" align="left" style="font-size: 10; font-weight: bold;">PVP</td>
</tr>
<tr height="25">
<td class="<?php echo $_estilo; ?>" width="60" align="center" style="font-weight: bold;">
<?php echo "$ ".number_format($pvp,2,'.',''); ?></td>
<td width="20"></td>
<td class="<?php echo $_estilo; ?>" width="60" align="center" style="font-weight: bold;">
<?php echo "$ ".number_format($pvp2,2,'.',''); ?></td>
</tr>
<tr height="20"><td colspan="9"></td></tr>
<?php
$k++;
} ?>
<tr><td scope="colgroup" colspan="9"></td></tr>
<tr><td scope="colgroup" colspan="9" align="left">Notas: PVP Precio de venta al Público. </td></tr>
<tr><td scope="colgroup" colspan="9"></td></tr>
<tr><td scope="colgroup" colspan="9" align="left" style="font-weight: bold;">* Los precios son los detallados a la fecha y pueden sufrir modificaciones. </td></tr>
<tr><td scope="colgroup" colspan="9"></td></tr>
<tr><td scope="colgroup" colspan="9" align="left">Cualquier inquietud no dude en consultarme y me estaré comunicando con ustede </td></tr>
<tr><td scope="colgroup" colspan="9" align="left">a la brevedad. </td></tr>
<tr><td scope="colgroup" colspan="9"></td></tr>
<tr><td scope="colgroup" colspan="9" align="left">Saludos cordiales.</td></tr>
<tr><td scope="colgroup" colspan="9"></td></tr>
<?php
}
} else { ?>
<tr>
<td scope="colgroup" colspan="9" style="border:1px solid #666">No se encontraron condiciones.</td>
</tr> <?php
} ?>
</tbody>
<tfoot>
<tr>
<th scope="colgroup" colspan="9" align="center" style="height:100px;"><?php echo $pie; ?></th>
</tr>
</tfoot>
</table> <?php
break;
default: exit;
break;
} ?>
</body>
</html>
<file_sep>/articulos/logica/ajax/duplicar.condicion.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="A"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$dtHoy = new DateTime("now");
$dtManana = clone $dtHoy;
$dtManana->modify("+1 day");
$dtAyer = clone $dtHoy;
$dtAyer->modify("-1 day");
//calculo ULTIMO DÍA del mes de mañana
$dtFin = clone $dtManana;
$dtFin->setDate($dtFin->format('Y'), $dtFin->format('m'), $dtFin->format("t"));
//Se consultarán TODAS las condiciones comerciales donde su FECHA de FIN sea mayor o igual al día de MAÑANA
$condiciones = DataManager::getCondiciones(0, 0, '', '', '', '', '', '', $dtManana->format("Y-m-d"));
if (count($condiciones)) {
//------------------------------//
// Lee cada condición comercial //
foreach ($condiciones as $k => $cond) {
$condId = $cond['condid'];
if ($condId) {
$condObject = DataManager::newObjectOfClass('TCondicionComercial', $condId);
$condEmpresa = $condObject->__get('Empresa');
$condLaboratorio= $condObject->__get('Laboratorio');
$condFechaInicio= $condObject->__get('FechaInicio');
$fechaInicio = new DateTime($condFechaInicio);
$condFechaFin = $condObject->__get('FechaFin');
//Si la fecha de Inicio de la condicion es MENOR a MAÑANA
if($fechaInicio->format("Y-m-d") < $dtManana->format("Y-m-d")){
//------------------
//MODIFICO fecha FIN de condición vigente para que cierre HOY
$condObject->__set('FechaFin', $dtHoy->format("Y-m-d"));
DataManagerHiper::updateSimpleObject($condObject, $condId);
DataManager::updateSimpleObject($condObject);
//----------------
//CLONO EL OBJETO PARA DUPLICAR
$condObjectDup = DataManager::newObjectOfClass('TCondicionComercial');
$condObjectDup->__set('Empresa' , $condEmpresa);
$condObjectDup->__set('Laboratorio' , $condLaboratorio);
$condObjectDup->__set('Cuentas' , $condObject->__get('Cuentas'));
$condObjectDup->__set('Nombre' , $condObject->__get('Nombre'));
$condObjectDup->__set('Tipo' , $condObject->__get('Tipo'));
$condObjectDup->__set('CondicionPago' , $condObject->__get('CondicionPago'));
$condObjectDup->__set('CantidadMinima' , $condObject->__get('CantidadMinima'));
$condObjectDup->__set('MinimoReferencias' , $condObject->__get('MinimoReferencias'));
$condObjectDup->__set('MinimoMonto' , $condObject->__get('MinimoMonto'));
$condObjectDup->__set('Observacion' , $condObject->__get('Observacion'));
$condObjectDup->__set('Cantidad' , $condObject->__get('Cantidad'));
$condObjectDup->__set('Bonif1' , $condObject->__get('Bonif1'));
$condObjectDup->__set('Bonif2' , $condObject->__get('Bonif2'));
$condObjectDup->__set('Desc1' , $condObject->__get('Desc1'));
$condObjectDup->__set('Desc2' , $condObject->__get('Desc2'));
$condObjectDup->__set('FechaInicio' , $dtManana->format("Y-m-d"));
$condObjectDup->__set('FechaFin' , $dtFin->format("Y-m-d"));
$condObjectDup->__set('UsrUpdate' , $_SESSION["_usrid"]);
$condObjectDup->__set('LastUpdate' , date("Y-m-d"));
$condObjectDup->__set('Activa' , 1);
$condObjectDup->__set('Lista' , $condObject->__get('Lista'));
$condObjectDup->__set('ID' , $condObjectDup->__newID());
DataManagerHiper::_getConnection('Hiper'); //Controla conexión a HiperWin
$IDCondDup = DataManager::insertSimpleObject($condObjectDup);
DataManagerHiper::insertSimpleObject($condObjectDup, $IDCondDup);
//------------------//
// Cargo Artículos //
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
foreach ($articulosCond as $k => $detArt) {
$detId = $detArt['cartid'];
$detIdart = $detArt['cartidart'];
$artPrecio = DataManager::getArticulo('artpreciolista', $detIdart, $condEmpresa, $condLaboratorio);
$artPrecio = (empty($artPrecio)) ? '0.000' : $artPrecio;
//------------------------------//
// Clono Detalle de Artículo //
$condArtObject = DataManager::newObjectOfClass('TCondicionComercialArt', $detId);
//$condArtObjectDup = clone $condArtObject;
//modifico los datos del duplicado
$condArtObjectDup = DataManager::newObjectOfClass('TCondicionComercialArt');
$condArtObjectDup->__set('Articulo' , $condArtObject->__get('Articulo'));
$condArtObjectDup->__set('Digitado' , $condArtObject->__get('Digitado'));
$condArtObjectDup->__set('CantidadMinima' , $condArtObject->__get('CantidadMinima'));
$condArtObjectDup->__set('OAM' , $condArtObject->__get('OAM'));
$condArtObjectDup->__set('Oferta' , $condArtObject->__get('Oferta'));
$condArtObjectDup->__set('Activo' , $condArtObject->__get('Activo'));
$condArtObjectDup->__set('Condicion' , $IDCondDup);
$condArtObjectDup->__set('Precio' , $artPrecio);
$condArtObjectDup->__set('ID' , $condArtObjectDup->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDArt = DataManager::insertSimpleObject($condArtObjectDup);
DataManagerHiper::insertSimpleObject($condArtObjectDup, $IDCondDup);
//----------------------------------//
// Creo Detalle de Bonificaciones //
$articulosBonif = DataManager::getCondicionBonificaciones($condId, $detIdart);
if (count($articulosBonif)) {
foreach ($articulosBonif as $j => $artBonif) {
$artBonifId = $artBonif['cbid'];
$condArtBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif', $artBonifId);
//------------------------------//
// Duplico Detalle de Artículo //
$condArtBonifObjectDup = DataManager::newObjectOfClass('TCondicionComercialBonif');
//$condArtBonifObjectDup = clone $condArtBonifObject;
$condArtBonifObjectDup->__set('Articulo' , $condArtBonifObject->__get('Articulo'));
$condArtBonifObjectDup->__set('Cantidad' , $condArtBonifObject->__get('Cantidad'));
$condArtBonifObjectDup->__set('Bonif1' , $condArtBonifObject->__get('Bonif1'));
$condArtBonifObjectDup->__set('Bonif2' , $condArtBonifObject->__get('Bonif2'));
$condArtBonifObjectDup->__set('Desc1' , $condArtBonifObject->__get('Desc1'));
$condArtBonifObjectDup->__set('Desc2' , $condArtBonifObject->__get('Desc2'));
$condArtBonifObjectDup->__set('Activo' , $condArtBonifObject->__get('Activo'));
$condArtBonifObjectDup->__set('Condicion' , $IDCondDup);
$condArtBonifObjectDup->__set('ID' , $condArtBonifObjectDup->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDArt = DataManager::insertSimpleObject($condArtBonifObjectDup);
DataManagerHiper::insertSimpleObject($condArtBonifObjectDup, $IDCondDup);
}
}
}
}
$movimiento = 'DUPLICA_ID_'.$condId;
$movTipo = 'INSERT';
} else {
//Si la fecha de INICIO es MAYOR O IGUAL a MAÑANA, SOLO se actualizan los precios???
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
foreach ($articulosCond as $k => $detArt) {
$detId = $detArt['cartid'];
$detIdart = $detArt['cartidart'];
$artPrecio = DataManager::getArticulo('artpreciolista', $detIdart, $condEmpresa, $condLaboratorio);
$artPrecio = (empty($artPrecio)) ? '0.000' : $artPrecio;
//+-----------------------------//
// Update precios de Artículo //
$condArtObject = DataManager::newObjectOfClass('TCondicionComercialArt', $detId);
$condArtObject->__set('Precio', $artPrecio);
DataManagerHiper::updateSimpleObject($condArtObject, $detId);
DataManager::updateSimpleObject($condArtObject);
}
}
$movimiento = 'PRECIO_ID_'.$condId;
$movTipo = 'UPDATE';
}
//-----------------------//
// Registro MOVIMIENTO //
dac_registrarMovimiento($movimiento, $movTipo, 'TCondicionComercial', $condId);
} else {
echo "Error al consultar los registros."; exit;
}
}
} else {
echo "No se encontraron registros para duplicar."; exit;
}
echo "1"; exit; ?><file_sep>/informes/logica/exportar.pedidos.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
//*******************************************
$fechaDesde = (isset($_POST['fechaDesde'])) ? $_POST['fechaDesde'] : NULL;
$fechaHasta = (isset($_POST['fechaHasta'])) ? $_POST['fechaHasta'] : NULL;
//*******************************************
if(empty($fechaDesde) || empty($fechaHasta)){
echo "Debe completar las fechas para exportar"; exit;
}
$fechaInicio = new DateTime(dac_invertirFecha($fechaDesde));
$fechaFin = new DateTime(dac_invertirFecha($fechaHasta));
$fechaFin->modify("+1 day");
//*************************************************
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=PedidosWeb-".date('d-m-y').".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos .::</TITLE>
<head></head>
<body>
<table border="0">
<thead>
<tr>
<TD width="1px">Fecha</TD>
<TD width="1px">Vendedor</TD>
<TD width="1px">Cliente</TD>
<TD width="1px">Pedido</TD>
<TD width="1px">Lab</TD>
<TD width="1px">IdArt</TD>
<TD width="1px">Cant</TD>
<TD width="1px">Precio</TD>
<TD width="1px">B1</TD> <TD width="1px">B2</TD>
<TD width="1px">D1</TD> <TD width="1px">D2</TD> <TD width="1px">D3</TD>
<TD width="1px">CondPago</TD>
<TD width="1px">OC</TD>
<TD width="1px">Observación</TD>
</tr>
</thead>
<?php
$pedidos = DataManager::getPedidosEntre(0, $fechaInicio->format("Y-m-d"), $fechaFin->format("Y-m-d"));
if($pedidos){
foreach ($pedidos as $k => $pedido) {
$nroPedido = $pedido["pidpedido"];
$detalles = DataManager::getPedidos(NULL, 0, $nroPedido, NULL, NULL, NULL);
if ($detalles) {
foreach ($detalles as $j => $detalle) {
$_idusuario = $detalle["pidusr"];
//datos para control
$_idemp = $detalle["pidemp"];
$_idpack = $detalle["pidpack"];
$_idlista = $detalle["pidlista"];
//*****************//
$_fecha_pedido = substr($detalle['pfechapedido'], 0, 10);
$_nombreusr = DataManager::getUsuario('unombre', $_idusuario);
$_idcli = $detalle["pidcliente"];
$_nropedido = $detalle["pidpedido"];
$_idlab = $detalle["pidlab"];
$_idart = $detalle['pidart'];
//$_nombreart = DataManager::getArticulo('artnombre', $_idart, $_idemp, $_idlab);
$_cantidad = $detalle['pcantidad'];
$_precio = str_replace('EUR','', money_format('%.3n', $detalle['pprecio']));
$_b1 = ($detalle['pbonif1']) ? $detalle['pbonif1'] : '';
$_b2 = ($detalle['pbonif2']) ? $detalle['pbonif2'] : '';
$_desc1 = ($detalle['pdesc1']) ? $detalle['pdesc1'] : '';
$_desc2 = ($detalle['pdesc2']) ? $detalle['pdesc2'] : '';
$_desc3 = '';
$_condpago = $detalle["pidcondpago"];
$_ordencompra = ($detalle["pordencompra"] == 0) ? '' : $detalle["pordencompra"];
$_observacion = $detalle["pobservacion"];
echo sprintf("<tr align=\"left\">");
echo sprintf("<td >%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>", $_fecha_pedido, $_nombreusr, $_idcli, $_nropedido, $_idlab, $_idart, $_cantidad, $_precio, $_b1, $_b2, $_desc1, $_desc2, $_desc3, $_condpago, $_ordencompra, $_observacion);
echo sprintf("</tr>");
}
}
}
}
?>
</table>
</body>
</html>
<file_sep>/informes/insertar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!= "M" && $_SESSION["_usrrol"]!= "V"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_sms = empty($_GET['sms']) ? 0 : $_GET['sms'];
if ($_sms) {
$_tipo_informe = $_SESSION['inf_nombre'];
switch ($_sms) {
case 6: $_info = "Notificación enviada a Vendedores."; break;
} // mensaje de error
}
//generales
$_button_notificar = sprintf("<input type=\"submit\" id=\"btsExportar Tablasend\" name=\"_accion\" value=\"Notificar\"/>");
$_action_notificar = sprintf("/pedidos/informes/logica/new.noticia.php");
$btnExporTbl = sprintf("<input type=\"button\" id=\"btnExporTbl\" value=\"Exportar\" title=\"Exportar Tabla Seleccionada\"/>");
$btnExporReport = sprintf("<input type=\"button\" id=\"btnExporReport\" value=\"Exportar\" title=\"Exportar Informe Seleccionado\"/>");
?>
<div class="box_body"> <!-- datos -->
<div class="bloque_1">
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
<?php if ($_sms) {
if($_sms == 6){ ?>
<fieldset id='box_observacion' class="msg_alerta" style="display: block">
<div id="msg_atencion" align="center"><?php echo $_info; ?></div>
</fieldset> <?php
}
} ?>
</div>
<div class="temas2">
<a href="javascript:dac_exportar(11);">
<div class="box_mini2">
Comprobantes <br> <p>Neo-farma</p>
</div>
</a>
<?php if($_SESSION["_usrdni"] == "3035" || $_SESSION["_usrrol"]== "A" || $_SESSION["_usrrol"]== "G") { ?>
<a href="javascript:dac_exportar(22);" >
<div class="box_mini2">
Comprobantes <br> <p>Gezzi</p>
</div>
</a>
<?php } ?>
</div>
<div class="temas2">
<a href="https://neo-farma.com.ar/pedidos/informes/archivos/DevolucionesNeo.xls">
<div class="box_mini2">
Devoluciones <br> <p>Neo-farma</p>
</div>
</a>
<a href="https://neo-farma.com.ar/pedidos/informes/archivosgezzi/DevolucionesGezzi.xls" >
<div class="box_mini2">
Devoluciones <br> <p>Gezzi</p>
</div>
</a>
</div>
<div class="temas2">
<a href="javascript:dac_exportar(12);" >
<div class="box_mini2">
Deudas <br> <p>Neo-farma</p>
</div>
</a>
<?php if($_SESSION["_usrdni"] == "3035" || $_SESSION["_usrrol"]== "A" || $_SESSION["_usrrol"]== "G") { ?>
<a href="https://neo-farma.com.ar/pedidos/informes/archivosgezzi/deudores/30_Informe_de_Deudas.XLS" >
<div class="box_mini2">
Deudas <br> <p>Gezzi</p>
</div>
</a>
<?php } ?>
</div>
<div class="temas2">
<a href="https://neo-farma.com.ar/pedidos/informes/archivos/NotasValor.xls" >
<div class="box_mini2">
Notas de Valor <br> <p>Neo-farma</p>
</div>
</a>
</div>
<hr>
<?php if ($_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]== "M"){ ?>
<fieldset>
<legend>Archivos Únicos</legend>
<div class="bloque_6">
<select id="tipo_informeUnico" name="tipo_informeUnico">
<option value="0">Seleccione archivo...</option>
<option value="Ofertas">Ofertas</option>
<!--option value="Cantidades">Neo Cantidades</option>
<option value="Minoristas">Neo Minoristas</option>
<option value="NotasValor">Neo Notas de Valor</option>
<option value="PedidosPendientes">Neo Pedidos pendientes</option>
<option value="DevolucionesNeo">Neo Devoluciones</option-->
<!--option value="Stock">Neo Stock</option-->
<!--option value="PedidosPendientesGezzi">Gezzi Pedidos pendientes</option>
<option value="DevolucionesGezzi">Gezzi Devoluciones</option-->
</select>
</div>
<div class="bloque_5">
<input id="informesUnicos" class="file" type="file"/>
</div>
<div class="bloque_8">
<input type="button" id="enviar_informesUnicos" value="Enviar">
</div>
</fieldset>
<fieldset>
<legend>Archivos Múltiples (Máximo 20 archivos por vez)</legend>
<div class="bloque_6">
<select id="tipo_informe" name="tipo_informe">
<option value="0">Seleccione archivos...</option>
<!--option value="archivos/comprobantes">Neo Comprobantes</option>
<option value="archivos/deudores">Neo Deudas</option>
<option value="archivos/cartasdeporte">Neo Cartas de Porte</option-->
<option value="archivos/facturas/contrareembolso">Neo Facturas Contrareembolso</option>
<!--option value="archivosgezzi/comprobantes">Gezzi Comprobantes</option>
<option value="archivosgezzi/deudores">Gezzi Deudas</option>
<option value="archivosgezzi/cartasdeporte">Gezzi Cartas de Porte</option-->
</select>
</div>
<div class="bloque_5">
<input id="informes" class="file" type="file" multiple/>
</div>
<div class="bloque_8">
<input type="button" id="enviar_informes" value="Enviar">
</div>
</fieldset>
<?php } ?>
</div>
<div class="box_seccion">
<?php if ($_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]== "M"){ ?>
<form name="fm_noticia" method="post" action="<?php echo $_action_notificar;?>" enctype="multipart/form-data">
<fieldset>
<legend>Notificar Cambios</legend>
<div class="bloque_1">
<?php echo $_button_notificar; ?>
</div>
</fieldset>
</form>
<?php } ?>
<form id="exportInforme" action="#" method="POST">
<fieldset>
<legend>Exportar Informes</legend>
<div class="bloque_5">
<input id="fechaDesde" name="fechaDesde" type="text" placeholder="* DESDE" size="14" readonly/>
</div>
<div class="bloque_5">
<input id="fechaHasta" name="fechaHasta" type="text" placeholder="* HASTA" size="14" readonly/>
</div>
<div class="bloque_5">
<select id="exportReport">
<option value="0">Seleccione...</option>
<option value="llamadas">Llamadas</option>
<option value="transfers">Transfers</option>
<?php if ($_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]== "M"){ ?>
<option value="pedidos">Pedidos</option>
<!--option value="liqPendExce">Liquidaciones Pendientes Excedentes</option-->
<?php } ?>
</select>
</div>
<div class="bloque_5"><?php echo $btnExporReport; ?> </div>
</fieldset>
<fieldset>
<legend>Exportar Tablas</legend>
<?php if ($_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]== "M"){ ?>
<div class="bloque_5">
<select id="exportTable">
<option value="0">Seleccione...</option>
<!--option value="abm">Abm</option-->
<option value="articulo">Articulo</option>
<option value="cadena">Cadena</option>
<option value="cuentasCadena">Cuentas Cadena</option>
<option value="condicion">Condicion</option>
<option value="condicionArt">CondicionArt</option>
<option value="condicionBonif">CondicionBonif</option>
<option value="cuentas">Cuentas</option>
<option value="droguerias">Droguerias</option>
<option value="drogueriasCad">DrogueriasCAD</option>
<option value="transfers">Transfers</option>
<option value="proveedor">Proveedores</option>
</select>
</div>
<div class="bloque_5"><?php echo $btnExporTbl; ?> </div>
<?php } ?>
</fieldset>
<fieldset>
<legend>Importar Tablas</legend>
<?php if ($_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]== "M"){ ?>
<div class="bloque_5">
<select id="importTable" name="importTable">
<option value="0">Seleccione...</option>
<!--option value="abm">Abm</option-->
</select>
</div>
<div class="bloque_5">
<input type="button" id="sendImportFile" value="Importar">
</div>
<div class="bloque_1">
<input id="importTableFile" class="file" type="file"/>
</div>
<?php } ?>
</fieldset>
</form>
<fieldset>
<legend>Facturas Contrareembolso Actuales:</legend>
<div class="bloque_1">
<div class="lista"> <?php
$ruta = $_SERVER['DOCUMENT_ROOT'].'/pedidos/informes/archivos/facturas/contrareembolso/';
$data = dac_listar_directorios($ruta);
if($data){
foreach ($data as $file => $timestamp) {
echo $timestamp."</br>";
}
} else {
echo "No hay facturas subidas";
} ?>
</div>
</div>
</fieldset>
</div>
<!-- Scripts para IMPORTAR MULTIPLES ARCHIVOS -->
<script type="text/javascript" src="/pedidos/informes/logica/js/jquery.script.multifile.js"></script>
<script language="javascript" type="text/javascript">
$("#btnExporReport").click(function () {
//el control de fechas debería ser acá y no en el excel
switch($('select[id=exportReport]').val()){
case "0":
$('#box_error').css({'display':'block'});
$("#msg_error").html('Seleccione un informe.');
break;
case "llamadas":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.registro_llamadas.php');
document.forms["exportInforme"].submit();
break;
case "pedidos":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.pedidos.php');
document.forms["exportInforme"].submit();
break;
case "transfers":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.transfer.php');
document.forms["exportInforme"].submit();
break;
case "liqPendExce":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.liquidacionPendExce.php');
document.forms["exportInforme"].submit();
break;
}
});
$("#btnExporTbl").click(function () {
//el control de fechas debería ser acá y no en el excel
switch($('select[id=exportTable]').val()){
case "0":
$('#box_error').css({'display':'block'});
$("#msg_error").html('Seleccione un tabla.');
break;
case "transfers":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.tablatransfer.php');
document.forms["exportInforme"].submit();
break;
case "abm":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.tablaabm.php');
document.forms["exportInforme"].submit();
break;
case "cadena":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.tablacadenas.php');
document.forms["exportInforme"].submit();
break;
case "cuentasCadena":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.tablacuentascadenas.php');
document.forms["exportInforme"].submit();
break;
case "articulo":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.tablaarticulos.php');
document.forms["exportInforme"].submit();
break;
case "condicion":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.tablacondicion.php');
document.forms["exportInforme"].submit();
break;
case "condicionArt":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.tablacondicionArt.php');
document.forms["exportInforme"].submit();
break;
case "condicionBonif":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.tablacondicionBonif.php');
document.forms["exportInforme"].submit();
break;
case "cuentas":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.tablacuentas.php');
document.forms["exportInforme"].submit();
break;
case "droguerias":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.tabladroguerias.php');
document.forms["exportInforme"].submit();
break;
case "drogueriasCad":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.tabladrogueriasCAD.php');
document.forms["exportInforme"].submit();
break;
case "proveedor":
$('#exportInforme').attr('action', '/pedidos/informes/logica/exportar.tablaproveedor.php');
document.forms["exportInforme"].submit();
break;
}
});
</script>
<script type="text/javascript">
function dac_exportar(nro){
switch (nro){
case 11:
if (confirm("ATENCI\u00d3N: Se proceder\u00e1 a descargar un archivo por cada una de las zonas que le corresponda. Si no consigue hacerlo, p\u00f3ngase en contacto con el administrador de la web. Si no encuentra el archivo descargado, busque en la carpeta descargas de la PC. \u00A1Gracias!")){
<?php
$zona = explode(', ', $_SESSION["_usrzonas"]);
for($i = 0; $i < count($zona); $i++){
$_archivo = $_SERVER["DOCUMENT_ROOT"]."/pedidos/informes/archivos/comprobantes/".trim($zona[$i])."_Ventas_por_Vendedor.XLS";
if (file_exists($_archivo)){ ?>
archivo = <?php echo trim($zona[$i]); ?>+'_Ventas_por_Vendedor.XLS';
direccion = 'https://neo-farma.com.ar/pedidos/informes/archivos/comprobantes/'+archivo;
window.open(direccion, '_blank'); <?php
}else{ ?>
alert("No hay Ventas correspondiente a la zona <?php echo trim($zona[$i]); ?>"); <?php
}
} ?>
}
break;
case 12:
if (confirm("ATENCI\u00d3N: Se proceder\u00e1 a descargar un archivo por cada una de las zonas que le corresponda. Si no consigue hacerlo, p\u00f3ngase en contacto con el administrador de la web. Si no encuentra el archivo descargado, busque en la carpeta descargas de la PC. \u00A1Gracias!")){
<?php
$zona = explode(', ', $_SESSION["_usrzonas"]);
for($i = 0; $i < count($zona); $i++){
$_archivo = $_SERVER["DOCUMENT_ROOT"]."/pedidos/informes/archivos/comprobantes/".trim($zona[$i])."_Ventas_por_Vendedor.XLS";
if (file_exists($_archivo)){ ?>
archivo = <?php echo trim($zona[$i]); ?>+'_Informe_de_Deudas.XLS';
direccion = 'https://neo-farma.com.ar/pedidos/informes/archivos/deudores/'+archivo;
window.open(direccion, '_blank'); <?php
}else{ ?>
alert("No hay Deudores correspondiente a la zona <?php echo trim($zona[$i]); ?>"); <?php
}
} ?>
}
break;
}
}
</script>
<script type="text/javascript">
new JsDatePick({
useMode:2,
target:"fechaDesde",
dateFormat:"%d-%M-%Y"
});
/*********************************/
new JsDatePick({
useMode:2,
target:"fechaHasta",
dateFormat:"%d-%M-%Y"
});
</script><file_sep>/condicionpago/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_condid = empty($_REQUEST['condid']) ? 0 : $_REQUEST['condid'];
$readOnly = '';
if ($_condid) {
$_condcion = DataManager::newObjectOfClass('TCondicionPago', $_condid);
$_condcodigo = $_condcion->__get('Codigo');
$_condtipo = $_condcion->__get('Tipo');
$_condtipo1 = $_condcion->__get('Tipo1');
$_condtipo2 = $_condcion->__get('Tipo2');
$_condtipo3 = $_condcion->__get('Tipo3');
$_condtipo4 = $_condcion->__get('Tipo4');
$_condtipo5 = $_condcion->__get('Tipo5');
$_conddias = ($_condcion->__get('Dias') == '0') ? '' : $_condcion->__get('Dias');
$_conddias2 = ($_condcion->__get('Dias2') == '0') ? '' : $_condcion->__get('Dias2');
$_conddias3 = ($_condcion->__get('Dias3') == '0') ? '' : $_condcion->__get('Dias3');
$_conddias4 = ($_condcion->__get('Dias4') == '0') ? '' : $_condcion->__get('Dias4');
$_conddias5 = ($_condcion->__get('Dias5') == '0') ? '' : $_condcion->__get('Dias5');
$_condporcentaje= ($_condcion->__get('Porcentaje') == '0.00') ? '' : $_condcion->__get('Porcentaje');
$_condporcentaje2= ($_condcion->__get('Porcentaje2') == '0.00') ? '' : $_condcion->__get('Porcentaje2');
$_condporcentaje3= ($_condcion->__get('Porcentaje3') == '0.00') ? '' : $_condcion->__get('Porcentaje3');
$_condporcentaje4= ($_condcion->__get('Porcentaje4') == '0.00') ? '' : $_condcion->__get('Porcentaje4');
$_condporcentaje5= ($_condcion->__get('Porcentaje5') == '0.00') ? '' : $_condcion->__get('Porcentaje5');
$_condsigno = $_condcion->__get('Signo');
$_condsigno2 = $_condcion->__get('Signo2');
$_condsigno3 = $_condcion->__get('Signo3');
$_condsigno4 = $_condcion->__get('Signo4');
$_condsigno5 = $_condcion->__get('Signo5');
$_condfechadec = ($_condcion->__get('FechaFinDec') == '2001-01-01') ? '' : $_condcion->__get('FechaFinDec');
$_condfechadec2 = ($_condcion->__get('FechaFinDec2') == '2001-01-01') ? '' : $_condcion->__get('FechaFinDec2');
$_condfechadec3 = ($_condcion->__get('FechaFinDec3') == '2001-01-01') ? '' : $_condcion->__get('FechaFinDec3');
$_condfechadec4 = ($_condcion->__get('FechaFinDec4') == '2001-01-01') ? '' : $_condcion->__get('FechaFinDec4');
$_condfechadec5 = ($_condcion->__get('FechaFinDec5') == '2001-01-01') ? '' : $_condcion->__get('FechaFinDec5');
$_conddecrece = $_condcion->__get('Decrece');
$_condcuotas = ($_condcion->__get('Cantidad') == 0) ? '' : $_condcion->__get('Cantidad');
$_condactiva = $_condcion->__get('Activa');
} else {
$_condcodigo = "";
$_condtipo = "";
$_condtipo1 = "";
$_condtipo2 = "";
$_condtipo3 = "";
$_condtipo4 = "";
$_condtipo5 = "";
$_conddias = "";
$_conddias2 = "";
$_conddias3 = "";
$_conddias4 = "";
$_conddias5 = "";
$_condporcentaje= "";
$_condporcentaje2= "";
$_condporcentaje3= "";
$_condporcentaje4= "";
$_condporcentaje5= "";
$_condsigno = "";
$_condsigno2 = "";
$_condsigno3 = "";
$_condsigno4 = "";
$_condsigno5 = "";
$_condfechadec = "";
$_condfechadec2 = "";
$_condfechadec3 = "";
$_condfechadec4 = "";
$_condfechadec5 = "";
$_conddecrece = "";
$_condcuotas = "";
$_condactiva = "";
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "condiciones_pago";
$_subsection = "nueva_condicion_neo";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<div class="box_body">
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<form id="fmCondicionDePago" name="fmCondicionDePago" method="post" action="<?php echo $_action;?>">
<fieldset>
<input type="hidden" name="condid" value="<?php echo @$_condid;?>">
<legend>Condición</legend>
<div class="bloque_8">
<label for="condcodigo">Código</label>
<input name="condcodigo" type="text" value="<?php echo @$_condcodigo;?>" readonly>
</div>
<div class="bloque_4">
<label for="condtipo">Condición</label>
<?php
$condicionesTipo = DataManager::getCondicionesDePagoTipo();
if (count($condicionesTipo)) { ?>
<select name="condtipo">
<option id="0" value="" selected></option> <?php
foreach ($condicionesTipo as $j => $condTipo) {
$tipoID = $condTipo['ID'];
$tipoNombre = $condTipo['Descripcion'];
$selected = ($_condtipo == $tipoID) ? "selected" : ""; ?>
<option id="<?php echo $tipoID; ?>" value="<?php echo $tipoID; ?>" <?php echo $selected; ?>><?php echo $tipoNombre; ?> </option> <?php
} ?>
</select>
<?php } ?>
</div>
<div class="bloque_8">
<label for="condcuotas">Cuotas</label>
<input name="condcuotas" type="text" maxlength="2" value="<?php echo @$_condcuotas;?>">
</div>
<div class="bloque_8">
<label for="conddecrece">Decrece</label>
<select name="conddecrece">
<option id="0" value="N" selected>N</option> <?php
$selected = ($_conddecrece == 'S') ? "selected" : "";
?> <option id="1" value="S" <?php echo $selected;?>>S</option>
</select>
</div>
<hr>
<div class="bloque_6">
<label for="condtipo1">Condición</label>
<?php
if (count($condicionesTipo)) { ?>
<select name="condtipo1">
<option id="0" value="" selected></option> <?php
foreach ($condicionesTipo as $j => $condTipo) {
$tipoID = $condTipo['ID'];
$tipoNombre = $condTipo['Descripcion'];
$selected = ($_condtipo1 == $tipoID) ? "selected" : ""; ?>
<option id="<?php echo $tipoID; ?>" value="<?php echo $tipoID; ?>" <?php echo $selected; ?>><?php echo $tipoNombre; ?> </option> <?php
} ?>
</select>
<?php } ?>
</div>
<div class="bloque_8">
<label for="conddias1">Días</label>
<?php $readOnly = (!empty($_condfechadec)) ? 'readonly="readonly"' : ''; ?>
<input name="conddias1" type="text" maxlength="3" value="<?php echo @$_conddias;?>" <?php echo $readOnly;?>>
</div>
<div class="bloque_8">
<label for="condporcentaje1">%</label>
<input name="condporcentaje1" type="text" maxlength="1" value="<?php echo @$_condporcentaje;?>" />
</div>
<div class="bloque_8">
<label for="condsigno1">Signo</label>
<select name="condsigno1">
<option value="" selected></option> <?php
$selected = ($_condsigno) ? "selected" : "";
?> <option value="%" <?php echo $selected;?>>%</option>
</select>
</div>
<div class="bloque_7">
<label for="condfechadec1">Hasta el día</label>
<input name="condfechadec1" id="condfechadec1" type="text" value="<?php echo @$_condfechadec;?>" readonly/>
</div>
<hr>
<div class="bloque_6">
<label for="condtipo2">Condición</label>
<?php
if (count($condicionesTipo)) { ?>
<select name="condtipo2">
<option id="0" value="" selected></option> <?php
foreach ($condicionesTipo as $j => $condTipo) {
$tipoID = $condTipo['ID'];
$tipoNombre = $condTipo['Descripcion'];
$selected = ($_condtipo2 == $tipoID) ? "selected" : ""; ?>
<option id="<?php echo $tipoID; ?>" value="<?php echo $tipoID; ?>" <?php echo $selected; ?>><?php echo $tipoNombre; ?> </option> <?php
} ?>
</select>
<?php } ?>
</div>
<div class="bloque_8">
<label for="conddias2">Días</label>
<?php $readOnly = (!empty($_condfechadec2)) ? 'readonly="readonly"' : ''; ?>
<input name="conddias2" type="text" maxlength="3" value="<?php echo @$_conddias2;?>" <?php echo $readOnly;?>>
</div>
<div class="bloque_8">
<label for="condporcentaje2">%</label>
<input name="condporcentaje2" type="text" maxlength="1" value="<?php echo @$_condporcentaje2;?>"/>
</div>
<div class="bloque_8">
<label for="condsigno2">Signo</label>
<select name="condsigno2">
<option value="" selected></option> <?php
$selected = ($_condsigno2) ? "selected" : "";
?> <option value="%" <?php echo $selected;?>>%</option>
</select>
</div>
<div class="bloque_7">
<label for="condfechadec2">Hasta el día</label>
<input name="condfechadec2" id="condfechadec2" type="text" value="<?php echo @$_condfechadec2;?>" readonly/>
</div>
<hr>
<div class="bloque_6">
<label for="condtipo3">Condición</label>
<?php
if (count($condicionesTipo)) { ?>
<select name="condtipo3">
<option id="0" value="" selected></option> <?php
foreach ($condicionesTipo as $j => $condTipo) {
$tipoID = $condTipo['ID'];
$tipoNombre = $condTipo['Descripcion'];
$selected = ($_condtipo3 == $tipoID) ? "selected" : ""; ?>
<option id="<?php echo $tipoID; ?>" value="<?php echo $tipoID; ?>" <?php echo $selected; ?>><?php echo $tipoNombre; ?> </option> <?php
} ?>
</select>
<?php } ?>
</div>
<div class="bloque_8">
<label for="conddias3">Días</label>
<?php $readOnly = (!empty($_condfechadec3)) ? 'readonly="readonly"' : ''; ?>
<input name="conddias3" type="text" maxlength="3" value="<?php echo @$_conddias3;?>" <?php echo $readOnly;?>>
</div>
<div class="bloque_8">
<label for="condporcentaje3">%</label>
<input name="condporcentaje3" type="text" maxlength="1" value="<?php echo @$_condporcentaje3;?>"/>
</div>
<div class="bloque_8">
<label for="condsigno3">Signo</label>
<select name="condsigno3">
<option value="" selected></option> <?php
$selected = ($_condsigno3) ? "selected" : "";
?> <option value="%" <?php echo $selected;?>>%</option>
</select>
</div>
<div class="bloque_7">
<label for="condfechadec3">Hasta el día</label>
<input name="condfechadec3" id="condfechadec3" type="text" value="<?php echo @$_condfechadec3;?>" readonly/>
</div>
<hr>
<div class="bloque_6">
<label for="condtipo4">Condición</label>
<?php
if (count($condicionesTipo)) { ?>
<select name="condtipo4">
<option id="0" value="" selected></option> <?php
foreach ($condicionesTipo as $j => $condTipo) {
$tipoID = $condTipo['ID'];
$tipoNombre = $condTipo['Descripcion'];
$selected = ($_condtipo4 == $tipoID) ? "selected" : ""; ?>
<option id="<?php echo $tipoID; ?>" value="<?php echo $tipoID; ?>" <?php echo $selected; ?>><?php echo $tipoNombre; ?> </option> <?php
} ?>
</select>
<?php } ?>
</div>
<div class="bloque_8">
<label for="conddias4">Días</label>
<?php $readOnly = (!empty($_condfechadec4)) ? 'readonly="readonly"' : ''; ?>
<input name="conddias4" type="text" maxlength="3" value="<?php echo @$_conddias4;?>" <?php echo $readOnly;?>>
</div>
<div class="bloque_8">
<label for="condporcentaje4">%</label>
<input name="condporcentaje4" type="text" maxlength="1" value="<?php echo @$_condporcentaje4;?>"/>
</div>
<div class="bloque_8">
<label for="condsigno4">Signo</label>
<select name="condsigno4">
<option value="" selected></option> <?php
$selected = ($_condsigno4) ? "selected" : "";
?> <option value="%" <?php echo $selected;?>>%</option>
</select>
</div>
<div class="bloque_7">
<label for="condfechadec4">Hasta el día</label>
<input name="condfechadec4" id="condfechadec4" type="text" value="<?php echo @$_condfechadec4;?>" readonly/>
</div>
<hr>
<div class="bloque_6">
<label for="condtipo5">Condición</label>
<?php
if (count($condicionesTipo)) { ?>
<select name="condtipo5">
<option id="0" value="" selected></option> <?php
foreach ($condicionesTipo as $j => $condTipo) {
$tipoID = $condTipo['ID'];
$tipoNombre = $condTipo['Descripcion'];
$selected = ($_condtipo5 == $tipoID) ? "selected" : ""; ?>
<option id="<?php echo $tipoID; ?>" value="<?php echo $tipoID; ?>" <?php echo $selected; ?>><?php echo $tipoNombre; ?> </option> <?php
} ?>
</select>
<?php } ?>
</div>
<div class="bloque_8">
<label for="conddias5">Días</label>
<?php $readOnly = (!empty($_condfechadec5)) ? 'readonly="readonly"' : ''; ?>
<input name="conddias5" type="text" maxlength="3" value="<?php echo @$_conddias5;?>" <?php echo $readOnly;?>>
</div>
<div class="bloque_8">
<label for="condporcentaje5">%</label>
<input name="condporcentaje5" type="text" maxlength="1" value="<?php echo @$_condporcentaje5;?>"/>
</div>
<div class="bloque_8">
<label for="condsigno5">Signo</label>
<select name="condsigno5">
<option value="" selected></option> <?php
$selected = ($_condsigno5) ? "selected" : "";
?> <option value="%" <?php echo $selected;?>>%</option>
</select>
</div>
<div class="bloque_7">
<label for="condfechadec5">Hasta el día</label>
<input name="condfechadec5" id="condfechadec5" type="text" value="<?php echo @$_condfechadec5;?>" readonly/>
</div>
<hr>
<?php $urlSend = '/pedidos/condicionpago/logica/update.condicion.php';?>
<a id="btnSend" title="Enviar">
<img class="icon-send" onclick="javascript:dac_sendForm(fmCondicionDePago, '<?php echo $urlSend;?>');"/>
</a>
</fieldset>
</form>
</div> <!-- FIN box_body -->
<hr>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html>
<script language="javascript" type="text/javascript">
new JsDatePick({
useMode:2,
target:"condfechadec1",
dateFormat:"%d-%M-%Y"
});
new JsDatePick({
useMode:2,
target:"condfechadec2",
dateFormat:"%d-%M-%Y"
});
new JsDatePick({
useMode:2,
target:"condfechadec3",
dateFormat:"%d-%M-%Y"
});
new JsDatePick({
useMode:2,
target:"condfechadec4",
dateFormat:"%d-%M-%Y"
});
new JsDatePick({
useMode:2,
target:"condfechadec5",
dateFormat:"%d-%M-%Y"
});
</script><file_sep>/inicio/contenido1.inc.php
<script type="text/javascript">
/*** Funcion que muestra el div en la posicion del mouse*/
function showdiv(event, id){
document.getElementById('flotante'+id).style.display="inline";
//determina un margen de pixels del div al raton
margin=5;
var tempX = 0;
var tempY = 0;
//window.pageYOffset = devuelve el tamaño en pixels de la parte superior no visible (scroll) de la pagina
document.captureEvents(Event.MOUSEMOVE);
tempX = event.pageX;
tempY = event.pageY;
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;}
// Modificamos el contenido de la capa
/*document.getElementById('flotante'+id).innerHTML=text;*/
// Posicionamos la capa flotante
document.getElementById('flotante'+id).style.top = (tempY+margin)+"px";
document.getElementById('flotante'+id).style.left = (tempX+margin)+"px";
document.getElementById('flotante'+id).style.display='block';
return;
}
</script>
<div class="temas_noticias" style="margin-right:10px;" align="left">
<div class="tituloazul">Noticias <a class="noti" href="/pedidos/noticias/ver.php" title="Ver más noticias" style="color:#666; float:right;" ><?php echo " Ver más..."; ?></a></div>
<?php
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/noticias/': $_REQUEST['backURL'];
$_noticias = DataManager::getNoticiasActivas(0, 0, false);
if (count($_noticias )) {
foreach ($_noticias as $k => $_noticia) {
if ($x < 10){
$x ++;
$fecha = explode(" ", $_noticia["ntfecha"]);
//calcula días transcurridos a la fecha
$fecha_actual = date("Y-m-d");
$dias = (strtotime($fecha[0])-strtotime($fecha_actual))/86400;
$dias = abs($dias); $dias = floor($dias);
list($ano, $mes, $dia) = explode("-", $fecha[0]);
$Nfecha = $dia."-".$mes."-".$ano;
$Nid = $_noticia["idnt"];
$Ntitulo = $_noticia["nttitulo"];
$Ndescripcion = $_noticia["ntdescripcion"];
//$Nlink = $_noticia["ntlink"];
$NID = $_noticia["ntid"];
?>
<div class="box_noticia">
<div class="box_noticia_titulo">
<a class="noti" href="/pedidos/noticias/ver.php?idnt=<?php echo $Nid; ?>&backURL=<?php echo $backURL; ?>" onmouseover="showdiv(event, <?php echo $Nid; ?>);" onmousemove="showdiv(event, <?php echo $Nid; ?>);" onmouseout="javascript:document.getElementById('flotante<?php echo $Nid; ?>').style.display='none';"><?php echo $Ntitulo; ?></a>
<label id="fecha" style="color:#999; font-size:10px; float: right;"><?php echo "(".$Nfecha.")"; ?>
<?php if($dias <= 7){ ?>
<img src="/pedidos/images/icons/icono-news30.png" alt="nueva noticia" style="float:right;"/>
<?php } ?>
</label>
<br/>
</div>
<div id="flotante<?php echo $Nid; ?>" class="flotante">
<p class="itemcheck" style="font-size:11px;"><span><strong>
<div class="titulo"><?php echo $Ntitulo; ?></div>
<div class="noticia"><?php echo $Ndescripcion; ?></div>
</div>
</div>
<?php
}
}
}else {?>
<div class="box_noticia" align="center" style="background-color:#EBEBEB">
<div class="box_noticia_titulo">
<?php echo "ACTUALMENTE NO HAY NOTICIAS ACTIVAS. Gracias."; ?><br/>
</div>
</div>
<?php
}?>
</div> <!-- Fin temas noticias --> <file_sep>/cuentas/logica/ajax/getCuenta.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
$usrZonas = isset($_SESSION["_usrzonas"]) ? $_SESSION["_usrzonas"] : '';
//*************************************************
$empresa = (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
$activos = (isset($_POST['activos'])) ? $_POST['activos'] : NULL;
$tipo = (isset($_POST['tipo'])) ? $_POST['tipo'] : NULL;
$pag = (isset($_POST['pag'])) ? $_POST['pag'] : NULL;
$_LPP = (isset($_POST['rows'])) ? $_POST['rows'] : NULL;
//*************************************************
$cuentas = DataManager::getCuentas($pag, $_LPP, $empresa, $activos, "'".$tipo."'", $usrZonas);
$_rows = count($cuentas); //DataManager::getCuentas($pag, $_LPP, $empresa, $activos, $tipo,
echo "<table id=\"tblCuentas\" style=\"table-layout:fixed;\">";
if (count($cuentas)) {
echo "<thead><tr align=\"left\"><th>Id</th><th>Cuenta</th><th>Nombre</th><th>Provincia</th><th>Localidad</th><th>Cuit</th><th>Modificada</th><th align=\"center\">Acciones</th></tr></thead>";
echo "<tbody>";
for( $k=0; $k < $_LPP; $k++ ) {
if ($k < $_rows) {
$cuenta = $cuentas[$k];
$id = $cuenta['ctaid'];
$idCuenta = $cuenta['ctaidcuenta'];
$empresa = $cuenta['ctaidempresa'];
$cuit = $cuenta['ctacuit'];
$nombre = $cuenta['ctanombre'];
$provincia = $cuenta['ctaidprov'];
$localidad = $cuenta['ctaidloc'];
$dateUpdate = ($cuenta['ctaupdate']=='0000-00-00 00:00:00' || $cuenta['ctaupdate']=='2001-01-01 00:00:00' || $cuenta['ctaupdate']=='1900-01-01 00:00:00') ? '' : $cuenta['ctaupdate'];
$provinciaNombre = DataManager::getProvincia('provnombre', $provincia);
$localidadNombre = DataManager::getLocalidad('locnombre', $localidad);
$localidadNombre = (empty($localidadNombre) ? $cuenta['ctalocalidad'] : $localidadNombre);
$_editar = sprintf( "onclick=\"window.open('editar.php?ctaid=%d')\" style=\"cursor:pointer;\"",$id);
$_status = ($cuenta['ctaactiva']) ? "<a title=\"Activa\"><img class=\"icon-status-active\" onclick=\"javascript:dac_changeStatus('/pedidos/cuentas/logica/changestatus.php', $id, $pag)\"/></a>" : "<a title=\"Inactiva\" ><img class=\"icon-status-inactive\" onclick=\"javascript:dac_changeStatus('/pedidos/cuentas/logica/changestatus.php', $id, $pag)\"/></a>";
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class=".$clase.">";
echo "<td ".$_editar.">".$id."</td><td ".$_editar.">".$idCuenta."</td><td ".$_editar.">".$nombre."</td><td ".$_editar.">".$provinciaNombre."</td><td ".$_editar.">".$localidadNombre."</td><td ".$_editar.">".$cuit."</td><td ".$_editar.">".$dateUpdate."</td><td align=\"center\">".$_status."</td>";
echo "</tr>";
}
}
} else {
echo "<tbody>";
echo "<thead><tr><th colspan=\"8\" align=\"center\">No hay cuentas relacionadas</th></tr></thead>"; exit;
}
echo "</tbody></table>";
?><file_sep>/js/ajax/getCadena.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$idEmpresa = $_GET['idEmpresa'];
$datosJSON;
$cadenas = DataManager::getCadenas($idEmpresa);
if (count($cadenas)) {
foreach ($cadenas as $k => $cadena) {
if ($idEmpresa == $cadena["IdEmpresa"]){
$datosJSON[] = $cadena["IdCadena"]."-".$cadena["NombreCadena"];
}
}
}
/*una vez tenemos un array con los datos los mandamos por json a la web*/
header('Content-type: application/json');
echo json_encode($datosJSON);
?><file_sep>/condicion/logica/jquery/jqueryHeaderEdit.js
//previene que se pueda hacer Enter en observaciones
$(document).ready(function() {
"use strict";
$('textarea').keypress(function(event) {
if (event.keyCode === 13) {
event.preventDefault();
}
});
$( "#btsend" ).click(function () {
var condid = $('input[name="condid"]:text').val();
var empselect = $('select[name="empselect"]').val();
var labselect = $('select[name="labselect"]').val();
var tiposelect = $('select[name="tiposelect"]').val();
var listaPrecio = $('select[name="listaPrecio"]').val();
var nombre = $('input[name="nombre"]:text').val();
var condpago = $('input[name="condpago"]:text').val();
var minMonto = $('input[name="minMonto"]:text').val();
var cantMinima = $('input[name="cantMinima"]:text').val();
var minReferencias = $('input[name="minReferencias"]:text').val();
var fechaInicio = $('input[name="fechaInicio"]:text').val();
var fechaFin = $('input[name="fechaFin"]:text').val();
var observacion = $('textarea[name="observacion"]').val();
var habitualCant = $('input[name="habitualCant"]:text').val();
var habitualBonif1 = $('input[name="habitualBonif1"]:text').val();
var habitualBonif2 = $('input[name="habitualBonif2"]:text').val();
var habitualDesc1 = $('input[name="habitualDesc1"]:text').val();
var habitualDesc2 = $('input[name="habitualDesc2"]:text').val();
var cuentaid; //= new Array();
var condpagoid;
var condidart = []; //= new Array();
var condprecioart = []; //= new Array();
var condpreciodigit = []; //= new Array();
var condcantmin = []; //= new Array();
var condoferta = []; //= new Array();
var condofertacheck = []; //= new Array();
$('input[name="cuentaid[]"]:text').each(function() {
cuentaid = (cuentaid) ? cuentaid+","+$(this).val() : $(this).val();
});
$('input[name="condpagoid[]"]:text').each(function() {
condpagoid = (condpagoid) ? condpagoid+","+$(this).val() : $(this).val();
});
$('input[name="condprecioart[]"]:text').each(function(i) { condprecioart[i] = $(this).val();});
$('input[name="condpreciodigit[]"]:text').each(function(i) { condpreciodigit[i]= $(this).val();});
$('input[name="condcantmin[]"]:text').each(function(i) { condcantmin[i] = $(this).val();});
$('select[name="condoferta[]"]').each(function(i) { condoferta[i] = $(this).val();});
$('input[name="condofertacheck[]"]').each(function(i) {
condofertacheck[i] = ($(this).is(':checked')) ? '1' : '0';
});
var condcant = '';
var condbonif1 = '';
var condbonif2 = '';
var conddesc1 = '';
var conddesc2 = '';
//al recorrer el foreach de artículos, cargo sus bonificaciones?
$('input[name="condidart[]"]:text').each(function(i) {
condidart[i] = $(this).val();
$('input[name="condcant'+condidart[i]+'[]"]:text').each(function(j) {
condcant = (j === 0) ? condcant+$(this).val() : condcant+"-"+$(this).val();
});
$('input[name="condbonif1'+condidart[i]+'[]"]:text').each(function(j) {
condbonif1 = (j === 0) ? condbonif1+$(this).val() : condbonif1+"-"+$(this).val();
});
$('input[name="condbonif2'+condidart[i]+'[]"]:text').each(function(j) {
condbonif2 = (j === 0) ? condbonif2+$(this).val() : condbonif2+"-"+$(this).val();
});
$('input[name="conddesc1'+condidart[i]+'[]"]:text').each(function(j) {
conddesc1 = (j === 0) ? conddesc1+$(this).val() : conddesc1+"-"+$(this).val();
});
$('input[name="conddesc2'+condidart[i]+'[]"]:text').each(function(j) {
conddesc2 = (j === 0) ? conddesc2+$(this).val() : conddesc2+"-"+$(this).val();
});
condcant = condcant + '|';
condbonif1 = condbonif1 + '|';
condbonif2 = condbonif2 + '|';
conddesc1 = conddesc1 + '|';
conddesc2 = conddesc2 + '|';
});
dac_enviar();
function dac_enviar(){
$.ajax({
type: 'POST',
url: '/pedidos/condicion/logica/update.condicion.php',
data: {
condid : condid,
empselect : empselect,
labselect : labselect,
tiposelect : tiposelect,
nombre : nombre,
condpago : condpago,
minMonto : minMonto,
cantMinima : cantMinima,
minReferencias:minReferencias,
fechaInicio : fechaInicio,
fechaFin : fechaFin,
observacion : observacion,
habitualCant : habitualCant,
habitualBonif1 : habitualBonif1,
habitualBonif2 : habitualBonif2,
habitualDesc1 : habitualDesc1,
habitualDesc2 : habitualDesc2,
cuentaid : cuentaid,
listaPrecio : listaPrecio,
condpagoid : condpagoid,
condidart : condidart,
condprecioart: condprecioart,
condpreciodigit:condpreciodigit,
condcantmin : condcantmin,
condoferta : condoferta,
condofertacheck : condofertacheck,
condcant : condcant,
condbonif1 : condbonif1,
condbonif2 : condbonif2,
conddesc1 : conddesc1,
conddesc2 : conddesc2
},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
$("#btsend").hide(100);
},
success: function(result) {
if (result){
var scrolltohere = '';
$('#box_cargando').css({'display':'none'});
if (result.replace("\n","") === '1'){
//Confirmación
scrolltohere = "#box_confirmacion";
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('Los datos fueron registrados');
window.location.reload(true);
} else {
//El pedido No cumple Condiciones
scrolltohere = "#box_error";
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
if(result === "Invalido"){
window.location = "/pedidos/login/index.php";
}
}
$('html,body').animate({
scrollTop: $(scrolltohere).offset().top
}, 2000);
$("#btsend").show(100);
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error en el proceso");
$("#btsend").show(100);
},
});
}
});
});
//------------------------------//
// Crea Nuevo div de artículo //
var nextcondicion = 0;
function dac_cargarArticuloCondicion(id, idart, nombre, precioLista, cantmin, precioDrog, oam, medicinal, iva, empresa, ganancia, oferta){
"use strict";
nextcondicion++;
//-----------------------
var p1 = parseFloat(precioLista);
var p2 = parseFloat(1.450);
var pvp = parseFloat(p1*p2);
if(iva === 'N') { pvp = parseFloat(pvp*1.21); }
if(medicinal === 'N'){ pvp = parseFloat(pvp*1.21); }
if(empresa === '3') {
if(iva === 'N') { pvp = parseFloat(pvp*1.21); }
if(medicinal === 'S') { pvp = parseFloat(pvp*1.21); }
}
if(ganancia !== undefined && ganancia !== '0.00'){
var porcGanancia = (parseFloat(ganancia) / 100) + 1;
pvp = parseFloat(pvp / porcGanancia);
}
pvp = pvp.toFixed(3);
//----------------------
var campo = '<div id="rutcondicion'+nextcondicion+'">';
campo += '<div class="bloque_1 background-art">';
campo += '<input id="condidart'+nextcondicion+'" name="condidart[]" type="text" value="'+idart+'" hidden="hidden"/>';
campo += '<div class="bloque_10"><br><input type="button" value="-" onClick="dac_deleteArticuloCondicion('+nextcondicion+')" class="btmenos red"></div>';
campo += '<div class="bloque_7"><br> <strong>'+idart+ ' | </strong>'+nombre+'</div>';
campo += '<div class="bloque_8"><label>PSL</label><input id="condprecioart'+nextcondicion+'" name="condprecioart[]" type="text" value="'+precioLista+'" maxlength="8" onkeydown="ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);" onKeyUp="javascript:ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);"/></div>';
campo += '<div class="bloque_8"><label>PVP</label><input type="text" value="$ '+pvp+'" readonly/></div>';
campo += '<div class="bloque_8"><label>Digitado</label><input id="condpreciodigit'+nextcondicion+'" name="condpreciodigit[]" type="text" value="'+precioDrog+'" maxlength="8" onkeydown="ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);" onKeyUp="javascript:ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);"/></div>';
campo += '<div class="bloque_9"><label>CantMin</label><input type="text" id="condcantmin'+nextcondicion+'" name="condcantmin[]" value="'+cantmin+'" maxlength="2" align="center"/></div>';
campo += '<div class="bloque_8"><label>AM</label>';
campo += '<select id="condoferta" name="condoferta[]">';
campo += ' <option value=""></option>';
campo += ' <option value="alta" '; if(oam === "alta"){ campo += 'selected';} campo += '>Alta</option>';
campo += ' <option value="modificado" '; if(oam === "modificado"){ campo += 'selected';} campo += '>Modifica</option>';
campo += ' <option value="oferta" disabled '; if(oam === "oferta"){ campo += 'selected';} campo += '>Oferta</option>';
campo += ' <option value="altaoff" disabled '; if(oam === "altaoff"){ campo += 'selected';} campo += '>AltaOff</option>';
campo += ' <option value="modifoff" disabled '; if(oam === "modifoff"){ campo += 'selected';} campo += '>ModifOff</option>';
campo += '</select>';
campo += '</div>';
var checked = '';
if(oferta === '1'){ checked = 'checked';}
campo += '<div class="bloque_9" align="center"><label>Oferta</label><br><input type="checkbox" id="condofertacheck'+nextcondicion+'" name="condofertacheck[]" value="'+oferta+'" '+checked+'/></div>';
campo += '<div class="bloque_10"><br><input id="btmas" type="button" value="+" onClick="dac_addBonificacion('+nextcondicion+', '+id+', '+idart+', 0, 0, 0, 0, 0, 0)" style="background-color:#3dc349;"></div><hr>';
campo += '</div>';
campo += '<div id="bonificacionArticulo'+nextcondicion+'"></div>';
campo += '<hr class="hr-line"></div>';
campo += '</div>';
$("#detalle_articulo").append(campo);
}
// función del botón eliminar para quitar un div de artículos
function dac_deleteArticuloCondicion(nextcondicion){ //elimina
"use strict";
var elemento = document.getElementById('rutcondicion'+nextcondicion);
elemento.parentNode.removeChild(elemento);
}
var nextbonificacion = 0;
function dac_addBonificacion(nextcondicion, id, idart, cant, b1, b2, d1, d2, idbonif){
"use strict";
idbonif = (idbonif===0) ? idbonif = '' : idbonif;
cant = (cant===0) ? cant = '' : cant;
b1 = (b1===0) ? b1 = '' : b1;
b2 = (b2===0) ? b2 = '' : b2;
d1 = (d1===0) ? d1 = '' : d1;
d2 = (d2===0) ? d2 = '' : d2;
nextbonificacion++;
var campo = '<div id="rutbonificacion'+nextbonificacion+'" class="bloque_5">';
campo += '<div class="bloque_8 background-bonif"><label>Cant.</label><input type="text" name="condcant'+idart+'[]" size="2" value="'+cant+'" maxlength="2"/></div>';
campo += '<div class="bloque_8"><label>Bonif 1</label><input type="text" name="condbonif1'+idart+'[]" size="2" value="'+b1+'" maxlength="2"/></div>';
campo += '<div class="bloque_8"><label>Bonif 2</label><input type="text" name="condbonif2'+idart+'[]" size="2" value="'+b2+'" maxlength="2"/></div>';
campo += '<div class="bloque_8"><label>Dto1</label> <input type="text" name="conddesc1'+idart+'[]" value="'+d1+'" maxlength="5" size="2" onkeydown="ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);" onKeyUp="javascript:ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);"/></div>';
campo += '<div class="bloque_8"><label>Dto2</label><input type="text" name="conddesc2'+idart+'[]" value="'+d2+'" maxlength="5" size="2" onkeydown="ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);" onKeyUp="javascript:ControlComa(this.id, this.value); dac_ControlNegativo(this.id, this.value);"/></div>';
campo += '<div class="bloque_9"><br><input type="button" value=" - " onClick="dac_deleteBonificacion('+nextbonificacion+')" style="background-color:#117db6;"></div>';
campo += '<hr></div>';
$("#bonificacionArticulo"+nextcondicion).append(campo);
}
function dac_deleteBonificacion(nextbonificacion){ //elimina
"use strict";
var elemento = document.getElementById('rutbonificacion'+nextbonificacion);
elemento.parentNode.removeChild(elemento);
}
/**********************/
/* OnChangeLaboratorio*/
/**********************/
/*function dac_changeEmpresa(emp, lab) {
"use strict";
dac_changeLaboratorio(emp, lab);
$.ajax({
type : 'POST',
cache: false,
url : 'logica/ajax/getCuentas.php',
data: { empresa : emp, },
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
$('#box_cargando').css({'display':'none'});
if (result){
document.getElementById('tablacuentas').innerHTML = result;
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
},
});
} */
function dac_changeLaboratorio(emp, lab) {
"use strict";
dac_limpiarListaArticulos();
$.ajax({
type : 'POST',
cache: false,
url : 'logica/ajax/getArticulos.php',
data: { idlab : lab,
idemp : emp},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
$('#box_cargando').css({'display':'none'});
if (result){
document.getElementById('tablaarticulos').innerHTML = result;
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
}
});
}
function dac_limpiarListaArticulos(){
"use strict";
$("#detalle_articulo").empty();
}
/******************************/
/* Carga Condicion de Pago */
var nextCondPago = 0;
function dac_cargarCondicionPago(condid, nombre, dias){
"use strict";
nextCondPago ++;
var campo = '<div id="rutconpago'+nextCondPago+'">';
campo +='<div class="bloque_2"><input id="condpagoid'+nextCondPago+'" name="condpagoid[]" type="text" value='+condid+' hidden="hidden"/>'+condid+' - '+nombre+' '+dias+'</div>';
campo +='<div class="bloque_9"><input id="btmenos" class="btmenos" type="button" value=" - " onClick="dac_deleteCondPago('+condid+', '+nextCondPago+')"></div>';
campo +='<hr></div>';
$("#detalle_condpago").append(campo);
/*Oculto la fila */
if(document.getElementById('condPago'+condid)){
document.getElementById('condPago'+condid).style.display = "none";
}
}
// Botón eliminar div
function dac_deleteCondPago(id, nextCondPago) {
"use strict";
document.getElementById('condPago'+id).style.display = "table-row";
var elemento = document.getElementById('rutconpago'+nextCondPago);
elemento.parentNode.removeChild(elemento);
}
/*************************************/
/* Cargas Cuentas de la Condicion */
var nextcuenta = 0;
function dac_cargarCuentaCondicion(id, idcuenta, nombre){
"use strict";
nextcuenta++;
var campo = '<div id="rutcuenta'+nextcuenta+'">';
campo +='<div class="bloque_2"><input id="cuentaid'+nextcuenta+'" name="cuentaid[]" type="text" value='+id+' hidden="hidden" />'+idcuenta+' - '+nombre+'</div>';
campo +='<div class="bloque_9"><input id="btmenos" class="btmenos" type="button" value=" - " onClick="dac_deleteCuenta('+id+', '+nextcuenta+')"></div>';
campo +='</div>';
$("#detalle_cuenta").append(campo);
/*Oculto la fila de la tabla para que no la repitan*/
if(document.getElementById('cuenta'+id)){
document.getElementById('cuenta'+id).style.display = "none";
}
}
// Botón eliminar para quitar un div de artículos
function dac_deleteCuenta(id, nextcuenta){
"use strict";
//Muestra la fila en la tabla para que la pueda volver a seleccionar//
document.getElementById('cuenta'+id).style.display = "table-row";
//elimina
var elemento = document.getElementById('rutcuenta'+nextcuenta);
elemento.parentNode.removeChild(elemento);
}<file_sep>/condicionpago/logica/update.condicion.transfer.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$condId = empty($_REQUEST['condid']) ? 0 : $_REQUEST['condid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/condicionpago/': $_REQUEST['backURL'];
$_codigo = $_POST['condcodigo'];
$_nombre = $_POST['condnombre'];
$_dias = $_POST['conddias'];
$_porc = $_POST['condporcentaje'];
$_SESSION['s_codigo'] = $_codigo;
$_SESSION['s_nombre'] = $_nombre;
$_SESSION['s_dias'] = $_dias;
$_SESSION['s_porcentaje'] = $_porc;
if (empty($_codigo)) {
$_goURL = sprintf("/pedidos/condicionpago/editar_transfer.php?condid=%d&sms=%d", $condId, 1);
header('Location:' . $_goURL);
exit;
}
if (empty($_nombre)) {
$_goURL = sprintf("/pedidos/condicionpago/editar_transfer.php?condid=%d&sms=%d", $condId, 2);
header('Location:' . $_goURL);
exit;
}
$_condicion = DataManager::getCondicionDePagoTransfer('condid', 'condcodigo', $_codigo);
if($_condicion){
if($_condicion != $condId){
$_goURL = sprintf("/pedidos/condicionpago/editar_transfer.php?condid=%d&sms=%d", $condId, 3);
header('Location:' . $_goURL);
exit;
}
}
$_condobject = ($condId) ? DataManager::newObjectOfClass('TCondiciontransfer', $condId) : DataManager::newObjectOfClass('TCondiciontransfer');
$_condobject->__set('Codigo', $_codigo);
$_condobject->__set('Empresa', 1);
$_condobject->__set('Nombre', $_nombre);
$_condobject->__set('Dias', $_dias);
$_condobject->__set('Porcentaje', $_porc);
//--------------------
// MOVIMIENTO
$movimiento = 'CONDICION_PAGO_TRANSFER';
if ($condId) {
DataManager::updateSimpleObject($_condobject);
//REGISTRA MOVIMIENTO
$movTipo = 'UPDATE';
} else {
$_condobject->__set('ID', $_condobject->__newID());
$_condobject->__set('Activa', 1);
$ID = DataManager::insertSimpleObject($_condobject);
//REGISTRA MOVIMIENTO
$movTipo = 'INSERT';
$condId = $ID;
}
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", $condId);
unset($_SESSION['s_codigo']);
unset($_SESSION['s_nombre']);
unset($_SESSION['s_dias']);
unset($_SESSION['s_porcentaje']);
header('Location:' . $backURL);
?><file_sep>/noticias/logica/eliminar.noticia.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_idnt = empty($_REQUEST['idnt']) ? 0 : $_REQUEST['idnt'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/usuarios/': $_REQUEST['backURL'];
if ($_idnt) {
$_uobject = DataManager::newObjectOfClass('TNoticia', $_idnt);
$_uobject->__set('ID', $_idnt );
$ID = DataManager::deleteSimpleObject($_uobject);
}
header('Location: '.$backURL);
?><file_sep>/includes/class/class.drogueria.php
<?php
require_once('class.PropertyObject.php');
class TDrogueria extends PropertyObject {
protected $_tablename = 'droguerias';
protected $_fieldid = 'drogtid';
protected $_fieldactivo = 'drogtactiva';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'drogtid';
$this->propertyTable['IDEmpresa'] = 'drogtidemp';
$this->propertyTable['Cliente'] = 'drogtcliid';
$this->propertyTable['CorreoTransfer'] = 'drogtcorreotransfer';
$this->propertyTable['CorreoAbm'] = 'drogtcorreoabm';
$this->propertyTable['TipoTransfer'] = 'drogttipotransfer';
$this->propertyTable['TipoAbm'] = 'drogttipoabm';
$this->propertyTable['Activa'] = 'drogtactiva';
$this->propertyTable['RentabilidadTL'] = 'drogtrentabilidadtl';
$this->propertyTable['RentabilidadTD'] = 'drogtrentabilidadtd';
$this->propertyTable['CadId'] = 'drgdcadId';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/pedidos/detalle.propuesta.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$idPropuesta= empty($_REQUEST['propuesta']) ? 0 : $_REQUEST['propuesta'];
$btnPrint = sprintf( "<a id=\"imprimir\" href=\"print.propuesta.php?propuesta=%s\" target=\"_blank\" title=\"Imprimir\" >%s</a>", $idPropuesta, "<img class=\"icon-print\"/>");
$btnAprobar = sprintf( "<a id=\"aprobarPropuesta\" title=\"Aprobar\">%s</a>", "<img class=\"icon-proposal-approved\"/>");
$btnRechazar= sprintf( "<a id=\"rechazarPropuesta\" title=\"Rechazar\">%s</a>", "<img class=\"icon-proposal-rejected\"/>");
?>
<!DOCTYPE html>
<html>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
<script language="JavaScript" src="/pedidos/pedidos/logica/jquery/jquery.aprobar.js" type="text/javascript"></script>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php");?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "pedidos";
$_subsection= "mis_propuestas";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav> <!-- fin menu -->
<main class="cuerpo">
<div class="cbte">
<!--div class="bloque_3"-->
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
<!--/div-->
<?php
if ($idPropuesta) {
$usr = ($_SESSION["_usrrol"] == "V") ? NULL : $_SESSION["_usrid"];
$propuesta = DataManager::getPropuesta($idPropuesta);
if ($propuesta) {
foreach ($propuesta as $k => $prop) {
$empresa = $prop["propidempresa"];
$laboratorio= $prop["propidlaboratorio"];
$nombreEmp = DataManager::getEmpresa('empnombre', $empresa);
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
?>
<div class="cbte_header">
<?php echo $cabeceraPropuesta; ?>
</div> <!-- boxtitulo -->
<?php
$fecha = $prop['propfecha'];
$usrProp = $prop['propusr'];
$usrNombre = DataManager::getUsuario('unombre', $usrProp);
$cuenta = $prop["propidcuenta"];
$cuentaNombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $cuenta, $empresa);
$domicilio = DataManager::getCuenta('ctadireccion', 'ctaidcuenta', $cuenta, $empresa);
$idLocalidad = DataManager::getCuenta('ctaidloc', 'ctaidcuenta', $cuenta, $empresa);
$localidad = DataManager::getLocalidad('locnombre', $idLocalidad);
$cp = DataManager::getCuenta('ctacp', 'ctaidcuenta', $cuenta, $empresa);
$estado = $prop["propestado"];
$observacion = $prop["propobservacion"];
?>
<div class="cbte_boxcontent">
<div class="cbte_box"><?php echo $fecha;?></div>
<div class="cbte_box">
Nro. Propuesta:
<input id="propuesta" name="propuesta" value="<?php echo $idPropuesta; ?>" hidden/>
<?php echo str_pad($idPropuesta, 9, "0", STR_PAD_LEFT); ?>
</div>
<div class="cbte_box" align="right">
<?php echo $usrNombre;?>
</div>
</div> <!-- cbte_boxcontent -->
<div class="cbte_boxcontent">
<div class="cbte_box">
Cuenta: </br>
Dirección: </br>
</div> <!-- cbte_box -->
<div class="cbte_box2">
<?php echo $cuenta." - ".$cuentaNombre;?></br>
<?php echo $domicilio." - ".$localidad." - ".$cp; ?>
</div> <!-- cbte_box2 -->
</div> <!-- cbte_boxcontent -->
<?php
$detalles = DataManager::getPropuestaDetalle($idPropuesta, 1);
if ($detalles) {
$totalFinal = 0;
foreach ($detalles as $j => $det) {
if($j == 0){
$condIdPago = $det["pdcondpago"];
$condicionesDePago = DataManager::getCondicionesDePago(0, 0, NULL, $condIdPago);
if (count($condicionesDePago)) {
foreach ($condicionesDePago as $k => $condPago) {
$condPagoCodigo = $condPago["IdCondPago"];
$condNombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condPago['condtipo']);
$condDias = "(";
$condDias .= empty($condPago['Dias1CP']) ? '0' : $condPago['Dias1CP'];
$condDias .= empty($condPago['Dias2CP']) ? '' : ', '.$condPago['Dias2CP'];
$condDias .= empty($condPago['Dias3CP']) ? '' : ', '.$condPago['Dias3CP'];
$condDias .= empty($condPago['Dias4CP']) ? '' : ', '.$condPago['Dias4CP'];
$condDias .= empty($condPago['Dias5CP']) ? '' : ', '.$condPago['Dias5CP'];
$condDias .= " Días)";
$condDias .= ($condPago['Porcentaje1CP'] == '0.00') ? '' : ' '.$condPago['Porcentaje1CP'].' %';
}
}
?>
<div class="cbte_boxcontent">
<div class="cbte_box2">
Condición de Pago:
<?php echo $condNombre." ".$condDias;?>
</div>
</div> <!-- cbte_boxcontent -->
<div class="cbte_boxcontent2">
<table>
<thead>
<tr align="left">
<th scope="col" width="10%" height="18" align="center">Código</th>
<th scope="col" width="10%" align="center">Cant</th>
<th scope="col" width="30%" align="center">Descripción</th>
<th scope="col" width="10%" align="center">Precio</th>
<th scope="col" width="10%" align="center">Bonif</th>
<th scope="col" width="10%" align="center">Dto1</th>
<th scope="col" width="10%" align="center">Dto2</th>
<th scope="col" width="10%" align="center">Total</th>
</tr>
</thead>
<?php
}
$total = 0;
$totalFinal += 0;
$idArt = $det['pdidart'];
$unidades = $det['pdcantidad'];
$descripcion = DataManager::getArticulo('artnombre', $idArt, $empresa, $laboratorio);
$medicinal = DataManager::getArticulo('artmedicinal', $idArt, $empresa, $laboratorio);
$medicinal = ($medicinal == 'S') ? 0 : 1;
$precio = str_replace('EUR','', $det['pdprecio']);
$b1 = ($det['pdbonif1'] == 0) ? '' : $det['pdbonif1'];
$b2 = ($det['pdbonif2'] == 0) ? '' : $det['pdbonif2'];
$bonif = ($b1 == 0) ? '' : $b1." X ".$b2;
$desc1 = ($det['pddesc1'] == 0) ? '' : $det['pddesc1'];
$desc2 = ($det['pddesc2'] == 0) ? '' : $det['pddesc2'];
$total = round(dac_calcularPrecio($unidades, $precio, $medicinal, $desc1, $desc2), 3);
$totalFinal += $total;
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\" align=\"center\">%s</td><td align=\"center\">%s</td><td>%s</td><td align=\"right\" style=\"padding-right:15px;\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"right\" style=\"padding-right:5px;\">%s</td>", $idArt, number_format($unidades,0), $descripcion, number_format(round($precio,2),2), $bonif, number_format(round($desc1,2),2), number_format(round($desc2,2),2), number_format(round($total,2),2) );
echo sprintf("</tr>");
} ?>
</table>
</div> <!-- cbte_boxcontent2 --> <?php
}
} ?>
<div class="cbte_boxcontent2">
<div class="cbte_box2">
<?php echo $observacion;?>
</div>
<div class="cbte_box" align="right" style="font-size:18px; float: right;">
TOTAL: <?php echo number_format(round($totalFinal,2),2); ?>
</div>
</div> <!-- cbte_boxcontent2 -->
<div class="cbte_boxcontent2">
<?php echo $piePropuesta; ?>
</div> <!-- cbte_boxcontent2 -->
<div class="cbte_boxcontent2" align="center"> <?php
echo $btnPrint;
if($usr){
if($estado == 1){
echo $btnAprobar;
echo $btnRechazar;
}
} else {
if($estado != 3 && $estado != '0'){
echo $btnRechazar;
}
}
?>
</div> <!-- cbte_boxcontent2 --> <?php
}
}?>
</div> <!-- cbte -->
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/articulos/logica/update.articulo.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo "SU SESIÓN HA CADUCADO"; exit;
}
$artId = (isset($_POST['artid'])) ? $_POST['artid'] : NULL;
$idEmpresa = (isset($_POST['artidempresa'])) ? $_POST['artidempresa'] : NULL;
$artIdlab = (isset($_POST['artidlab'])) ? $_POST['artidlab'] : NULL;
$artIdart = (isset($_POST['artidart'])) ? $_POST['artidart'] : NULL;
$nombre = (isset($_POST['artnombre'])) ? $_POST['artnombre'] : NULL;
$descripcion = (isset($_POST['artdescripcion'])) ? $_POST['artdescripcion']: NULL;
$precio = (isset($_POST['artprecio'])) ? $_POST['artprecio'] : NULL;
$precioCompra = (isset($_POST['artpreciocompra']))? $_POST['artpreciocompra'] : NULL;
$precioLista = (isset($_POST['artpreciolista'])) ? $_POST['artpreciolista'] : NULL;
$precioReposicion = (isset($_POST['artprecioreposicion']))? $_POST['artprecioreposicion'] : NULL;
$fechaCompra = (isset($_POST['artfechacompra'])) ? $_POST['artfechacompra']: NULL;
$ean = (isset($_POST['artean'])) ? $_POST['artean'] : NULL;
$ganancia = (isset($_POST['artporcentaje'])) ? $_POST['artporcentaje'] : NULL;
$medicinal = (isset($_POST['artmedicinal'])) ? $_POST['artmedicinal'] : NULL;
$iva = (isset($_POST['artiva'])) ? $_POST['artiva'] : NULL;
$oferta = (isset($_POST['artoferta'])) ? $_POST['artoferta'] : NULL;
$idImagen = (isset($_POST['artimagen'])) ? $_POST['artimagen'] : NULL;
$rubro = (isset($_POST['artrubro'])) ? $_POST['artrubro'] : NULL;
$familia = (isset($_POST['artfamilia'])) ? $_POST['artfamilia'] : NULL;
$lista = (isset($_POST['artlista'])) ? $_POST['artlista'] : NULL;
$dispone = (isset($_POST['artiddispone'])) ? $_POST['artiddispone'] : NULL;
//dispone
$nombreGenerico = (isset($_POST['artnombregenerico'])) ? $_POST['artnombregenerico'] : NULL;
$via = (isset($_POST['artvia'])) ? $_POST['artvia'] : NULL;
$forma = (isset($_POST['artforma'])) ? $_POST['artforma'] : NULL;
$envase = (isset($_POST['artenvase'])) ? $_POST['artenvase'] : NULL;
$unidad = (isset($_POST['artunidad'])) ? $_POST['artunidad'] : NULL;
$cantidad = (isset($_POST['artcantidad'])) ? $_POST['artcantidad'] : NULL;
$unidadMedida = (isset($_POST['artmedida'])) ? $_POST['artmedida'] : NULL;
$accion = (isset($_POST['artaccion'])) ? $_POST['artaccion'] : NULL;
$uso = (isset($_POST['artuso'])) ? $_POST['artuso'] : NULL;
$noUsar = (isset($_POST['artnousar'])) ? $_POST['artnousar'] : NULL;
$cuidadosPre = (isset($_POST['artcuidadospre'])) ? $_POST['artcuidadospre']: NULL;
$cuidadosPost = (isset($_POST['artcuidadospost']))? $_POST['artcuidadospost'] : NULL;
$comoUsar = (isset($_POST['artcomousar'])) ? $_POST['artcomousar'] : NULL;
$conservacion = (isset($_POST['artconservacion']))? $_POST['artconservacion'] : NULL;
$fechaVersion = (isset($_POST['artfechaultversion'])) ? $_POST['artfechaultversion'] : NULL;
//array de formula
$formId = (isset($_POST['formId'])) ? $_POST['formId'] : NULL;
$formIfa = (isset($_POST['formIfa'])) ? $_POST['formIfa'] : NULL;
$formCant = (isset($_POST['formCant'])) ? $_POST['formCant'] : NULL;
$formMedida = (isset($_POST['formMedida'])) ? $_POST['formMedida'] : NULL;
if (empty($idEmpresa)) {
echo "La empresa es obligatoria."; exit;
}
if (empty($artIdlab)) {
echo "El laboratorio es obligatorio."; exit;
}
if (empty($artIdart) || !is_numeric($artIdart)) {
echo "El código de artículo es obligatorio y numérico."; exit;
} else {
if (empty($artId)) {
$articulo = DataManager::getArticulo('artid', $artIdart, $idEmpresa, $artIdlab);
if(count($articulo) > 0){
echo "El código de artículo que desea crear ya existe."; exit;
}
}
}
if (empty($nombre)) {
echo "El nombre es obligatorio."; exit;
}
if(empty($familia)) {
echo "Indique la familia."; exit;
}
if(empty($rubro)) {
echo "Indique el rubro."; exit;
}
if (empty($precio)) {
echo "El precio es obligatoria."; exit;
}
if (empty($precioCompra)) {
echo "Controle que exista un valor de precio de Compra."; exit;
}
if (empty($ean)) {
echo "El código de barras es obligatoria."; exit;
}
$imagenNombre = $_FILES["imagen"]["name"];
$imagenPeso = $_FILES["imagen"]["size"];
$imagenType = $_FILES["imagen"]["type"];
if ($imagenPeso != 0){
if($imagenPeso > MAX_FILE){
echo "El archivo no debe superar los 4 MB"; exit;
}
if($imagenType!="image/png"){
echo "La imagen debe ser PNG."; exit;
}
}
if(empty($fechaVersion)){
$fechaVersion = '2001-01-01';
}
if(empty($unidad)){
$unidad = 0;
}
if(empty($cantidad)){
$cantidad = 0;
}
for($k=0; $k < count($formId); $k++) {
if(empty($formIfa[$k])){
echo "Indique IFA"; exit;
}
if(empty($formCant[$k]) || $formCant[$k] <= 0){
echo "Indique una cantidad"; exit;
}
if(empty($formMedida[$k])){
echo "Indique unidad de medida"; exit;
}
}
//Dispone
$dispObject = ($dispone) ? DataManager::newObjectOfClass('TArticuloDispone', $dispone) : DataManager::newObjectOfClass('TArticuloDispone');
$dispObject->__set('NombreGenerico' , $nombreGenerico);
$dispObject->__set('Via' , $via);
$dispObject->__set('Forma' , $forma);
$dispObject->__set('Envase' , $envase);
$dispObject->__set('Unidades' , $unidad);
$dispObject->__set('Cantidad' , $cantidad);
$dispObject->__set('UnidadMedida' , $unidadMedida);
$dispObject->__set('Accion' , $accion);
$dispObject->__set('Uso' , $uso);
$dispObject->__set('NoUsar' , $noUsar);
$dispObject->__set('CuidadosPre' , $cuidadosPre);
$dispObject->__set('CuidadosPost' , $cuidadosPost);
$dispObject->__set('ComoUsar' , $comoUsar);
$dispObject->__set('Conservacion' , $conservacion);
$dispObject->__set('FechaUltVersion', $fechaVersion);
if ($dispone) {
DataManager::updateSimpleObject($dispObject);
$idDispone = $dispone;
} else {
$dispObject->__set('ID', $dispObject->__newID());
$idDispone = DataManager::insertSimpleObject($dispObject);
}
//Formulas INSERT, UPDATE O DELETE
$fmId = [];
$formulas = DataManager::getArticuloFormula( $idDispone );
if (count($formulas)) {
foreach ($formulas as $k => $form) {
$fmId[] = $form["afid"];
$fmIfa[] = $form["afifa"];
$fmCant[] = $form["afcantidad"];
$fmMedida[] = $form["afumedida"];
}
}
if(count($formId)){
//^^^Returns all records of $new_ids ($formId) that aren't present in $old_ids
$insert = array_diff($formId, $fmId);
if(count($insert)) {
foreach ($insert as $k => $key) {
$formObject = DataManager::newObjectOfClass('TArticuloFormula');
$formObject->__set('IDArticuloDispone' , $idDispone);
$formObject->__set('IFA' , $formIfa[$k]);
$formObject->__set('Cantidad' , $formCant[$k]);
$formObject->__set('UnidadMedida' , $formMedida[$k]);
$formObject->__set('ID' , $formObject->__newID());
$idFormula = DataManager::insertSimpleObject($formObject);
}
}
//^^^Returns all records of $new_ids that were present in $old_ids
$update = array_intersect($formId, $fmId);
if(count($update)){
foreach ($update as $k => $key) {
$formObject = DataManager::newObjectOfClass('TArticuloFormula', $key);
$formObject->__set('IDArticuloDispone' , $idDispone);
$formObject->__set('IFA' , $formIfa[$k]);
$formObject->__set('Cantidad' , $formCant[$k]);
$formObject->__set('UnidadMedida' , $formMedida[$k]);
DataManager::updateSimpleObject($formObject);
}
}
}
//^^^Returns all records of $old_ids that aren't present in $new_ids
$delete = (count($formId)) ? array_diff($fmId, $formId) : $fmId;
if(count($delete)>0){
for($k=0; $k < count($delete); $k++) {
$formObject = DataManager::newObjectOfClass('TArticuloFormula', $fmId[$k]);
$formObject->__set('ID', $fmId[$k] );
DataManager::deleteSimpleObject($formObject);
}
}
$rutaFile = "/pedidos/images/imagenes/";
if ($imagenPeso != 0){
$ext = explode(".", $imagenNombre);
$name = dac_sanearString($ext[0]);
$imagenObject = ($idImagen) ? DataManager::newObjectOfClass('TImagen', $idImagen) :
DataManager::newObjectOfClass('TImagen');
$imagenNombre = md5($name).".".$ext[1];
$imagenObject->__set('Imagen' , $imagenNombre);
if($idImagen){
$imagenVieja = $imagenObject->__get('Imagen');
DataManager::updateSimpleObject($imagenObject);
$dir = $_SERVER['DOCUMENT_ROOT'].$rutaFile.$imagenVieja;
if (file_exists($dir)) { unlink($dir); }
} else {
$imagenObject->__set('ID', $imagenObject->__newID());
$idImagen = DataManager::insertSimpleObject($imagenObject);
}
if(!dac_fileUpload($_FILES["imagen"], $rutaFile, md5($name))){
echo "Error al intentar subir la imagen."; exit;
}
}
$artObject = ($artId) ? DataManager::newObjectOfClass('TArticulo', $artId) : DataManager::newObjectOfClass('TArticulo');
$artObject->__set('Empresa' , $idEmpresa);
$artObject->__set('Laboratorio' , $artIdlab);
$artObject->__set('Articulo' , $artIdart);
$artObject->__set('Nombre' , $nombre);
$artObject->__set('Descripcion' , $descripcion);
$artObject->__set('Precio' , $precio);
$artObject->__set('PrecioLista' , $precioLista);
$artObject->__set('PrecioCompra' , $precioCompra);
$artObject->__set('PrecioReposicion', $precioReposicion);
if(empty($fechaCompra)){
$artObject->__set('FechaCompra', date("Y-m-d H:m:s"));
} else {
$artObject->__set('FechaCompra', dac_invertirFecha($fechaCompra));
}
$artObject->__set('CodigoBarra' , $ean);
$artObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$artObject->__set('LastUpdate' , date("Y-m-d H:m:s"));
$artObject->__set('Medicinal' , ($medicinal) ? 'S' : 'N');
$artObject->__set('IVA' , ($iva) ? 'S' : 'N');
$artObject->__set('Ganancia' , $ganancia);
$artObject->__set('Imagen' , $idImagen);
$artObject->__set('Rubro' , $rubro);
$artObject->__set('Dispone' , $idDispone);
$artObject->__set('Familia' , $familia);
$artObject->__set('Lista' , $lista);
$artObjectHiper = ($artId) ? DataManagerHiper::newObjectOfClass('THiperArticulo', $artId) : DataManagerHiper::newObjectOfClass('THiperArticulo');
$artObjectHiper->__set('Empresa' , $idEmpresa);
$artObjectHiper->__set('Laboratorio' , $artIdlab);
$artObjectHiper->__set('Articulo' , $artIdart);
$artObjectHiper->__set('Nombre' , $nombre);
$artObjectHiper->__set('Descripcion' , $descripcion);
$artObjectHiper->__set('Precio' , $precio);
$artObjectHiper->__set('PrecioLista' , $precioLista);
$artObjectHiper->__set('PrecioCompra' , $precioCompra);
$artObjectHiper->__set('PrecioReposicion', $precioReposicion);
if(empty($fechaCompra)){
$artObjectHiper->__set('FechaCompra', date("Y-m-d H:m:s"));
} else {
$artObjectHiper->__set('FechaCompra', dac_invertirFecha($fechaCompra));
}
$artObjectHiper->__set('CodigoBarra' , $ean);
$artObjectHiper->__set('UsrUpdate' , $_SESSION["_usrid"]);
$artObjectHiper->__set('LastUpdate' , date("Y-m-d H:m:s"));
$artObjectHiper->__set('Medicinal' , ($medicinal) ? 'S' : 'N');
$artObjectHiper->__set('IVA' , ($iva) ? 'S' : 'N');
$artObjectHiper->__set('Oferta' , ($oferta) ? 'S' : 'N');
$artObjectHiper->__set('Ganancia' , $ganancia);
$artObjectHiper->__set('Imagen' , $idImagen);
$artObjectHiper->__set('Rubro' , $rubro);
$artObjectHiper->__set('Dispone' , $idDispone);
$artObjectHiper->__set('Familia' , $familia);
$artObjectHiper->__set('Lista' , $lista);
if ($artId) {
//UPDATE
$movTipo = 'UPDATE';
DataManagerHiper::updateSimpleObject($artObjectHiper, $artId);
DataManager::updateSimpleObject($artObject);
} else {
//INSERT
$movTipo = 'INSERT';
$artObject->__set('Activo' , 1);
$artObject->__set('Stock' , 1);
$artObject->__set('ID' , $artObject->__newID());
DataManagerHiper::_getConnection('Hiper'); //Controla conexión a HiperWin
$artId = DataManager::insertSimpleObject($artObject);
$artObjectHiper->__set('Activo' , 1);
$artObjectHiper->__set('Stock' , 1);
$artObjectHiper->__set('ID' , $artId);
DataManagerHiper::insertSimpleObject($artObjectHiper, $artId);
}
// Registro MOVIMIENTO //
$movimiento = 'Articulo_'.$artIdart;
dac_registrarMovimiento($movimiento, $movTipo, "TArticulo", $artId);
echo "1"; exit;
?><file_sep>/js/ajax/cargar.articulos.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
//*************************************************
$_laboratorio = (isset($_POST['idlab'])) ? $_POST['idlab'] : NULL;
$_empresa = (isset($_POST['idemp'])) ? $_POST['idemp'] : NULL;
//*************************************************
if (!empty($_laboratorio)) {
$_articulos = DataManager::getArticulos(0, 1000, 1, 1, $_laboratorio, $_empresa);
if (count($_articulos)) {
foreach ($_articulos as $k => $_articulo) {
$_articulo = $_articulos[$k];
$_id = $_articulo['artid'];
$_idart = $_articulo['artidart'];
$_nombre = $_articulo["artnombre"];
$_precio = str_replace('"', '', json_encode($_articulo["artprecio"])); $_articulo["artprecio"];
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr id=art".$_id." class=".$clase." onclick=\"javascript:dac_cargarArticuloCondicion('$_id', '$_idart', '$_nombre', '$_precio', '$_b1', '$_b2', '$_desc1', '$_desc2', '$_cantmin')\"><td>".$_idart."</td><td>".$_nombre."</td><td>".$_precio."</td></tr>";
}
} else {
echo "<tr><td colspan=\"3\"></br>No hay artículos activos en la empresa y laboratorio seleccionados</td></tr>";
}
} else {
echo "Error al seleccionar el laboratorio";
}
?><file_sep>/includes/class/class.usuario.php
<?php
require_once('class.PropertyObject.php');
class TUsuario extends PropertyObject {
protected $_tablename = 'usuarios';
protected $_fieldid = 'uid';
protected $_fieldactivo = 'uactivo';
protected $_timestamp = 0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'uid';
$this->propertyTable['Rol'] = 'urol';
//---------
//unombre habrá que adaptar a nombre?
$this->propertyTable['Nombre'] = 'unombre';
//$this->propertyTable['NombreyApellidos'] = 'NombreyApellidos';
//$this->propertyTable['Nombre'] = 'Nombre';
//$this->propertyTable['Apellido'] = 'Apellido';
//----------
$this->propertyTable['Dni'] = 'udni';
$this->propertyTable['Login'] = 'ulogin';
$this->propertyTable['Clave'] = 'uclave';
$this->propertyTable['Email'] = 'uemail';
$this->propertyTable['Obs'] = 'uobs';
$this->propertyTable['Activo'] = 'uactivo';
$this->propertyTable['idArea'] = 'uidarea';
$this->propertyTable['Roles'] = 'IdRoles';
$this->propertyTable['Iniciales'] = 'Iniciales';
/*
$this->propertyTable['LastWebIp'] = 'ulastwebip';
$this->propertyTable['LastWebLogin'] = 'ulastweblogin';
$this->propertyTable['LastHiperIp'] = 'ulasthiperip';
$this->propertyTable['LastHiperLogin'] = 'ulasthiperlogin';
$this->propertyTable['Created'] = 'ucreated';
$this->propertyTable['LastUpdate'] = 'uupdate';
*/
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
// Devuelve '#petid' para el alta de un nuevo registro
return ('#'.$this->propertyTable['ID']);
}
public function __validate() {
return true;
}
public function Autenticado() {
return $this->_autenticado;
}
public function esAdministrador() {
return ($this->__get('Rol')=='A');
}
public function esVendedor() {
return ($this->__get('Rol')=='V');
}
public function esAuditoria() {
return ($this->__get('Rol')=='U');
}
public function esAdministracion() {
return ($this->__get('Rol')=='M');
}
public function esProveedor() {
return ($this->__get('Rol')=='P'); //Proveedor
}
public function esCliente() {
return ($this->__get('Rol')=='C');
}
public function getNombreYApellidos() {
return ($this->__get('Nombre'));
}
private function setAuth($_status=false) {
$this->_autenticado = $_status;
}
public function login($_pwd) {
$this->setAuth(false);
$_status = (strcmp($_pwd, $this->__get('Clave')) == 0);
$this->setAuth($_status);
return $_status;
}
}
?><file_sep>/proveedores/fechaspago/lista.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$fecha = empty($_REQUEST['fecha']) ? date('d-m-Y') : $_REQUEST['fecha'];
if($fecha){
$_guardar = sprintf( "<a title=\"Guardar Pagos\" ><img id=\"guardar_pagos\" class=\"icon-save\"/></a>");
$_importarXLS = sprintf( "<a title=\"Importar Plazos Facturas\"><img id=\"importar\" class=\"icon-xls-import\"/></a>");
$_exportarXLS = sprintf( "<a href=\"logica/exportar.fechasemanal.php?fecha=%s\" title=\"Exportar fecha semanal de pago\">%s</a>", $fecha, "<img class=\"icon-xls-export\"/>");
$exportHistorial = sprintf( "<a id=\"btnExporHistorial\" title=\"Exportar historial\">%s</a>", "<img class=\"icon-xls-export\"/>");
}
?>
<script type="text/javascript" src="logica/jquery/jqueryHeader.js"></script>
<div class="box_body">
<div class="bloque_1">
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<div class="bloque_7">
<label>Fecha de Pago </label>
<input id="f_fecha" name="fecha" type="text" value="<?php echo $fecha;?>" readonly/>
</div>
<div class="bloque_7">
<input type="file" name="file" id="file">
</div>
<div class="bloque_9">
<?php echo $_importarXLS; ?>
</div>
<div class="bloque_9">
<?php echo $_guardar; ?>
</div>
<div class="bloque_9">
<?php echo $_exportarXLS; ?>
</div>
<hr>
<div class="bloque_1">
<div class="bloque_7">
<label>Exportar Desde</label>
<input id="fechaDesde" type="text" readonly/>
</div>
<div class="bloque_7">
<label>Hasta </label>
<input id="fechaHasta" type="text" readonly/>
</div>
<div class="bloque_9">
<br>
<?php echo $exportHistorial; ?>
</div>
</div>
</div>
<div class="box_seccion"> <!-- datos -->
<div class="barra">
<div class="bloque_5">
<h1>Facturas</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn" type="text" value="tblTablaFacts" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<table id="tblTablaFacts" border="0" width="100%" align="center">
<thead>
<tr align="left">
<th>Empresa</th>
<th>Código</th>
<th >Proveedor</th>
<th >Nro Factura</th>
</tr>
</thead>
<tbody id="bodyFactList">
<?php
$facturas = DataManager::getFacturasProveedor(NULL, 0, NULL);
if($facturas){
foreach ($facturas as $k => $fact) {
$_idfact = $fact['factid'];
$_idempresa = $fact['factidemp'];
//nombre de empresa
$_empresa = DataManager::getEmpresa('empnombre', $_idempresa);
$_idprov = $fact['factidprov'];
//saco el nombre del proveedor
$_proveedor = DataManager::getProveedor('providprov', $_idprov, $_idempresa);
$_nombre = isset($_proveedor[0]['provnombre']) ? $_proveedor[0]['provnombre'] : 'Proveedor desconocido';
$_plazo = $fact['factplazo'];
$_tipo = $fact['facttipo'];
$factnro = $fact['factnumero'];
$fechacbte = dac_invertirFecha($fact['factfechacbte']);
$fechavto = dac_invertirFecha($fact['factfechavto']);
$_observacion = $fact['factobservacion'];
$_saldo = $fact['factsaldo'];
$_activa = $fact['factactiva'];
((($k % 2) == 0)? $clase="par" : $clase="impar"); ?>
<tr id="listafact<?php echo $k;?>" class="<?php echo $clase;?>" onclick="javascript:dac_ControlProveedor('<?php echo $_idempresa;?>', '<?php echo $_idprov;?>'); dac_CargarDatosPagos('<?php echo $k;?>', '<?php echo $_idfact;?>', '<?php echo $_idempresa;?>', '<?php echo $_idprov;?>', '<?php echo $_nombre;?>', '<?php echo $_plazo;?>', '<?php echo $fechavto;?>', '<?php echo $_tipo;?>', '<?php echo $factnro;?>', '<?php echo $fechacbte;?>', '<?php echo $_saldo;?>', '<?php echo $_observacion;?>', '<?php echo $_activa;?>')" style="cursor: pointer;">
<td><?php echo substr($_empresa, 0, 3); ?></td>
<td><?php echo $_idprov; ?></td>
<td ><?php echo $_nombre; ?></td>
<td ><?php echo $factnro; ?></td>
</tr> <?php
}
} else { ?>
<tr>
<td scope="colgroup" colspan="4" height="25" align="center">No hay facturas cargadas</td>
</tr> <?php
} ?>
</tbody>
</table>
</div> <!-- Fin listar -->
</div> <!-- Fin boxdatosuper -->
<hr>
<div class="box_down">
<div class="bloque_10">Emp</div>
<div class="bloque_9">Código</div>
<div class="bloque_7">Proveedor</div>
<div class="bloque_10">Plazo</div>
<div class="bloque_8">Vencimiento</div>
<div class="bloque_10">Tipo</div>
<div class="bloque_9">Nro</div>
<div class="bloque_8">Fecha Cbte</div>
<div class="bloque_9">Saldo</div>
<div class="bloque_8">Observación</div>
<div class="bloque_10"></div>
<div class="bloque_10"></div>
<hr class="hr-line">
<form id="fm_fechaspago_edit" name="fm_fechaspago_edit" method="POST" enctype="multipart/form-data">
<input id="fecha" name="fecha" type="text" value="<?php echo $fecha; ?>" hidden>
<div id="lista_fechaspago">
<?php
//hago consulta de fechas de pago en la fecha actual ordenada por proveedor
$saldoTotal = 0;
$facturas_pago = DataManager::getFacturasProveedor(NULL, 1, dac_invertirFecha($fecha));
if($facturas_pago) {
foreach ($facturas_pago as $k => $factPago) {
$_idfact = $factPago['factid'];
$_idempresa = $factPago['factidemp'];
$_idprov = $factPago['factidprov'];
//Saco el nombre del proveedor
$_proveedor = DataManager::getProveedor('providprov', $_idprov, $_idempresa);
$_nombre = $_proveedor['0']['provnombre'];
$_plazo = $factPago['factplazo'];
$_tipo = $factPago['facttipo'];
$factnro = $factPago['factnumero'];
$fechacbte = dac_invertirFecha($factPago['factfechacbte']);
$fechavto = dac_invertirFecha($factPago['factfechavto']);
$_saldo = $factPago['factsaldo'];
$_observacion = $factPago['factobservacion'];
$_activa = $factPago['factactiva'];
$saldoTotal += $_saldo;
echo "<script>";
echo "javascript:dac_CargarDatosPagos('', '".$_idfact."', '".$_idempresa."','".$_idprov."','".$_nombre."','".$_plazo."','".$fechavto."','".$_tipo."' ,'".$factnro."', '".$fechacbte."' , '".$_saldo."', '".$_observacion."', '".$_activa."')";
echo "</script>";
}
} ?>
</div>
</form>
<div class="bloque_4"><strong>TOTAL $</strong></div>
<div class="bloque_7" id="saldo_total" style="float:right"><strong><?php echo $saldoTotal; ?></strong></div>
<div hidden="hidden"><button id="btnExport" hidden="hidden"></button></div>
</div>
<script type="text/javascript" src="logica/jquery/jqueryFooter.js"></script>
<file_sep>/informes/logica/exportar.registro_llamadas.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="V"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
//*******************************************
$fechaDesde = (isset($_POST['fechaDesde'])) ? $_POST['fechaDesde'] : NULL;
$fechaHasta = (isset($_POST['fechaHasta'])) ? $_POST['fechaHasta'] : NULL;
//*******************************************
if(empty($fechaDesde) || empty($fechaHasta)){
echo "Debe completar las fechas para exportar"; exit;
}
//*************************************************
//Duplicado de registros
//*************************************************
$fechaInicio = new DateTime(dac_invertirFecha($fechaDesde));
$fechaFin = new DateTime(dac_invertirFecha($fechaHasta));
$fechaFin->modify("+1 day");
//*************************************************
// Exportar datos de php a Excel
//*************************************************
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=Llamadas_$fechaDesde-al-$fechaHasta.xls");
?>
<HTML LANG="es"><TITLE>::. Exportacion de Datos .::</TITLE></head>
<body>
<table border=1 align="center" cellpadding=1 cellspacing=1 >
<tr><td colspan="10" align="center" style="font-weight:bold; border:none;"> Registro de Llamadas </td></tr>
<tr><td colspan="10" style="font-weight:bold; border:none;"> DESDE: <?php echo $fechaDesde; ?></td></tr>
<tr><td colspan="10" style="font-weight:bold; border:none;"> HASTA: <?php echo $fechaHasta; ?></td></tr>
<tr>
<td>Id</td><td>IdOrigen</td><td>Fecha Llamada </td><td>Tipo</td><td>Resultado</td><td>Observación</td><td>Usuario</td><td>Asignado</td><td>Cuenta</td><td>Nombre</td>
</tr> <?php
$llamadas = DataManager::getLlamadas(NULL, NULL, NULL, "TCuenta", 0, $fechaInicio->format("Y-m-d 00:00:00"), $fechaFin->format("Y-m-d 23:59:59"));
if (count($llamadas)) {
foreach ($llamadas as $k => $llam) {
$id = $llam["llamid"];
$origenId = $llam["llamorigenid"];
$fecha = new DateTime($llam["llamfecha"]);
$tipo = $llam["llamtiporesultado"];
$resultado = $llam["llamresultado"];
$observacion= $llam["llamobservacion"];
$usr = DataManager::getUsuario('unombre', $llam["llamusrupdate"]);
$usrAsignado= DataManager::getCuenta('ctausrassigned', 'ctaid', $origenId, 1);
if($usrAsignado){
$nombreAsignado = DataManager::getUsuario('unombre', $usrAsignado);
$idCuenta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $origenId, 1);
$nombreCuenta = DataManager::getCuenta('ctanombre', 'ctaid', $origenId, 1);
} else {
$usrAsignado= "";
$nombreAsignado = "";
$idCuenta = "";
$nombreCuenta = "";
}
if($fecha->format("Y-m-d") >= $fechaInicio->format("Y-m-d") && $fecha->format("Y-m-d") < $fechaFin->format("Y-m-d")){ //&& $fecha < $fechaFin?>
<tr>
<td><?php echo $id;?></td>
<td><?php echo $origenId; ?></td>
<td><?php echo $fecha->format("Y-m-d H:i:s"); ?></td>
<td><?php echo $tipo;?></td>
<td><?php echo $resultado; ?></td>
<td width="150px"><?php echo $observacion; ?></td>
<td><?php echo $usr; ?></td>
<td><?php echo $nombreAsignado; ?></td>
<td><?php echo $idCuenta; ?></td>
<td><?php echo $nombreCuenta; ?></td>
</tr> <?php
}
}
} ?>
</table>
</body>
</html><file_sep>/includes/class/class.articulo.php
<?php
require_once('class.PropertyObject.php');
class TArticulo extends PropertyObject {
protected $_tablename = 'articulo';
protected $_fieldid = 'artid';
protected $_fieldactivo = 'artactivo';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'artid';
$this->propertyTable['Empresa'] = 'artidempresa';
$this->propertyTable['Laboratorio'] = 'artidlab';
$this->propertyTable['Articulo'] = 'artidart';
$this->propertyTable['Nombre'] = 'artnombre';
$this->propertyTable['Descripcion'] = 'artdescripcion';
$this->propertyTable['Precio'] = 'artprecio'; //es PrecioART
$this->propertyTable['PrecioLista'] = 'artpreciolista'; //PrecioListaART';
$this->propertyTable['PrecioCompra']= 'artpreciocompra'; //PrecioComART';
$this->propertyTable['PrecioReposicion']= 'artprecioreposicion'; //PrecioRepART';
$this->propertyTable['FechaCompra'] = 'artfechacompra';
$this->propertyTable['CodigoBarra'] = 'artcodbarra';
$this->propertyTable['Stock'] = 'artstock';
$this->propertyTable['Medicinal'] = 'artmedicinal';
$this->propertyTable['Imagen'] = 'artimagen';
$this->propertyTable['UsrUpdate'] = 'artusrupdate';
$this->propertyTable['LastUpdate'] = 'artlastupdate';
$this->propertyTable['Activo'] = 'artactivo';
$this->propertyTable['Rubro'] = 'artidrubro';
$this->propertyTable['Dispone'] = 'artiddispone';
$this->propertyTable['Familia'] = 'artidfamilia';
$this->propertyTable['Lista'] = 'artidlista';
$this->propertyTable['IVA'] = 'artiva';
$this->propertyTable['Ganancia'] = 'artganancia';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/soporte/tickets/lista.php
<?php
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/soporte/tickets/': $_REQUEST['backURL'];
$_LPP = 10;
$_total = count(DataManager::getTicket(0, 0, NULL, $_SESSION["_usrid"]));
$_LPP = ($_total < $_LPP) ? $_total : $_LPP;
$_paginas = (empty($_total)) ? 1 : ceil($_total/$_LPP);
$_pag = isset($_REQUEST['pag']) ? min(max(1,$_REQUEST['pag']),$_paginas) : 1;
$_GOFirst = sprintf("<a class=\"icon-go-first\" href=\"%s?pag=%d\"></a>", $backURL, 1);
$_GOPrev = sprintf("<a class=\"icon-go-previous\" href=\"%s?pag=%d\"></a>", $backURL, $_pag-1);
$_GONext = sprintf("<a class=\"icon-go-next\" href=\"%s?pag=%d\"></a>", $backURL, $_pag+1);
$_GOLast = sprintf("<a class=\"icon-go-last\" href=\"%s?pag=%d\"></a>", $backURL, $_paginas);
?>
<div class="box_down">
<div class="barra">
<div class="bloque_5">
<h1>Mis Consultas</h1>
</div>
<div class="bloque_5">
<a href="nuevo/"><input type="button" value="NUEVA CONSULTA"/></a>
</div>
<hr>
</div> <!-- Fin barra -->
<table id="tblSoporte"> <?php
$ticket = DataManager::getTicket($_pag, $_LPP, NULL, $_SESSION["_usrid"]);
$_max = count($ticket);
for( $k=0; $k < $_LPP; $k++ ) {
if ($k < $_max) {
$tk = $ticket[$k];
$tkId = "Nro. ".$tk['tkid'];
$idSector = $tk['tkidsector'];
$idMotivo = $tk['tkidmotivo'];
$estado = $tk['tkestado'];
$creado = $tk['tkcreated'];
$sectores = DataManager::getTicketSector();
if (count($sectores)) {
foreach( $sectores as $j => $sec ) {
$idSec = $sec['tksid'];
if($idSector == $idSec){
$sector = $sec['tksnombre'];
}
}
}
$motivos = DataManager::getTicketMotivos($idSector);
if (count($motivos)) {
foreach ($motivos as $j => $mot) {
$idMot = $mot['tkmotid'];
if($idMotivo == $idMot){
$motivo = $mot['tkmotmotivo'];
}
}
}
switch($estado){
case 0:
$_status = "<input type=\"button\" value=\"RESPONDIDO\" style=\"background-color: gray;\">";
break;
case 1:
$_status = "<input type=\"button\" value=\"ACTIVO\" style=\"background-color:green;\">";
break;
}
$_lista = sprintf( "<a href=\"../mensajes/?tkid=%d&pag=%s\">%s</a>", $tk['tkid'], $_pag, "<img src=\"/pedidos/images/icons/icono-next.png\" border=\"0\" align=\"absmiddle\" />");
} else {
$tkId = " ";
$sector = " ";
$motivo = " ";
$_status= " ";
$creado = " ";
$_lista = " ";
}
echo sprintf("<tr class=\"%s\" >", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"100\" >%s <br> %s </td><td>%s</td><td>%s </td><td>%s</td><td align=\"center\">%s</td>", $creado, $tkId, $_status, $sector, $motivo, $_lista);
echo sprintf("</tr>");
} ?>
</table>
<?php
if ( $_paginas > 1 ) {
$_First = ($_pag > 1) ? $_GOFirst : " ";
$_Prev = ($_pag > 1) ? $_GOPrev : " ";
$_Last = ($_pag < $_paginas) ? $_GOLast : " ";
$_Next = ($_pag < $_paginas) ? $_GONext : " ";
echo("<table class=\"paginador\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
echo sprintf("<td height=\"16\">Mostrando página %d de %d</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td>", $_pag, $_paginas, $_First, $_Prev, $_Next, $_Last);
echo("</tr></table>");
} ?>
<hr>
</div>
<file_sep>/zonas/logica/jquery/jquery.map.js
function initialize(data) {
"use strict";
$.ajax({
type : 'POST',
cache : false,
data : data,
url : '/pedidos/zonas/logica/ajax/getCuentaZonas.php',
beforeSend: function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
$("#btnSendTransfer").hide(100);
},
success : function (resultado) {
if (resultado){
var marcadores = [];
var pathCoordinates = [];
var json = eval(resultado);
for(i = 0; i < json.length; i++){
marcadores.push([json[i].datos, json[i].latitud, json[i].longitud, json[i].cuenta, json[i].color, json[i].imagen, json[i].id, json[i].direccion, json[i].idcuenta]);
}
var map = new google.maps.Map(document.getElementById('mapa'), {
zoom: 4,
center: new google.maps.LatLng(-34, -64),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//-------------------------
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
//-------------------------
var infowindow = new google.maps.InfoWindow();
var marker, i;
//---------
//List Records
var listRecords = [];
listRecords.headStart = '<table id="tblTablaCta" border="0" width="100%" align="center">';
listRecords.titles = '<thead><tr align="left"><th>Id</th><th>Nombre</th></tr></thead>';
listRecords.headEnd = '<tbody>';
listRecords.foot = '</tbody></table>';
listRecords.records = '';
//---------
for(i = 0; i < marcadores.length; i++) {
/*var latitud = marcadores[i][1];
var longitud = marcadores[i][2];*/
marker = new google.maps.Marker({
position : new google.maps.LatLng(marcadores[i][1], marcadores[i][2]),
icon : 'https://www.neo-farma.com.ar/pedidos/images/icons/'+marcadores[i][5],//imagen marcador
id : marcadores[i][6],
title : marcadores[i][3],
map : map,
longitud : marcadores[i][2],
latitud : marcadores[i][1],
direccion : marcadores[i][7],
contenido : marcadores[i][0],
idcuenta : marcadores[i][8],
//label: 'titulo junto al marcador',
/*icon: { //define forma de marcado
path: google.maps.SymbolPath.CIRCLE,
scale: 4, //tamaño
strokeColor: 'black',//'#ea4335', //color del borde
strokeWeight: 1, //grosor del borde
fillColor: marcadores[i][4], //color de relleno
fillOpacity:1// opacidad del relleno
},*/
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(marker.contenido);
infowindow.open(map, marker);
//map.setCenter(marker.getPosition());
};
})(marker, i));
google.maps.event.addListener(marker, 'dblclick', (function(marker, i) {
return function() {
//cambia icono del marcador
var marcado = 'https://www.neo-farma.com.ar/pedidos/images/icons/marcador.png';
var desmarcado = 'https://www.neo-farma.com.ar/pedidos/images/icons/'+marcadores[i][5];
if(marker.icon === marcado){
marker.setIcon(desmarcado);
//Quitar elemento con index marker.id
var result = $.grep(pathCoordinates, function(e){
return e.id !== marker.id;
});
pathCoordinates = result;
//-------------------
$('#waypoints2 option[value="'+marker.direccion+'"]').remove();
//-----------------
} else {
pathCoordinates.push({
id : marker.id,
dir : marker.direccion,
lat : marker.latitud,
lng : marker.longitud
});
marker.setIcon(marcado);
dac_cargarDatosCuenta(marker.idcuenta, marker.title, marker.direccion);
//-----------------
$('#waypoints2').append('<option id="'+marker.id+'" value="'+marker.direccion+'" >'+marker.direccion+'</option>');
$('#'+marker.id).dblclick(function () {
this.remove();
marker.setIcon(desmarcado);
//Quita el registro de la cuenta
dac_deleteRecord(marker.idcuenta);
//Quitar elemento con index marker.id
var result = $.grep(pathCoordinates, function(e){
return e.id !== marker.id;
});
pathCoordinates = result;
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
//---------------
}
calculateAndDisplayRoute(directionsService, directionsDisplay);
//calcular ruteo
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
if(pathCoordinates.length){
for (var j = 0; j < pathCoordinates.length; j++) {
if(j !== 0 && j !== (pathCoordinates.length-1)){
waypts.push({
location: pathCoordinates[j].dir,
stopover: true
});
}
}
directionsService.route({
origin : pathCoordinates[0].dir,
destination : pathCoordinates[(pathCoordinates.length - 1)].dir,
waypoints : waypts,
optimizeWaypoints : true,
travelMode : 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel= $('#waypoints');
summaryPanel.html();
// For each route, display summary information.
var routes = '';
for (var j = 0; j < route.legs.length; j++) {
var routeSegment = j + 1;
routes += '<div class="bloque_1"><b>Segmento ' + routeSegment + ': ' + route.legs[j].distance.text + '</b></div>';
routes += '<div class="bloque_5"> <b>Desde: </b>' + route.legs[j].start_address+ '</b></div>';
routes += '<div class="bloque_5"> <b>Hasta: </b>' + route.legs[j].end_address+ '</div>';
routes += '<hr class="hr-line">';
summaryPanel.html(routes);
}
} else {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html('La consulta de dirección ha fallado ' + status);
}
});
directionsDisplay.setMap(map);
} else {
var routes = '';
var summaryPanel= $('#waypoints');
summaryPanel.html(routes);
}
}
//actualizar en mapa
infowindow.open(map, marker);
};
})(marker, i));
//Add list Records
var clase = '';
if((i % 2) === 0) { clase="par"; } else { clase="impar";}
listRecords.records += "<tr id="+marker.id+" class="+clase+" title='"+marker.direccion+"' style=\"cursor:pointer\"><td>"+marker.idcuenta+"</td><td>"+marker.title+"</td></tr>";
}
//Show ListRecords
$("#tablacuenta").empty(); $("#tablacuenta").html(listRecords.headStart+listRecords.titles+listRecords.headEnd+listRecords.records+listRecords.foot);
//----------------
$('#tblTablaCta').on('click', 'tbody tr', function(event) {
var id = $(this)[0].id; //id de la cuenta cliqueada
//console.log(marcadores[i][6]);
for(i = 0; i < marcadores.length; i++) {
if(marcadores[i][6] === id){
marker = new google.maps.Marker({
position : new google.maps.LatLng(marcadores[i][1], marcadores[i][2]),
contenido : marcadores[i][0],
});
map.setCenter(marker.getPosition());
//map.setZoom(16);
infowindow.setContent(marker.contenido);
}
}
});
//----------
$('#box_cargando').css({'display':'none'});
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html("Se han registrado "+json.length+" cuentas.");
} else {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("No se encuentra registros con los datos indicados.");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("No se encuentra registros con los datos indicados.");
}
});
}
function dac_cargarDatosCuenta(idCuenta, nombre, direccion){
"use strict";
var campo = '<div id="reg'+idCuenta+'"><div class="bloque_6"><label><b>Cuenta:</b></label> '+idCuenta+' </div><div class="bloque_4"><label><b>Razón Social: </b></label> '+nombre+'</div><div class="bloque_1"><label><b>Dirección:</b></label> '+direccion+'</div><hr class="hr-line"></div>';
$("#listCuentas").before(campo);
}
function dac_deleteRecord(idCuenta){
"use strict";
console.log(idCuenta);
var elemento = document.getElementById('reg'+idCuenta);
elemento.parentNode.removeChild(elemento);
}<file_sep>/condicionpago/logica/changestatus.transfer.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag2']) ? 0 : $_REQUEST['pag2'];
$_condid = empty($_REQUEST['condid']) ? 0 : $_REQUEST['condid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/condicionpago/' : $_REQUEST['backURL'];
if ($_condid) {
$_condobject = DataManager::newObjectOfClass('TCondiciontransfer', $_condid);
$_status = ($_condobject->__get('Activa')) ? 0 : 1;
$_condobject->__set('Activa', $_status);
$ID = DataManager::updateSimpleObject($_condobject);
}
header('Location: '.$backURL.'?pag2='.$_pag);
?><file_sep>/pedidos/logica/ajax/getArticulos.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
$laboratorio = (isset($_POST['laboratorio'])) ? $_POST['laboratorio'] : NULL;
$empresa = (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
$condicion = (isset($_POST['condicion'])) ? $_POST['condicion'] : NULL;
$listaCuenta = (isset($_POST['listaCuenta'])) ? $_POST['listaCuenta'] : NULL;
if (empty($laboratorio)) {
echo '<table><tr><td align="center">Error al seleccionar el laboratorio</td></tr></table>'; exit;
}
if(!is_null($listaCuenta) && $listaCuenta != 0){
//$condicion = DataManager::getCondicionCampo('condid', 'condlista', $listaCuenta, $empresa, $laboratorio);
$condiciones = DataManager::getCondiciones( 0, 0, 1, $empresa, $laboratorio, NULL, NULL, NULL, NULL, NULL, $listaCuenta);
if(empty($condiciones)){
echo '<table><tr><td align="center">No hay registros actuales de la Condición Comercial con la Lista de Precios definida en la cuenta</td></tr></table>'; exit;
} else {
foreach ($condiciones as $k => $cond) {
$condicion = $cond['condid'];
}
}
}
if($condicion){
$articulos = DataManager::getCondicionArticulos($condicion);
if (count($articulos)) {
echo '<table id="tblTablaArt" align="center">';
echo '<thead><tr align="left"><th>Id</th><th>Nombre</th><th>Precio</th></tr></thead>';
echo '<tbody>';
foreach ($articulos as $k => $artCond) {
$condArtId = $artCond['cartid'];
$condArtIdArt = $artCond['cartidart'];
$condArtNombre = DataManager::getArticulo('artnombre', $condArtIdArt, $empresa, $laboratorio);
$condArtPrecio = ($artCond["cartpreciodigitado"] == '0.000')? $artCond["cartprecio"] : $artCond["cartpreciodigitado"];
((($k % 2) == 0)? $clase="par" : $clase="impar");
$articulosBonif = DataManager::getCondicionBonificaciones($condicion, $condArtIdArt);
if (count($articulosBonif) == 1) {
foreach ($articulosBonif as $j => $artBonif) {
$artBonifCant = empty($artBonif['cbcant']) ? '' : $artBonif['cbcant'];
$artBonifB1 = empty($artBonif['cbbonif1']) ? '' : $artBonif['cbbonif1'];
$artBonifB2 = empty($artBonif['cbbonif2']) ? '' : $artBonif['cbbonif2'];
$artBonifD1 = ($artBonif['cbdesc1'] == '0.00') ? '' : $artBonif['cbdesc1'];
$artBonifD2 = ($artBonif['cbdesc2'] == '0.00') ? '' : $artBonif['cbdesc2'];
}
echo "<tr class=".$clase." style=\"cursor:pointer\" onclick=\"javascript:dac_CargarArticulo('$condArtIdArt', '$condArtNombre', '$condArtPrecio', '$artBonifB1', '$artBonifB2', '$artBonifD1', '$artBonifD2', '$artBonifCant')\"><td>".$condArtIdArt."</td><td>".$condArtNombre."</td><td>".$condArtPrecio."</td></tr>";
} else {
echo "<tr class=".$clase." style=\"cursor:pointer\" onclick=\"javascript:dac_CargarArticulo('$condArtIdArt', '$condArtNombre', '$condArtPrecio', '', '', '', '', '')\"><td>".$condArtIdArt."</td><td>".$condArtNombre."</td><td>".$condArtPrecio."</td></tr>";
}
}
echo '</tbody></table>';
exit;
} else {
echo '<table><tr><td align="center">No hay registros activos.</td></tr></table>'; exit;
}
} else {
// Busca coincidencia entre la Lista de precios entre Cuenta y condición comercial para cargar, en caso contrario cargar los artículos normales.
$articulos = DataManager::getArticulos(0, 1000, 1, 1, $laboratorio, $empresa);
if (count($articulos)) {
echo '<table id="tblTablaArt" align="center">';
echo '<thead><tr align="left"><th>Id</th><th>Nombre</th><th>Precio</th></tr></thead>';
echo '<tbody>';
foreach ($articulos as $k => $art) {
$art = $articulos[$k];
$idArt = $art['artidart'];
$nombre = $art["artnombre"];
$precio = str_replace('"', '', json_encode($art["artpreciolista"])); $art["artpreciolista"];
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class=".$clase." onclick=\"javascript:dac_CargarArticulo('$idArt', '$nombre', '$precio', '', '', '', '', '', '')\"><td>".$idArt."</td><td>".$nombre."</td><td>".$precio."</td></tr>";
}
echo '</tbody></table>';
exit;
} else {
echo '<table><tr><td align="center">No hay registros activos.</td></tr></table>'; exit;
}
} ?><file_sep>/proveedores/fechaspago/logica/ajax/control.proveedor.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$_idempresa = empty($_REQUEST['idempresa']) ? 0 : $_REQUEST['idempresa'];
$_idprov = empty($_REQUEST['idprov']) ? 0 : $_REQUEST['idprov'];
if(empty($_idempresa) || empty($_idprov)){
echo "Ocurrió un ERROR al verificar el proveedor."; exit;
}
//Busco registros ya guardados en ésta fecha y pongo en cero si no están en el array (si fueron eliminados)
$_proveedor = DataManager::getProveedor('providprov', $_idprov, $_idempresa);
if($_proveedor){
$_activo = $_proveedor['0']['provactivo'];
$_nombre = $_proveedor['0']['provnombre'];
if(!$_activo){
echo "El proveedor '".$_idprov." - ".$_nombre."' no se encuentra activo."; exit;
}
} else {
echo "El proveedor no existe cargado"; exit;
}
echo "1"; exit;
?><file_sep>/transfer/logica/eliminar.pedido.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_ptid = empty($_REQUEST['ptid']) ? 0 : $_REQUEST['ptid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/transfer/': $_REQUEST['backURL'];
if ($_ptid) {
//lo siguiente borra todos los registros de pedidos que tengan el mismo nro de pedido
$_tabla = "pedidos_transfer";
DataManager::deletefromtabla($_tabla, 'ptidpedido', $_ptid);
}
header('Location: '.$backURL);
?><file_sep>/informes/logica/exportar.tablacondicionArt.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=TablaCondicionArt-".date('d-m-y').".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos .::</TITLE>
<head></head>
<body>
<table border="0"> <?php
$registros = DataManager::getCondicionArticulos();
if (count($registros)) {
$names = array_keys($registros[0]); ?>
<thead>
<tr> <?php
foreach ($names as $j => $name) {
?><td scope="col" ><?php echo $name; ?></td><?php
} ?>
</tr>
</thead> <?php
foreach ($registros as $k => $registro) {
echo sprintf("<tr align=\"left\">");
foreach ($names as $j => $name) {
if($j != 3){
echo sprintf("<td >%s</td>", $registro[$name]);
} else {
echo sprintf("<td style=\"mso-number-format:'\@';\">%s</td>", $registro[$name]);
}
}
echo sprintf("</tr>");
}
} ?>
</table>
</body>
</html>
<file_sep>/planificacion/logica/ajax/anular.parte.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//*******************************************
$_vendedor = (isset($_POST['vendedor'])) ? $_POST['vendedor'] : NULL;
$_fecha_anular = (isset($_POST['fecha_anular'])) ? $_POST['fecha_anular'] : NULL;
//*******************************************
//Controles
//*******************************************
if ($_vendedor == 0) { echo "Debe seleccionar un vendedor."; exit; }
if (empty($_fecha_anular)) { echo "Debe indicar la fecha a anular."; exit; }
//*************************************************
// Anulo la planificación
//*************************************************
//Modifico partes con esa fecha y usuario de enviado a no enviado
$_parte = DataManager::getDetalleParteDiario($_fecha_anular, $_vendedor);
if (count($_parte)){
foreach ($_parte as $k => $_part){
$_part = $_parte[$k];
$_partid = $_part["parteid"];
/*se setea el parte*/
$_partobject = DataManager::newObjectOfClass('TPartediario', $_partid);
if($_partobject->__get('Activa') == 0){
$_partobject->__set('Envio', '2001-01-01');
$_partobject->__set('Activa', '1');
$ID = DataManager::updateSimpleObject($_partobject);
if (empty($ID)) { echo "Error al anular el parte. $ID."; exit; }
}
}
} else {
echo "No se verifica que haya datos de parte diario para anular."; exit;
}
//*******************************************************************
echo "Se ha anulado el envío del parte. Si no ve lo cambios actualice con la tecla F5";
?>
<file_sep>/transfer/detalle_transfer.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_ptnropedido = empty($_REQUEST['idpedido']) ? 0 : $_REQUEST['idpedido'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/mispedidos/': $_REQUEST['backURL'];
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php"); ?>
<!DOCTYPE html>
<html>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "pedidos";
$_subsection = "mis_transfers";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<div class="cbte">
<div class="cbte_header">
<div class="cbte_boxheader">
<?php echo $cabeceraPedido; ?>
</div> <!-- cbte_boxheader -->
<div class="cbte_boxheader">
<h1>PEDIDO WEB TRANSFER</h1></br>
Guevara 1347 - CP1427 - Capital Federal - Tel: 4555-3366</br>
<EMAIL> / www.neo-<EMAIL></br>
IVA RESPONSABLE INSCRIPTO
</div> <!-- cbte_boxheader -->
</div> <!-- boxtitulo -->
<?php
if ($_ptnropedido) {
//EL DETALLE DE PEDIDO NO ESTÁ CONTEMPLANDO LA POSIBILIDAD de que haya dos clientes con el mismo id pero de distinta empresa y/o nombre
$_detalles = DataManager::getTransfersPedido(NULL, NULL, NULL, NULL, NULL, NULL, $_ptnropedido);
//DataManager::getDetallePedidoTransfer($_ptnropedido);
if ($_detalles) {
for( $k=0; $k < count($_detalles); $k++ ){
$_detalle = $_detalles[$k];
if ($k==0){
$_fecha_pedido = $_detalle['ptfechapedido'];
$_idvendedor = $_detalle['ptidvendedor'];
$_nombreven = DataManager::getUsuario('unombre', $_idvendedor);
$paraIdUsr = $_detalle['ptparaidusr'];
$paraIdUsrNombre= DataManager::getUsuario('unombre', $paraIdUsr);
$_iddrogueria = $_detalle['ptiddrogueria'];
$ptIdCta = $_detalle['ptidclineo'];
$droguerias = DataManager::getDrogueria(NULL, NULL, NULL, NULL, $_iddrogueria);
if($droguerias){
foreach ($droguerias as $j => $drog) {
$empresaDrog= $drog['drogtidemp'];
$nombreDrog = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $_iddrogueria, $empresaDrog);
}
} else {
$nombreDrog = '';
}
$_idcliente_drog= $_detalle['ptnroclidrog'];
if ($ptIdCta != 0){
$_idcliente_neo = DataManager::getCuenta('ctaidcuenta', 'ctaid', $ptIdCta, 1);
}
$_razonsocial = $_detalle['ptclirs'];
$_cuit = $_detalle['ptclicuit'];
$_domicilio = $_detalle['ptdomicilio'];
$_contacto = $_detalle['ptcontacto']; ?>
<div class="cbte_boxcontent">
<div class="cbte_box"><?php echo $_fecha_pedido;?></div>
<div class="cbte_box">Nro. Transfer <?php echo $_ptnropedido;?></div>
<div class="cbte_box" align="right"><?php echo $_nombreven;?></div>
</div> <!-- cbte_box_nro -->
<?php if($paraIdUsr != $_idvendedor){?>
<div class="cbte_boxcontent" align="right">
<div class="cbte_box" ><?php echo "<strong>Para: </strong>".$paraIdUsrNombre;?></div>
</div> <!-- cbte_box_nro -->
<?php } ?>
<div class="cbte_boxcontent">
<div class="cbte_box">
<?php if ($ptIdCta != 0) { echo "Nro Cuenta:</br>"; }?>
Razón Social: </br>
Droguería: </br>
Nro Cliente Droguería: </br>
CUIT: </br>
<?php if ($_domicilio != "") { echo "Domicilio:</br>"; }?>
<?php if ($_contacto != "") { echo "Contacto:</br>"; }?>
</div> <!-- cbte_box -->
<div class="cbte_box2">
<?php if ($ptIdCta != 0) { echo $_idcliente_neo."</br>";}?>
<?php echo $_razonsocial; ?></br>
<?php echo $_iddrogueria." - ".substr($nombreDrog,0,35);?></br>
<?php echo $_idcliente_drog;?></br>
<?php echo $_cuit; ?></br>
<?php if ($_domicilio != "") { echo $_domicilio."</br>"; }?>
<?php if ($_contacto != "") { echo $_contacto."</br>"; }?>
</div> <!-- cbte_box2 -->
</div> <!-- cbte_boxcontent -->
<div class="cbte_boxcontent2">
<table>
<thead>
<tr align="left">
<th scope="col" width="15%" height="18">Código</th>
<th scope="col" width="15%">Cantidad</th>
<th scope="col" width="50%">Descripción</th>
<th scope="col" width="10%">CondPago</th>
<th scope="col" width="10%">Descuento</th>
</tr>
</thead>
<?php
}
$_ptidart = $_detalle['ptidart'];
$_unidades = $_detalle['ptunidades'];
$condPagoId = $_detalle['ptcondpago'];
$condPagoDias = DataManager::getCondicionDePagoTransfer('conddias', 'condid', $condPagoId);
$condPagoDias = ($condPagoDias == 0) ? 'Habitual' : $condPagoDias;
$_descuento = $_detalle['ptdescuento'];
$_descripcion = DataManager::getArticulo('artnombre', $_ptidart, 1, 1);
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td>", $_ptidart, number_format($_unidades,0), $_descripcion, $condPagoDias, number_format(round($_descuento,2),2));
echo sprintf("</tr>");
} ?>
</table>
</div> <!-- cbte_boxcontent2 -->
<?php
}
} ?>
<div class="cbte_boxcontent2" align="center">
<?php echo $piePedido; ?>
<?php
if ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="M"){
//Reasigna el usuarioAsignado de la venta ?>
<form id="frmReasignar" name="frmReasignar" method="post">
<input id="nroPedido" name="nroPedido" value="<?php echo $_ptnropedido; ?>" hidden="hidden"/>
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<div class="bloque_6">
<label for="ptAsignar">Reasignar a</label>
<select id="ptAsignar" name="ptAsignar" >
<option id="0" value="0" selected></option> <?php
$vendedores = DataManager::getUsuarios( 0, 0, 1, NULL, '"V"');
if (count($vendedores)) {
foreach ($vendedores as $k => $vend) {
$idVend = $vend["uid"];
$nombreVend = $vend['unombre'];
if ($idVend == $paraIdUsr){ ?>
<option id="<?php echo $idVend; ?>" value="<?php echo $idVend; ?>" selected><?php echo $nombreVend; ?></option><?php
} else { ?>
<option id="<?php echo $idVend; ?>" value="<?php echo $idVend; ?>"><?php echo $nombreVend; ?></option><?php
}
}
} ?>
</select>
</div>
<div class="bloque_8">
<br>
<a id="btnReasignar" title="Reasignar" style="cursor:pointer;">
<img class="icon-user-assigned" onclick="javascript:dac_sendForm(frmReasignar, '/pedidos/transfer/logica/reasignar.pedido.php', '/pedidos/transfer/' );"/>
</a>
</div>
</form>
<?php
} ?>
</div> <!-- cbte_boxcontent2 -->
</div> <!-- boxcenter -->
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/movimientos/logica/ajax/getFilasMovimientos.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
//---------------------------
/*$empresa = (isset($_POST['empselect'])) ? $_POST['empselect'] : NULL;
$activos = (isset($_POST['actselect'])) ? $_POST['actselect'] : NULL;
$tipo = (isset($_POST['tiposelect'])) ? $_POST['tiposelect'] : NULL;
//----------------------------
$tipo = ($tipo == '0') ? NULL : "'".$tipo."'";*/
$movimientos = DataManager::getMovimientos(0, 0);
echo count($movimientos);
?><file_sep>/acciones/logica/changestatus.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$_acid = empty($_REQUEST['acid']) ? 0 : $_REQUEST['acid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/acciones/' : $_REQUEST['backURL'];
if ($_acid) {
$_acobject = DataManager::newObjectOfClass('TAccion', $_acid);
$_status = ($_acobject->__get('Activa')) ? 0 : 1;
$_acobject->__set('Activa', $_status);
$ID = DataManager::updateSimpleObject($_acobject);
}
header('Location: '.$backURL.'?pag='.$_pag);
?><file_sep>/soporte/mensajes/lista.php
<?php
$tkid = empty($_REQUEST['tkid']) ? 0 : $_REQUEST['tkid'];
if($tkid){
$tickets = DataManager::getTicket(0, 0, $tkid);
foreach( $tickets as $k => $tk ) {
$idSector = $tk['tkidsector'];
$idMotivo = $tk['tkidmotivo'];
$estado = $tk['tkestado'];
$usrCreated = $tk['tkusrcreated'];
}
}
if ($usrCreated != $_SESSION["_usrid"] && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="A"){
echo "USUARIO DESLOGUEADO $usrCreated != ".$_SESSION["_usrid"];
exit;
}
?>
<div class="box_body">
<form id="fmTicket" method="post" enctype="multipart/form-data">
<div class="bloque_1">
<div class="bloque_5">
<label>
<span style="font-size:24px; color:#666;" ><?php echo "Consulta Nro. ".$tkid; ?></span>
</label>
</div>
<div class="bloque_7">
<label><?php
switch($estado){
case 0: //RESPONDIDO
echo "<input type=\"button\" value=\"Respondido\" style=\"background-color: gray;\">";
break;
case 1: //ACTIVO
echo "<input type=\"button\" value=\"Activo\" style=\"background-color:green;\">";
break;
}
?>
</label>
</div>
<div class="bloque_3">
<label>
<span style="font-size:16px; font-weight: bold; color: #666;">
<?php
$sectores = DataManager::getTicketSector();
foreach( $sectores as $k => $sec ) {
$id = $sec['tksid'];
$sector = $sec['tksnombre'];
if($id == $idSector){
echo $sector;
}
} ?>
</span>
</label>
</div>
</div>
<?php
$mensajes = DataManager::getTicketMensajes($tkid);
foreach( $mensajes as $k => $msg ) {
$mensaje = $msg['tkmsgmensaje'];
$msgUsrCreated = $msg['tkmsgusrcreated'];
$msgNameCreated = DataManager::getUsuario('unombre', $msgUsrCreated);
$msgCreated = $msg['tkmsgcreated'];
if($msgUsrCreated != $_SESSION["_usrid"]){
$style = "background-color: #FFF";
} else {
$style = "background-color: transparent";
} ?>
<fieldset style="<?php echo $style; ?>">
<div class="bloque_5">
<?php echo $msgCreated; ?>
</div>
<div class="bloque_5">
<?php echo $msgNameCreated; ?>
</div>
<div class="bloque_1">
<br>
<?php echo $mensaje; ?>
</div>
<?php
/*if($adjunto){
echo "Archivo adjunto.";
}; */
?>
</fieldset>
<?php
} ?>
<fieldset>
<legend>Añadir una respuesta</legend>
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<!--input type="hidden" name="tkcopia" value="<?php //echo $copia;?>"/-->
<input type="hidden" name="usrCreated" value="<?php echo $usrCreated;?>"/>
<input type="hidden" name="tkestado" value="<?php echo $estado;?>"/>
<input type="hidden" name="tkid" value="<?php echo $tkid;?>"/>
<input type="hidden" name="tkidsector" value="<?php echo $idSector;?>"/>
<input type="hidden" name="tkidmotivo" value="<?php echo $idMotivo;?>"/>
<div class="bloque_1">
<textarea name="tkmensaje" type="text" placeholder="Escribe tu respuesta..."/></textarea>
</div>
<div class="bloque_5">
<input id="imagen" name="imagen" class="file" type="file"/>
</div>
<div class="bloque_5">
<?php $urlSend = '/pedidos/soporte/mensajes/logica/update.mensaje.php';?>
<a id="btnSend" title="Enviar">
<img class="icon-send" onclick="javascript:dac_sendForm(fmTicket, '<?php echo $urlSend;?>');"/>
</a>
</div>
</fieldset>
</form>
</div> <!-- FIN box_body -->
<hr>
<file_sep>/js/provincias/getDirecciones.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php");
/*Me traigo el codigo Provincia seleccionado, el codigo provincia es la referencia a cada Provincia de la BBDD*/
$codigoProvincia = $_GET['codigoProvincia'];
$datosJSON;
$_direcciones = DataManager::getDirecciones();
if (count($_direcciones)) {
foreach ($_direcciones as $k => $_dir) {
if ($codigoProvincia == $_dir["diridprov"]){
$datosJSON[] = $_dir["dirnombre"];
}
}
}
/*una vez tenemos un array con los datos los mandamos por json a la web*/
header('Content-type: application/json');
echo json_encode($datosJSON);
?><file_sep>/informes/logica/new.noticia.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/informes/");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
//**********************************
//envío por MAIL la misma información
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = "<EMAIL>";
$mail->FromName = "Notificacion automatica."; //"Notificación automática.";
$mail->Subject = "Se han actualizado informes web";
$_total= "Hola, se han realizado actualizaciones de precios y/o informes.<br />
Para ver más accede a la web para controlar lo que necesites.<br /><br />
Saludos.<br /><br />
(no respondas a éste mail)";
$mail->msgHTML($_total);
$_usuarios = DataManager::getUsuarios( 0, 0, 1, NULL, '"V"');
for( $k=0; $k < count($_usuarios); $k++ ) {
$_usuario = $_usuarios[$k];
$_email = $_usuario['uemail'];
$_rol = $_usuario['urol'];
if ($_rol == "V"){
$mail->AddAddress($_email, "Noticias Web");
}
}
$mail->AddAddress('<EMAIL>', "Noticias Web");
if(!$mail->Send()) {
echo 'Fallo en el envío';
} else {
$_goURL = "../index.php?sms=6";
header('Location:'.$_goURL);
exit;
}
exit;
?><file_sep>/transfer/gestion/liquidacion/logica/controles.liquidacion.php
<?php
$_CtrlCant = '';
$_CtrlPSLUnit = '';
$_CtrlDescPSL = '';
$_CtrlImpNT = '';
$_Estado = '';
$_CtrlCantArts = array();
$_cantPedidas = 0;
$_cantUnidades = 0;
$_cont_art = 0;
$_noControlar = 0;
if(!empty($_idart)){
$_detallestransfer = DataManager::getTransfersPedido(NULL, NULL, NULL, NULL, NULL, NULL, $_liqTransfer); //DataManager::getDetallePedidoTransfer($_liqTransfer);
if ($_detallestransfer) {
foreach ($_detallestransfer as $j => $_dettrans){
$_dettrans = $_detallestransfer[$j];
$_ptiddrog = $_dettrans['ptiddrogueria'];
$_ptidart = $_dettrans['ptidart'];
$_ptunidades= $_dettrans['ptunidades'];
//Cantidad Pedida del TRANSFER Original del Vendedor
if($_ptidart == $_idart){
$_cantPedidas = $_ptunidades;
}
}
//Si la droguería del pedido transfer es diferente a la droguería de la liquidación
if($_ptiddrog == $_drogid) {
//******************************//
//#1 DIFERENCIA DE CANTIDADES //
//******************************//
$_liqtransfers = DataManager::getDetalleLiquidacionTransfer($_liqID, $_drogid, $_liqTransfer, $_liqean); //$_liqFecha
if($_liqtransfers){
foreach ($_liqtransfers as $j => $_liqtrans){
$_liqtrans = $_liqtransfers[$j];
$_liqtID = $_liqtrans['liqid'];
$_liqtcant = $_liqtrans['liqcant'];
$_cont_art = $_cont_art+1;
//Suma las unidades totales de dicho transfer en liquidaciones
$_cantUnidades += $_liqtcant;
}
}
// DIFERENCIA entre (Unidades LIQUIDADAS + actual) y Unidades PEDIDAS
if(($_cantUnidades + $_liqcant) != $_cantPedidas){
$_CtrlCant = ($_cantUnidades + $_liqcant) - $_cantPedidas; //"Diferencia Cant : ".
}
//Si el artículo se repite en una liquidación y un mismo número de transfer
if($_cont_art > 0){
$_CtrlCant = "*".$_CtrlCant;
}
//**************************//
//#2 Control "PSL Unitario" == a PrecioDrog de la Bonificacion de ese mes
//**************************//
$_bonifarticulo = DataManager::getBonificacionArticulo($_idart, $_mes, $_anio);
$_preciodrog = $_bonifarticulo[0]['bonifpreciodrog'];
$_bonifiva = $_bonifarticulo[0]['bonifiva'];
if(empty($_preciodrog)){ $_CtrlPSLUnit = "#ErrorPSLUnit </br>";
} else {
//SI EL Producto es Cosmético, le agrego un 21%
if($_bonifiva != 0) {
$_preciodrog = round(($_preciodrog * 1.21),2);
}
if($_preciodrog != $_liqunit){
//Si la diferencia es mayor o menos al 2% que la muestre, sino que la discrimine
$_porc_dif = 100 - (($_liqunit * 100) / $_preciodrog);
if ($_porc_dif < -2 || $_porc_dif > 2) {
$_CtrlPSLUnit = "$_preciodrog";
}
}
//SI EL Producto es Cosmético, le vuelvo a retirar un 21%
/*if($_bonifiva != 0) {
$_preciodrog = round(($_preciodrog / 1.21),2);
}*/
if($_drogidemp == 3) {
$_preciodrog = round(($_preciodrog / 1.21),2); //$_preciodrog - ($_preciodrog * 0.21);
}
}
//***********************************//
//#3 Control "% Desc PSL" con "% Desc" del ABM
//***********************************//
$_abmart = DataManager::getDetalleArticuloAbm($_mes, $_anio, $_drogid, $_idart, 'TL');
$_abmdesc = $_abmart[0]['abmdesc'];
$_abmdifcomp = $_abmart[0]['abmdifcomp']; //para el punto #3
if(empty($_abmdesc)){ $_CtrlDescPSL = "#ErrorDescPSL </br>";
} else {
if($_liqdesc < $_abmdesc){ $_CtrlDescPSL = "< $_abmdesc %</br>";
} else{
if($_liqdesc > $_abmdesc){ $_CtrlDescPSL = "> $_abmdesc %</br>";
}
}
}
//***************************//
//#4 Control "Importe NC" == Cantidad * PSL Unitario * (Desc PSL / 100)
//**************************//
//Si en TABLA BONIFICACION el ART "NO" TIENE % IVA, (Y la EMPRESA es 3), le resto el 21%
/*if($_drogidemp == 3) {
$_preciodrog = $_preciodrog / 1.21; //$_preciodrog - ($_preciodrog * 0.21);
} */
//$_liqunit PRECIO UNITARIO DE LA BONIFICACION
$_ImporteNC = round(($_liqcant * $_preciodrog * (($_abmdifcomp) / 100)), 2);
$_CtrlTotalNC += $_ImporteNC;
//Si diferencia es > o < a 2%. la muestre
if($_ImporteNC){
$_porc_difNC = 100 - (($_liqimportenc * 100) / $_ImporteNC);
if ($_porc_difNC < -2 || $_porc_difNC > 2) {
$_CtrlImpNT = $_ImporteNC;
}
} else {
$_CtrlImpNT = "#Error";
}
//ESTADO DE LA LIQUIDACION
//**********************//
// CONTROLA POR ATÍCULO // las cantidades.
//**********************//
if($_liqactiva == 1){
$_Estado .= "Liquidado";
} else {
if($_cantPedidas > ($_cantUnidades + $_liqcant)){
$_Estado .= "LP"; //Liquidado Parcial
} elseif($_cantPedidas == ($_cantUnidades + $_liqcant)) {
$_Estado .= "LT"; //Liquidado Total
} else { //$_cantPedidas < ($_cantUnidades + $_liqcant)
$_Estado .= "LE"; //Liquidado Excedente
}
}
} else {
$_Estado = "#ErrorDrog $_ptiddrog";
}
} else { //Si el transfer no existe!
$_Estado = "#ErrorNroTrans";
}
} else {
$_Estado .= "#ErrorEAN";
}
?><file_sep>/usuarios/editar.zona.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_uid = empty($_REQUEST['uid']) ? 0 : $_REQUEST['uid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/usuarios/': $_REQUEST['backURL'];
if ($_uid) {
$_usuario = DataManager::newObjectOfClass('TUsuario', $_uid);
$_unombre = $_usuario->__get('Nombre');
} else {
$_unombre = "";
}
$_button = sprintf("<input type=\"submit\" id=\"btsend\" name=\"_accion\" value=\"Enviar\"/>");
$_action = sprintf("logica/update.zonaven.php?uid=%d&backURL=", $_uid, $backURL);
?>
<!DOCTYPE html>
<html lang="es">
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = '';
$_subsection = '';
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav> <!-- fin menu -->
<main class="cuerpo">
<div class="box_body">
<form name="fm_zona_vend_edit" method="post" action="<?php echo $_action;?>">
<fieldset>
<legend>ZONAS DE USUARIO: <strong><?php echo $_unombre;?></strong></legend>
<input type="hidden" name="uid" value="<?php echo $_uid; ?>" />
<div class="bloque_8" style="float: right;"> <?php echo $_button; ?> </div>
<hr>
<?php
$_zonas = DataManager::getZonas( 0, 0, 1);
$_max = count($_zonas);
for( $k = 0; $k < $_max; $k++ ) {
$_zona = $_zonas[$k];
$_numero= $_zona['zzona'];
$nombre = $_zona['znombre'];
$_checked = 0;
?>
<div class="bloque_5">
<?php
$zonas_actuales = DataManager::getZonasVendedor($_uid);
$_max2 = count($zonas_actuales);
for( $i = 0; $i < $_max2; $i++ ) {
$zona_actual = $zonas_actuales[$i];
if($_numero == $zona_actual['zona']){$_checked = 1;}
}
$_checked = ($_checked == 1) ? 'checked="checked"' : '' ;
?>
<input name="zzonas[]" id="zzonas" type="checkbox" value="<?php echo $_numero ?>" <?php echo $_checked ?>/>
<label><?php echo $_numero." - ".$nombre; ?></label>
</div>
<?php
} ?>
</fieldset>
</form>
</div> <!-- boxbody -->
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/proveedores/pagos/solicitarfecha/lista.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="P"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_sms = empty($_GET['sms']) ? 0 : $_GET['sms'];
if ($_sms) {
$_nrofact = $_SESSION['nrofact'];
switch ($_sms) {
case 1: $_info = "El número de factura es obligatorio."; break;
case 2: $_info = "El archivo adjunto no debe superar los 4MB."; break;
case 3: $_info = "El archivo adjunto debe ser IMAGEN o PDF."; break;
case 4: $_info = "Error al intentar cargar el archivo adjunto."; break;
case 5: $_info = "Error al intentar enviar el mail de solicitud. Por favor, vuelva a intentarlo"; break;
case 6: $_info = "La solicitud se realizó con éxito."; break;
} // mensaje de error
} else {
$_nrofact = "";
}
$_button = sprintf("<input type=\"submit\" id=\"btsend\" name=\"_accion\" value=\"Solicitar\"/>");
$_action = "/pedidos/proveedores/pagos/solicitarfecha/logica/upload.php";
?>
<script type="text/javascript">
function dac_MostrarSms(sms){
document.getElementById('box_error').style.display = 'none';
if(sms){
if(sms > 0 && sms < 6){
document.getElementById('box_error').style.display = 'block';
document.getElementById('box_confirmacion').style.display = 'none';
} else {
document.getElementById('box_confirmacion').style.display = 'block';
document.getElementById('box_error').style.display = 'none';
}
}
}
</script>
<div class="box_body">
<form action="<?php echo $_action;?>" method="POST" enctype="multipart/form-data">
<fieldset>
<legend> Solicita Fecha de Pago</legend>
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"> <?php echo $_info; ?> </div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"><?php echo $_info;?></div>
</fieldset>
<?php
echo "<script>";
echo "javascript:dac_MostrarSms(".$_sms.")";
echo "</script>";
?>
</div>
<div class="bloque_5">
<input name="archivo" type="file"/>
</div>
<div class="bloque_7">
<label for="nrofact">Nro de Factura *</label>
<input name="nrofact" id="nrofact" type="text" maxlength="10" value="<?php echo @$_nrofact;?>"/>
</div>
<div class="bloque_7"> <br><?php echo $_button;?></div>
</fieldset>
</form>
</div>
<hr>
<!-- Scripts para IMPORTAR ARCHIVO -->
<script type="text/javascript" src="/pedidos/proveedores/pagos/solicitarfecha/logica/jquery/jquery.script.file.js"></script>
<file_sep>/planificacion/nuevo.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
//---------------------
// ACCIONES ACTIVAS
$_accobject = DataManager::getAcciones('', '', 1);
if (count($_accobject)) {
foreach ($_accobject as $k => $_accion) {
$_array_acid = (empty($_array_acid)) ? $_array_acid=$_accion["acid"] : $_array_acid.",".$_accion["acid"];
$_array_acnombre = (empty($_array_acnombre)) ? $_array_acnombre=$_accion["acnombre"] : $_array_acnombre.",".$_accion["acnombre"]; //utf8_decode(
}
$_acciones = $_array_acid."/".$_array_acnombre;
} else {
$_acciones = "0/0";
}
//---------------------
$_fecha_planif = empty($_REQUEST['fecha_planif']) ? date("d-m-Y") : $_REQUEST['fecha_planif'];
//---------------------
$_button_enviar = sprintf("<a title=\"Enviar Planificación\" onclick=\"javascript:dac_Guardar_Planificacion(1)\">%s</a>", "<img class=\"icon-send\"/>");
$_button_print = sprintf( "<a href=\"detalle_planificacion.php?fecha_planif=%s\" title=\"Imprimir Planificación\" target=\"_blank\">%s</a>", $_fecha_planif, "<img class=\"icon-print\"/>");
$_button_guardar_planif= sprintf( "<a title=\"Guardar Planificación\" onclick=\"javascript:dac_Guardar_Planificacion(0)\">%s</a>", "<img class=\"icon-save\"/>");
$_button_nuevo = sprintf( "<a title=\"Nueva Planificación\" onclick=\"javascript:dac_Carga_Planificacion('','','','1')\">%s</a>", "<img class=\"icon-new\"/>");
$_button_enviar_parte = sprintf("<a title=\"Enviar Parte\" onclick=\"javascript:dac_Guardar_Parte(1)\">%s</a>", "<img class=\"icon-send\"/>");
$_button_print_parte = sprintf( "<a href=\"detalle_parte.php?fecha_planif=%s\" title=\"Imprimir Parte\" target=\"_blank\">%s</a>", $_fecha_planif, "<img class=\"icon-print\"/>");
$_button_guardar_parte = sprintf( "<a title=\"Guardar Parte\" onclick=\"javascript:dac_Guardar_Parte(0)\">%s</a>", "<img class=\"icon-save\"/>");
$_button_nuevo_parte = sprintf( "<a title=\"Nuevo Parte\" onclick=\"javascript:dac_Carga_Parte('','','','','','','1','0', '%s')\">%s</a>", $_acciones, "<img class=\"icon-new\"/>");
$_btn_anularplanif = sprintf("<input type=\"submit\" id=\"btsend\" value=\"Anular\" style=\"float:right;\" title=\"Anular Planificación\" onclick=\"javascript:dac_Anular_Planificacion()\"/>");
$_btn_anularparte = sprintf("<input type=\"submit\" id=\"btsend\" value=\"Anular\" style=\"float:right;\" title=\"Anular Parte\" onclick=\"javascript:dac_Anular_Parte()\"/>");
//----------------------------------
// CONTROL DE FECHA PARA ALERTAS
if ($_SESSION["_usrrol"]=="V"){ //ALERTAS//
$dias = array(0,1,2,3,4,5,6); //array("dom","lun","mar","mie","jue","vie","sab");
$_dia = $dias[date("w")];
/*Da la fecha viernes de la prox semana*/
$_prox_viernes = date("Y-m-d",mktime(0, 0, 0, date("m"),date("d")+(12-$_dia), date("Y")));//se define con --> date("d")+(12-$_dia): El 12 es por (6 + 6)
$_prox_viernes2 = dac_invertirFecha( $_prox_viernes );
/*Da la fecha lunes de la prox semana*/
$_prox_lunes = date("Y-m-d",mktime(0, 0, 0, date("m"),date("d")+(8-$_dia), date("Y")));//se define con --> date("d")+(8-$_dia) El 8 es por (6 + 2)
$_prox_lunes2 = dac_invertirFecha( $_prox_lunes );
/*Da la fecha lunes de la semana actual*/
$_lunes_actual = date("Y-m-d",mktime(0, 0, 0, date("m"),date("d")+(1-$_dia), date("Y")));
$_lunes_actual2 = dac_invertirFecha( $_lunes_actual );
/*Da la fecha viernes de la semana actual*/
$_viernes_actual = date("Y-m-d",mktime(0, 0, 0, date("m"),date("d")+(5-$_dia), date("Y")));
$_viernes_actual2 = dac_invertirFecha( $_viernes_actual );
if ($_dia == 5 || $_dia == 6 || $_dia == 0){ // "ES fine";
/*Controlo si faltan cargar o enviar planificaciones de la proxima semana*/
$_planif = DataManager::getControlEnvioPlanif($_prox_lunes, $_prox_viernes, $_SESSION["_usrid"]);
if (count($_planif)){
if (count($_planif) < 5){
$_msg_error_planif = "Faltan PLANIFICACIONES en la semana </br> del ".$_prox_lunes2." al ".$_prox_viernes2;
} else {
foreach ($_planif as $k => $_plan){
$_plan = $_planif[$k];
$_planenviado = $_plan["planifactiva"];
if ($_planenviado == 1){
$_msg_error_planif = "Hay PLANIFICACIONES sin enviar </br> del ".$_prox_lunes2." al ".$_prox_viernes2;
}
}
}
} else { $_msg_error_planif = "No hay PLANIFICACIONES cargadas </br> del ".$_prox_lunes2." al ".$_prox_viernes2; }
/*Controlo si hay partes que falten enviar de la semana pasada desde el Lunes que pasó al finde actual*/
$_parts = DataManager::getControlEnvioPartes($_lunes_actual, $_viernes_actual, $_SESSION["_usrid"]);
if (count($_parts)){
if (count($_parts) < 5){
$_msg_error_parte = "Faltan PARTES en la semana </br> del ".$_lunes_actual2." al ".$_viernes_actual2;
} else {
foreach ($_parts as $k => $_part){
$_part = $_parts[$k];
$_partenviado = $_part["parteactiva"];
if ($_partenviado == 1){
$_msg_error_parte = "Hay PARTES sin enviar </br> del ".$_lunes_actual2." al ".$_viernes_actual2;
}
}
}
} else { $_msg_error_parte = "NO hay PARTES cargados </br> del ".$_lunes_actual2." al ".$_viernes_actual2;}
}
}
?>
<script language="JavaScript" src="/pedidos/planificacion/logica/jquery/jqueryUsr.js" type="text/javascript"></script>
<?php if ($_SESSION["_usrrol"]== "G" || $_SESSION["_usrrol"]== "A"){ ?>
<script language="JavaScript" src="/pedidos/planificacion/logica/jquery/jqueryAdmin.js" type="text/javascript"></script>
<?php } ?>
<div class="box_body">
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<hr>
<!-- FORM CALENDARIOS -->
<form id="export_partes_to_excel" action="logica/exportar.parte.php" method="POST">
<div class="bloque_7">
<label><?php if ($_SESSION["_usrrol"]== "V"){ echo "Origen";} else { echo "Desde";}?></label>
<input id="fecha_planif" name="fecha_planificado" type="text" value="<?php echo @$_fecha_planif;?>" style="background-color:#f2f7d8;" readonly>
</div>
<div class="bloque_7">
<label><?php if ($_SESSION["_usrrol"]== "V"){ echo "Destino";} else { echo "Hasta";}?></label>
<input id="fecha_destino" name="fecha_destino" type="text" value="<?php echo @$_fecha_destino;?>" style="background-color:#fdd494;" readonly>
<!--/div> <!-- end fechas_p-->
</div>
<?php if ($_SESSION["_usrrol"]== "V" || $_SESSION["_usrrol"]== "A" ){ ?>
<div class="bloque_8">
<br>
<a title="Duplicar" onclick="javascript:dac_Duplicar_Planificacion('<?php echo $_fecha_planif;?>')"><img class="icon-copy" /></a>
</div>
<?php }?>
<?php if ($_SESSION["_usrrol"]== "G" || $_SESSION["_usrrol"]== "A" || $_SESSION["_usrrol"]== "M"){?>
<div class="bloque_8">
<br>
<a title="Exportar Planificaciones" onclick="javascript:dac_ExportarPlanifOPartesToExcel(fecha_planif.value, fecha_destino.value, 'planificado')">
<img class="icon-xls-export-planif" />
</a>
</div>
<div class="bloque_8">
<br>
<a title="Exportar Partes" onclick="javascript:dac_ExportarPlanifOPartesToExcel(fecha_planif.value, fecha_destino.value, 'parte')">
<img class="icon-xls-export-parte"/>
</a>
</div>
<?php }?>
<input id="tipo_exportado" name="tipo_exportado" type="text" hidden>
<?php if ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="M"){?>
<div class="bloque_8">
<br>
<a title="Exportar Reporte" onclick="javascript:dac_ExportarPlanifOPartesToExcel(fecha_planif.value, fecha_destino.value, 'reporte')">
<img class="icon-xls-export-report"/>
</a>
</div>
<?php }?>
</form>
<hr>
<div class="bg-orange barra">
<h1>IMPORTANTE! Recuerda pedir a todas tus cuentas, <br>
<strong>DISPONE de habilitación y DT.</strong></h1>
</div>
<hr>
<div class="barra">
<div class="bloque_5">
<h1>Planificación</h1>
</div>
<hr>
<div class="bloque_9"> <?php echo $_button_nuevo; ?> </div>
<div class="bloque_9"> <?php echo $_button_guardar_planif; ?> </div>
<div class="bloque_9"> <?php echo $_button_print; ?> </div>
<div class="bloque_9"> <?php echo $_button_enviar; ?> </div>
<hr>
</div> <!-- Fin barra -->
<form id="fm_planificacion" name="fm_planificacion" method="post" enctype="multipart/form-data">
<div id="detalle_planif"></div>
<?php
$_idclientes = array();
$_planificacion = DataManager::getDetallePlanificacion($_fecha_planif, $_SESSION["_usrid"]);
if (count($_planificacion)){
foreach ($_planificacion as $k => $_planif){
$_planif = $_planificacion[$k];
$_planifcliente = $_planif["planifidcliente"];
$_planifnombre = $_planif["planifclinombre"];
$_planifdir = $_planif["planifclidireccion"];
$_planifactiva = $_planif["planifactiva"];
$_idclientes[$k]= $_planifcliente;
echo "<script>";
echo "javascript:dac_Carga_Planificacion('".$_planifcliente."','".$_planifnombre."','".$_planifdir."','".$_planifactiva."')";
echo "</script>";
}
} ?>
</form>
<hr>
<!-- PARTE -->
<?php
$_parte_diario = DataManager::getDetalleParteDiario($_fecha_planif, $_SESSION["_usrid"]);
if (count($_parte_diario)){ ?>
<div class="barra">
<div class="bloque_5">
<h1>Parte Diario</h1>
</div>
<hr>
<div class="bloque_9"> <?php echo $_button_nuevo_parte; ?> </div>
<div class="bloque_9"> <?php echo $_button_guardar_parte; ?></div>
<div class="bloque_9"> <?php echo $_button_print_parte; ?> </div>
<div class="bloque_9"> <?php echo $_button_enviar_parte; ?> </div>
<hr>
</div> <!-- Fin barra -->
<form id="fm_parte" name="fm_parte" method="post" enctype="multipart/form-data">
<div id="detalle_parte"></div> <?php
foreach ($_parte_diario as $k => $_parte){
$_partecliente = $_parte["parteidcliente"];
$_partenombre = $_parte["parteclinombre"];
$_partedir = $_parte["parteclidireccion"];
$_partetrabajo = $_parte["partetrabajocon"];
$_parteobservacion = $_parte["parteobservacion"];
$_parteaccion = $_parte["parteaccion"];
$_parteactiva = $_parte["parteactiva"];
$_parteplanificada = 0;
for($i=0; $i < count( $_idclientes); $i++){
if($_partecliente == $_idclientes[$i]){$_parteplanificada = 1;}
}
echo '<script >';
echo "javascript:dac_Carga_Parte('".$_partecliente."', '".$_partenombre."', '".$_partedir."', '".$_partetrabajo."', '".$_parteobservacion."', '".$_parteaccion."', '".$_parteactiva."', '".$_parteplanificada."', '".$_acciones."')";
echo '</script>';
} ?>
</form>
<hr>
<?php }?>
</div> <!-- end box_body-->
<div class="box_seccion">
<!-- ADMINISTRAR PARTES Y PLANIF -->
<?php if ($_SESSION["_usrrol"]== "G" || $_SESSION["_usrrol"]== "A"){ ?>
<div class="barra">
<h1>Administrar</h1> <hr>
</div> <!-- Fin barra -->
<form id="fm_anularplanif" name="fm_anularplanif" method="POST">
<fieldset>
<legend>Anular Planificación</legend>
<!--El id lo usaremos para seleccionar este elemento con el jQuery-->
<div class="bloque_5">
<select id="vendedor" name="vendedor"/>
<option>Vendedor...</option> <?php
$vendedores = DataManager::getUsuarios( 0, 0, 1, NULL, '"V"');
if (count($vendedores)) {
foreach ($vendedores as $k => $vend) { ?>
<option id="<?php echo $vend["unombre"]; ?>" value="<?php echo $vend["uid"]; ?>"><?php echo $vend["unombre"]; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<input id="f_fecha_anular" name="fecha_anular" type="text" placeholder="Fecha" value="<?php echo @$_fechaanular;?>" size="16" readonly/>
</div>
<div class="bloque_7"><?php echo $_btn_anularplanif; ?> </div>
</fieldset>
</form>
<form id="fm_anularparte" name="fm_anularparte" method="POST">
<fieldset>
<legend>Anular Parte</legend>
<!--El id lo usaremos para seleccionar este elemento con el jQuery-->
<div class="bloque_5">
<select id="vendedor2" name="vendedor2"/>
<option>Vendedor...</option> <?php
$vendedores = DataManager::getUsuarios( 0, 0, 1, NULL, '"V"');
if (count($vendedores)) {
foreach ($vendedores as $k => $vend) { ?>
<option id="<?php echo $vend["unombre"]; ?>" value="<?php echo $vend["uid"]; ?>"><?php echo $vend["unombre"]; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<input id="f_fecha_anular_parte" name="fecha_anular_parte" type="text" placeholder="Fecha" value="<?php echo @$_fechaanularparte;?>" size="16" readonly/>
</div>
<div class="bloque_7"><?php echo $_btn_anularparte; ?> </div>
</fieldset>
</form>
<?php }?>
<!-- ALERTAS -->
<?php if ($_SESSION["_usrrol"]== "V" || $_SESSION["_usrrol"]== "A"){ ?>
<?php if (!empty($_msg_error_planif)){?>
<div class="bg-orange barra">
<h1><?php echo $_msg_error_planif; ?></h1>
<hr>
</div> <!-- Fin barra -->
<?php }?>
<?php if (!empty($_msg_error_parte)){?>
<div class="bg-orange barra">
<h1><?php echo $_msg_error_parte; ?></h1>
<hr>
</div> <!-- Fin barra -->
<?php }?>
<!-- LISTADO DE CLIENTES -->
<div class="barra">
<div class="bloque_5"> <h1>Cuentas</h1> </div>
<div class="bloque_5">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn" type="text" value="tblTablaCli" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<table border="0" id="tblTablaCli" align="center">
<thead>
<tr align="left">
<th>Id</th>
<th>Nombre</th>
<th>Localidad</th>
</tr>
</thead>
<tbody> <?php
if (!empty($_SESSION["_usrzonas"])) {
$_clientes = DataManager::getCuentas( 0, 0, 1, NULL, '"C","CT","T","TT"', $_SESSION["_usrzonas"], 2);
if (count($_clientes)) {
//Consulto si la planificacion fue enviada para que los clientes se carguen en planif o partes
$_estado = 0;
$_planificacion = DataManager::getDetallePlanificacion($_fecha_planif, $_SESSION["_usrid"]);
if (count($_planificacion) > 0){
foreach ($_planificacion as $k => $_planif) {
$_planif = $_planificacion[$k];
$_planactiva = $_planif["planifactiva"];
if($_planactiva == 0){ $_estado = 1; }
}
}
if($_estado == 0){ ?>
<tr class="par" onclick="javascript:dac_Carga_Planificacion('999999', 'Otra Actividad', 'Otra Actividad', '1')">
<td>999999</td>
<td>Otra Actividad</td>
<td>Otra Actividad</td>
</tr>
<tr class="impar" onclick="javascript:dac_Carga_Planificacion('888888', 'Nuevos Clientes', 'Nuevos Clientes', '1')">
<td>888888</td>
<td>Nuevos Clientes</td>
<td>Nuevos Clientes</td>
</tr>
<?php
} else { ?>
<tr class="par" onclick="javascript:dac_Carga_Parte('999999', 'Otra Actividad', 'Otra Actividad', '', '', '', '1', '0', '<?php echo $_acciones; ?>')">
<td>999999</td>
<td>Otra Actividad</td>
<td>Otra Actividad</td>
</tr>
<tr class="impar" onclick="javascript:dac_Carga_Parte('888888', 'Nuevos Clientes', 'Nuevos Clientes', '', '', '', '1', '0', '<?php echo $_acciones; ?>')">
<td>888888</td>
<td>Nuevos Clientes</td>
<td>Nuevos Clientes</td>
</tr> <?php
}
foreach ($_clientes as $k => $_cliente) {
$_Cid = $_cliente["ctaid"];
$_Cidcliente = $_cliente["ctaidcuenta"];
$ctaActiva = $_cliente["ctaactiva"];
$ctaTipo = $_cliente["ctatipo"];
if($_Cidcliente != 0){
$_Cnombre = $_cliente["ctanombre"];
$_Ccuit = $_cliente["ctacuit"];
$_Cdireccion = ($_cliente["ctaidloc"] == 0) ? $_cliente["ctalocalidad"] : DataManager::getLocalidad('locnombre', $_cliente["ctaidloc"]) ;
$_Ccorreo = $_cliente["ctacorreo"];
((($k % 2) == 0)? $clase="par" : $clase="impar");
if($_estado == 0){
$_onclick = "javascript:dac_Carga_Planificacion('".$_Cidcliente."', '".$_Cnombre."', '".$_Cdireccion."', '1')";
} else {
$_onclick = "javascript:dac_Carga_Parte('".$_Cidcliente."', '".$_Cnombre."', '".$_Cdireccion."', '', '', '', '1', '0', '".$_acciones."')";
} ?>
<tr class="<?php echo $clase;?>" onclick="<?php echo $_onclick;?>">
<td><?php echo $_Cidcliente;?></td>
<td><?php echo $_Cnombre;?></td>
<td><?php echo $_Cdireccion;?></td>
</tr> <?php
}
}
} else {?>
<tr>
<td colspan="3"><?php echo "No se encontraron registros."; ?></td>
</tr> <?php
}
} ?>
</tbody>
</table>
</div> <!-- Fin lista -->
<?php }?>
</div> <!-- Fin box_seccion -->
<hr>
<!-- Scripts para calendario -->
<script language="JavaScript" src="/pedidos/planificacion/logica/jquery/jqueryUsrFooter.js" type="text/javascript"></script>
<?php if ($_SESSION["_usrrol"]== "G" || $_SESSION["_usrrol"]== "A"){ ?>
<script language="JavaScript" src="/pedidos/planificacion/logica/jquery/jqueryAdminFooter.js" type="text/javascript"></script>
<?php } ?><file_sep>/includes/classHiper/class.cuenta.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/pedidos/includes/class/class.PropertyObject.php');
class THiperCuenta extends PropertyObject {
protected $_tablename = 'Clientes';
protected $_fieldid = 'ctaid';
/*
protected $_fieldid = 'IdEmpresa';
protected $_fieldidTwo = 'IdCliente';
*/
protected $_fieldactivo = 'ctaactiva';
protected $_timestamp = 0;
protected $_id = 0;
//protected $_idTwo = '';
//protected $_idThree = 0;
public function __construct($_id=NULL) { /*, $_idTwo=NULL/*, $_idThree=NULL*/
$this->_timestamp = time();
$this->_id = $_id;
//$this->_idTwo = $_idTwo;
//$this->_idThree = $_idThree;
if ($_id) {
$arData = DataManagerHiper::loadFromDatabase($this, $_id); /*, $_idTwo/*, $_idThree*/
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'ctaid';
$this->propertyTable['Empresa'] = 'IdEmpresa';
$this->propertyTable['Cuenta'] = 'IdCliente';
$this->propertyTable['Tipo'] = 'ctatipo'; //CLIENTE/TRANSFER/PROSPECTO/PROVEEDOR
$this->propertyTable['Estado'] = 'ctaestado'; //Estado actual Ej: Solicita Alta
$this->propertyTable['Nombre'] = 'NombreCLI';
$this->propertyTable['CUIT'] = 'CuitCLI';
$this->propertyTable['Zona'] = 'IdVendedor'; //idvendedor ASIGNADO en HIPERWIN!
$this->propertyTable['ZonaEntrega'] = 'Zona'; //Zona de entrega depósito
$this->propertyTable['Pais'] = 'IdPais';
$this->propertyTable['Provincia'] = 'IdProvincia';
$this->propertyTable['Localidad'] = 'ctaidloc';
$this->propertyTable['LocalidadNombre'] = 'LocalidadCLI';
$this->propertyTable['Direccion'] = 'ctadireccion';
$this->propertyTable['DireccionCompleta'] = 'DomicilioCLI';
$this->propertyTable['DireccionEntrega'] = 'EntregaCLI';
$this->propertyTable['Numero'] = 'ctadirnro';
$this->propertyTable['Piso'] = 'ctadirpiso';
$this->propertyTable['Dpto'] = 'ctadirdpto';
$this->propertyTable['CP'] = 'CPostalCLI';
$this->propertyTable['Longitud'] = 'ctalongitud';
$this->propertyTable['Latitud'] = 'ctalatitud';
$this->propertyTable['Ruteo'] = 'ctaruteo';
$this->propertyTable['CategoriaComercial'] = 'Categoria';
$this->propertyTable['Referencias'] = 'ctareferencias';
$this->propertyTable['CuentaContable'] = 'CuentaContable'; //tabla cuentascontables Hiper
$this->propertyTable['CondicionPago'] = 'IdCondPago';
$this->propertyTable['Empleados'] = 'ctacantempleados';
$this->propertyTable['Bonif1'] = 'Bonif1';
$this->propertyTable['Bonif2'] = 'Bonif2';
$this->propertyTable['Bonif3'] = 'Bonif3';
$this->propertyTable['CategoriaIVA'] = 'TipoIvaCLI';
$this->propertyTable['RetencPercepIVA'] = 'Ret_IVA';
$this->propertyTable['Credito'] = 'ctacredito'; //límite aceptado al cliente
$this->propertyTable['NroEmpresa'] = 'NroEmpresa'; //Empresa con qse relaciona la cta
$this->propertyTable['NroIngresosBrutos'] = 'NroIBruCLI';
$this->propertyTable['FechaAlta'] = 'FechaAlta';
$this->propertyTable['FechaCompra'] = 'FechaUcom';
$this->propertyTable['Email'] = 'EmailCLI';
$this->propertyTable['Telefono'] = 'TelefonoCLI';
$this->propertyTable['Web'] = 'ctaweb';
$this->propertyTable['Observacion'] = 'ObservCLI';
$this->propertyTable['Imagen1'] = 'ctaimagen1'; //id de imagen
$this->propertyTable['Imagen2'] = 'ctaimagen2'; //id de imagen
$this->propertyTable['IDCuentaRelacionada'] = 'ctaidctarelacionada'; //tabla "cuenta_relacionada"
$this->propertyTable['UsrCreated'] = 'ctausrcreated';
$this->propertyTable['DateCreated'] = 'ctacreated';
$this->propertyTable['UsrAssigned'] = 'ctausrassigned';
$this->propertyTable['UsrUpdate'] = 'ctausrupdate';
$this->propertyTable['LastUpdate'] = 'ctaupdate';
$this->propertyTable['Activa'] = 'ctaactiva';
$this->propertyTable['Lista'] = 'Lista';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
/*public function __getFieldIDTwo() {
return $this->_fieldidTwo;
}
/*
public function __getFieldIDThree() {
return $this->_fieldidThree;
}*/
}
?><file_sep>/articulos/logica/changestatus.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$id = empty($_REQUEST['id']) ? 0 : $_REQUEST['id'];
if ($id) {
$artObject = DataManager::newObjectOfClass('TArticulo', $id);
$status = ($artObject->__get('Activo')) ? 0 : 1;
$artObject->__set('Activo', $status);
$artObjectHiper = DataManagerHiper::newObjectOfClass('THiperArticulo', $id);
$artObjectHiper->__set('Activo', $status);
DataManagerHiper::updateSimpleObject($artObjectHiper, $id);
DataManager::updateSimpleObject($artObject);
// Registro MOVIMIENTO //
$movimiento = 'ChangeStatus';
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TArticulo", $id);
}
echo "1"; exit;
?><file_sep>/movimientos/lista.php
<div class="box_down">
<div class="barra">
<div class="bloque_5">
<h1>Registro de Movimientos</h1>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<div id='tablaMovimientos'></div>
</div> <!-- Fin listar -->
<!--div class="lista_super">
<table>
<thead>
<tr>
<th scope="colgroup" width="5%">ID</th>
<th scope="colgroup" width="15%">Origen</th>
<th scope="colgroup" width="10%">Id Origen</th>
<th scope="colgroup" width="10%">Transacción</th>
<th scope="colgroup" width="20%">Operación</th>
<th scope="colgroup" width="20%">Fecha</th>
<th scope="colgroup" width="20%">Usuario</th>
</tr>
</thead>
<?php
/*$movimientos = DataManager::getMovimientos(1, 20);
if($movimientos){
foreach ($movimientos as $k => $mov) {
$id = $mov['movid'];
$operacion = $mov['movoperacion'];
$transaccion= $mov['movtransaccion'];
$origen = $mov['movorigen'];
$origenId = $mov['movorigenid'];
$fecha = $mov['movfecha'];
$usuario = $mov['movusrid'];
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>", $id, $origen, $origenId, $transaccion, $operacion, $fecha, $usuario);
echo sprintf("</tr>");
}
}*/ ?>
</table>
</div-->
<div class="barra">
<div class="bloque_1" style="text-align: right;">
<!-- paginador de jquery -->
<paginator></paginator>
<input id="totalRows" hidden="hidden">
</div>
<hr>
</div> <!-- Fin barra -->
</div>
<script src="/pedidos/js/jquery/jquery.paging.js"></script>
<script>
//#######################################
// PAGING DACIOCCO
//#######################################
//Funcion que devuelve cantidad de Filas
function dac_filas(callback) {
/*var empresa = $('#empselect').val(),
tipo = $('#tiposelect').val(),
activos = $('#actselect').val();*/
$.ajax({
type : "POST",
cache : false,
url : '/pedidos/movimientos/logica/ajax/getFilasMovimientos.php',
/*data: { empselect : empresa,
tiposelect : tipo,
actselect : activos
},*/
success : function(totalRows){
if(totalRows){
$("#totalRows").val(totalRows);
callback(totalRows);
}
},
});
}
//---------------------------------------
//Cantidad de filas por página
var rows = 25;
//Setea datos de acceso a datos vía AJAX
var data = { //los indices deben ser iguales a los id de los select
/*empselect : $('#empselect').val(),
actselect : $('#actselect').val(),
tiposelect : $('#tiposelect').val()*/
};
var url = 'logica/ajax/getMovimientos.php';
var tableName = 'tablaMovimientos';
var selectChange= []; //'tiposelect', 'empselect', 'actselect'
//---------------------------------------
//Llamada a función generadora del paginado
dac_filas(function(totalRows) {
$("paginator").paging(rows, totalRows, data, url, tableName, selectChange);
});
</script><file_sep>/pedidos/logica/exportar.pendientes.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=PedidosPendientes-".date('d-m-y').".xls");
?>
<!DOCTYPE html>
<html>
<TITLE>::. Exportacion de Datos .::</TITLE>
<head></head>
<body>
<?php
// Recorro por empresa //
$_empresas = DataManager::getEmpresas(1);
if ($_empresas) {
foreach ($_empresas as $k => $_emp) {
$_idempresa = $_emp['empid'];
$_nombreemp = $_emp['empnombre'];
// Selecciono los Pedidos Activos por Empresa PARA Pre-facturar //
$_pedidos = DataManager::getPedidos(NULL, 1, NULL, $_idempresa, NULL, 0);
if ($_pedidos) { ?>
<table id="tblExport_<?php echo $_idempresa;?>" border="1">
<TR>
<TD colspan="2">Fecha:</TD>
<TD colspan="3" align="left"><?php echo date("d/m/y H:i:s"); ?></TD>
<TD colspan="11" align="center"><?php echo $_nombreemp;?></TD>
</TR>
<TR>
<TD colspan="2">Exportado por:</TD>
<TD colspan="3"><?php echo $_SESSION["_usrname"]; ?></TD>
<TD colspan="11" align="center"></TD>
</TR>
<TR>
<TD width="1px">Fecha</TD>
<TD width="1px">Vendedor</TD>
<TD width="1px">Cliente</TD>
<TD width="1px">Pedido</TD>
<TD width="1px">Lab</TD>
<TD width="1px">IdArt</TD>
<TD width="1px">Cant</TD>
<TD width="1px">Precio</TD>
<TD width="1px">B1</TD> <TD width="1px">B2</TD>
<TD width="1px">D1</TD> <TD width="1px">D2</TD> <TD width="1px">D3</TD>
<TD width="1px">CondPago</TD>
<TD width="1px">OC</TD>
<TD width="1px">Observación</TD>
</TR> <?php
foreach ($_pedidos as $j => $_pedido) {
$_idpedido = $_pedido["pid"];
$_idusuario = $_pedido["pidusr"];
//datos para control
$_idemp = $_pedido["pidemp"];
$idCondComercial= $_pedido["pidcondcomercial"];
//*****************//
$_fecha_pedido = substr($_pedido['pfechapedido'], 0, 10);
$_nombreusr = DataManager::getUsuario('unombre', $_idusuario);
$_idcli = $_pedido["pidcliente"];
$_nropedido = $_pedido["pidpedido"];
$_idlab = $_pedido["pidlab"];
$_idart = $_pedido['pidart'];
$_nombreart = DataManager::getArticulo('artnombre', $_idart, $_idemp, $_idlab);
$_cantidad = $_pedido['pcantidad'];
$_precio = round($_pedido['pprecio'], 3);
$_b1 = $_pedido['pbonif1'];
$_b2 = $_pedido['pbonif2'];
$_desc1 = $_pedido['pdesc1'];
$_desc2 = $_pedido['pdesc2'];
$_desc3 = '';
$_condpago = $_pedido["pidcondpago"];
$_ordencompra = ($_pedido["pordencompra"] == 0) ? '' : $_pedido["pordencompra"];
$_observacion = $_pedido["pobservacion"];
$_b1 = ($_b1 == 0) ? '' : $_b1;
$_b2 = ($_b2 == 0) ? '' : $_b2;
$_desc1 = ($_desc1 == 0) ? '' : $_desc1;
$_desc2 = ($_desc2 == 0) ? '' : $_desc2;
?>
<TR>
<TD><?php echo $_fecha_pedido; ?></TD><TD><?php echo $_nombreusr; ?></TD><TD><?php echo $_idcli; ?></TD><TD><?php echo $_nropedido; ?><TD><?php echo $_idlab; ?></TD><TD><?php echo $_idart; ?></TD><TD><?php echo $_cantidad; ?></TD><TD><?php echo $_precio; ?></TD><TD><?php echo $_b1; ?></TD><TD><?php echo $_b2; ?></TD><TD><?php echo $_desc1; ?></TD><TD><?php echo $_desc2; ?></TD><TD><?php echo $_desc3; ?></TD><TD><?php echo $_condpago; ?></TD><TD><?php echo $_ordencompra; ?></TD><TD><?php echo $_observacion; ?></TD>
</TR> <?php
} ?>
</table>
<?php
} //fin if pedido
} //fin for
} else { echo "No se encuentran EMPRESAS ACTIVAS. Gracias."; } ?>
</body>
</html><file_sep>/ayuda/lista.php
<div class="box_body">
<fieldset>
<legend>Instructivo</legend>
<div class="bloque_1">
<div id="file" style="overflow:auto;"></div>
</div>
</fieldset>
</div> <!-- Fin box_body -->
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Instructivos</h1>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista"><?php
$ruta = $_SERVER['DOCUMENT_ROOT'].'/pedidos/ayuda/archivos/';
$data = dac_listar_directorios($ruta);
if($data){ ?>
<table align="center">
<thead>
<tr align="left">
<th>Subido</th>
<th>Instructivo</th>
</tr>
</thead>
<tbody>
<?php
$row = 0;
foreach ($data as $file => $timestamp) {
$name = explode("-", $timestamp);
$archivo = trim($name[3]);
$row += 1;
(($row % 2) == 0)? $clase="par" : $clase="impar";
?>
<tr class="<?php echo $clase;?> cursor-pointer" onclick="javascript:dac_ShowFactura('<?php echo $archivo;?>')">
<td><?php echo $name[0]."/".$name[1]."/".$name[2]; ?></td>
<td><?php echo $archivo; ?></td>
</tr>
<?php
} ?>
</tbody>
</table> <?php
} else { ?>
<table>
<thead>
<td colspan="3" align="center"><?php echo "No hay archivos cargados"; ?></td>
</thead>
</table><?php
} ?>
</div> <!-- Fin listar -->
</div> <!-- Fin box_seccion -->
<hr>
<script language="JavaScript" type="text/javascript">
function dac_ShowFactura(archivo){
$("#file").empty();
campo = '<iframe src=\"https://docs.google.com/gview?url=https://neo-farma.com.ar/pedidos/ayuda/archivos/'+archivo+'&embedded=true\" style=\"width:560px; height:800px;\" frameborder=\"0\"></iframe>';
$("#file").append(campo);
}
</script><file_sep>/includes/class.dm.php
<?php
require_once('class.Database.php');
require_once('class.phpmailer.php');
require_once('class.smtp.php');
require_once('class/class.usuario.php');
require_once('class/class.noticias.php');
require_once('class/class.zona.php');
require_once('class/class.articulo.php');
require_once('class/class.articulodispone.php');
require_once('class/class.articuloformula.php');
require_once('class/class.pedido.php');
require_once('class/class.pedidotransfer.php');
require_once('class/class.pack.php');
require_once('class/class.planificacion.php');
require_once('class/class.partediario.php');
require_once('class/class.accion.php');
require_once('class/class.rendicion.php');
require_once('class/class.cheques.php');
require_once('class/class.facturas.php');
require_once('class/class.recibos.php');
require_once('class/class.bonificacion.php');
require_once('class/class.abm.php');
require_once('class/class.drogueria.php');
require_once('class/class.drogueriaCAD.php');
require_once('class/class.liquidacion.php');
require_once('class/class.condicion.php');
require_once('class/class.condicionesdepago.php');
require_once('class/class.condiciontransfer.php');
require_once('class/class.listas.php'); //listas de precios
require_once('class/class.condicionespecial.php');
require_once('class/class.proveedor.php');
require_once('class/class.facturaprov.php');
require_once('class/class.contacto.php');
require_once('class/class.prospecto.php');
require_once('class/class.relevamiento.php');
require_once('class/class.respuesta.php');
require_once('class/class.llamada.php');
require_once('class/class.condicioncomercial.php');
require_once('class/class.condicioncomercial.art.php');
require_once('class/class.condicioncomercial.bonif.php');
require_once('class/class.agenda.php');
require_once('class/class.cuenta.php');
require_once('class/class.cuentarelacionada.php');
require_once('class/class.propuesta.php');
require_once('class/class.propuesta.detalle.php');
require_once('class/class.estado.php');
require_once('class/class.imagen.php');
require_once('class/class.cadena.php');
require_once('class/class.cadenacuentas.php');
require_once('class/class.ticket.php');
require_once('class/class.ticketmotivo.php');
require_once('class/class.ticketmensaje.php');
require_once('class/class.localidad.php');
require_once('class/class.areas.php');
require_once('class/class.movimiento.php');
class DataManager {
//--------------------------
// FUNCIONES GENERICAS
//--------------------------
public static function _getConnection($dsn = '') {
static $hDB;
try {
//$hDB = Database::instance($dsn);
if(!$dsn){
$hDB = Database::instance();
} else {
$hDB = Database::instanceHiper();
}
} catch (Exception $e) {
die("Imposible conexion con BBDD<BR>");
}
return $hDB;
}
// Busca el id de la tabla que desee!?
public static function getIDByField($_class=null,$_field=null,$_value=null) {
$_id = 0;
$_object = DataManager::newObjectOfClass($_class);
if ($_object && $_field && $_value) {
$sql = "SELECT {$_object->__getFieldID()} FROM {$_object->__getTableName()} WHERE {$_field}='{$_value}' LIMIT 1";
$hDB = DataManager::_getConnection(); //$dbname
try {
$_id = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error Q = $sql<br/>");
}
}
return $_id;
}
public static function newObjectOfClass($_class=null, $_id=NULL) {
$_object = null;
if (!empty($_class)) {
if (class_exists($_class)) {
$_object = new $_class($_id);
}
}
return $_object;
}
public static function loadFromDatabase($_object=null, $_id=null) {
if (!empty($_object)) {
$_sql = sprintf("SELECT * FROM %s WHERE %s='%d' LIMIT 1", $_object->__getTableName(), $_object->__getFieldID(), $_id);
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getAll($_sql);
} catch (Exception $e) {
die("error ejecutando $_sql<br>");
}
return $data;
}
return null;
}
//CUENTA NÚMERO DE FILAS según la tabla del objeto enviado
public static function getNumeroFilasTotales($_class=NULL) {
$_numero = 0;
if ($_class) {
$_object = DataManager::newObjectOfClass($_class);
if ($_object) {
$sql = "SELECT COUNT(1) FROM {$_object->__getTableName()}";
}
$_numero = DataManager::getCount($sql);
}
return $_numero;
}
//*****************************
// CONSULTA SI EXISTEN DATOS CON UN ID Y COLUMNA INDICADO
//*****************************
public static function ExistFromDatabase($_object, $_field, $_ID) {
if (!empty($_ID)) {
$_sql = sprintf("SELECT COUNT(*) FROM %s WHERE %s=%s", $_object->__getTableName(), $_field, $_ID);
$hDB = DataManager::_getConnection();
$_total = DataManager::getCount($_sql);
}
return $_total;
}
//CUENTA FILAS DE LA CONSULTA SQL ENVIADA $sql = select count(*) ....
public static function getCount( $sql ) {
$hDB = DataManager::_getConnection();
$data = 0;
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
//Este Error ejecutando lo da también cuando la tabla está vacía,
//por lo cual habría que controlar eso para que no de error en esos casos.
die("error ejecutando $sql<br>");
}
return $data;
}
// SIMPLE OBJECT
// CLASES DERIVADAS DE PropertyObject y que tengan propiedad == ID
public static function updateSimpleObject($_object) {
$hDB = DataManager::_getConnection();
$_rows = 0;
$_fields = $_object->__getUpdated();
if (count($_fields) > 0) {
$hDB->startTransaction();
try {
$_ID = $_object->__get('ID');
$_fieldID = $_object->__getFieldName('ID');
$_rows = $hDB->update($_object->__getTableName(), $_fields, "$_fieldID=$_ID");
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transacción abortada. ERR=" . $e->getMessage();
}
}
return $_rows;
}
public static function deleteSimpleObject($_object) {
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
$_rows = 0;
try {
$_ID = $_object->__get('ID');
$_fieldID = $_object->__getFieldName('ID');
$_theSQL = sprintf("DELETE FROM %s WHERE %s=%s", $_object->__getTableName(), $_fieldID, $_ID);
$_rows = $hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_rows;
}
public static function insertSimpleObject($_object) {
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
$_ID = 0;
try {
$_ID = $hDB->insert($_object->__getTableName(), $_object->__getData());
$hDB->commit();
$_object->__set('ID', $_ID); // Para que el objeto quede consistente con la BD
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_ID;
}
//*****************************
// CONSULTA COUNT COLS DE TABLA
//*****************************
public static function informationSchema($tableName = NULL) {
$hDB = DataManager::_getConnection();
$sql = sprintf("SELECT * FROM information_schema.columns WHERE table_name = %s", $tableName);
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//*******************************
//********************************
// FUNCIONES SIN USO DE CLASES
//********************************
public static function deletefromtabla($_tabla, $_fieldID, $_ID) {
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
$_rows = 0;
try {
$_theSQL = sprintf("DELETE FROM %s WHERE %s=%s", $_tabla, $_fieldID, $_ID);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_rows;
}
public static function insertfromtabla($_tabla, $_fieldID, $_ID, $_values) {
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
try {
$_theSQL = sprintf("INSERT INTO %s (%s) VALUES (%s, %s)", $_tabla, $_fieldID, $_ID, $_values);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_ID;
}
//****************************************************************
//Para INSERTAR DATOS en tablas que no tienen Campo UNIQUE
//****************************************************************
public static function insertToTable($_tabla, $_fieldID, $_values, $_ID=0) {
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
try {
$_theSQL = sprintf("INSERT INTO %s (%s) VALUES (%s)", $_tabla, $_fieldID, $_values);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_ID;
}
public static function updateToTable($_tabla, $_fieldID, $_condition="TRUE") {
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
$_rows = 0;
if($_fieldID){
try {
$_theSQL = sprintf("UPDATE %s SET %s WHERE %s", $_tabla, $_fieldID, $_condition);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
}
return $_rows;
}
public static function deleteToTable($_tabla, $_campos = NULL) {
if (empty($_campos) || is_null($_campos)){ $_condicionWhere = "TRUE";
} else {$_condicionWhere = $_campos;}
$hDB = DataManager::_getConnection();
try {
$_theSQL = sprintf("DELETE FROM %s WHERE (%s)", $_tabla, $_condicionWhere);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_ID;
}
//****************************************************************
// FUNCIONES DEFINIDAS POR TABLAS
//****************************************************************
//********************
// LISTAR PEDIDOS
//********************
public static function getPedidos($idUsr=NULL, $mostrarTodos=NULL, $_nrosPedidos=NULL, $empresa=NULL, $_negociacion=NULL, $_aprobado=NULL, $_pag=NULL, $_rows=NULL, $dateFrom=NULL, $dateTo=NULL){
$hDB = DataManager::_getConnection();
if ((empty($idUsr) && $idUsr != 0) || is_null($idUsr)){ $_condicionUsr = "TRUE";
} else { $_condicionUsr = "pidusr=".$idUsr;}
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else { $_condicionActivos = "pactivo=".$mostrarTodos;}
if ((empty($_nrosPedidos) && $_nrosPedidos != 0) || is_null($_nrosPedidos)){ $_condicionNroPedido = "TRUE";
} else { $_condicionNroPedido = "pidpedido IN (".$_nrosPedidos.")";}
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else { $_condicionEmpresa = "pidemp=".$empresa;}
if ((empty($_negociacion) && $_negociacion != 0) || is_null($_negociacion)){ $_condicionNegociacion = "TRUE";
} else { $_condicionNegociacion = "pnegociacion=".$_negociacion;}
if ((empty($_aprobado) && $_aprobado != 0) || is_null($_aprobado)){ $_condicionAprobado = "TRUE";
} else { $_condicionAprobado = "paprobado=".$_aprobado;}
if (empty($dateFrom) || is_null($dateFrom)){ $_conditionFrom = "TRUE";
} else {$_conditionFrom = "pfechapedido >= '".$dateFrom."'";}
if (empty($dateTo) || is_null($dateTo)){ $_conditionTo = "TRUE";
} else {$_conditionTo = "pfechapedido <= '".$dateTo."'";}
$sql = "SELECT * FROM pedido WHERE ($_condicionNroPedido) AND ($_condicionActivos) AND ($_condicionUsr) AND ($_condicionEmpresa) AND ($_condicionNegociacion) AND ($_condicionAprobado) AND ($_conditionFrom) AND ($_conditionTo) ORDER BY pidpedido DESC ";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getPedidosEntre($mostrarTodos = NULL, $desde = NULL, $hasta = NULL){
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else { $_condicionActivos = "pactivo=".$mostrarTodos;}
if (empty($desde) || is_null($desde)){
$_fecha_inicio = strtotime ( '-1 year' , strtotime ( date("Y-m-d H:m:s") ) ) ;
$_fecha_inicio = date ( "Y-m-d H:m:s" , $_fecha_inicio );
$_condicionDesde = $_fecha_inicio;
} else {
$_condicionDesde = $desde;
}
$_condicionHasta = $hasta;
$_condicionFecha = "pfechapedido BETWEEN '".($_condicionDesde)."' AND '".($_condicionHasta)."'";
$sql = "SELECT DISTINCT pidpedido FROM pedido WHERE ($_condicionActivos) AND ($_condicionFecha) ORDER BY pidpedido DESC ";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//------------------------
// LISTADO TRANSFERS 2
//-------------------------
public static function getTransfersPedido($mostrarTodos = NULL, $desde = NULL, $hasta = NULL, $idDrog = NULL, $tipo = NULL, $idVendedor = NULL, $idPedido = NULL, $idCuenta = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "ptactivo=".$mostrarTodos;}
if (empty($idDrog) || is_null($idDrog)){ $_condicionDrogueria = "TRUE";
} else {$_condicionDrogueria = "ptiddrogueria=".$idDrog;}
if (empty($tipo) || is_null($tipo)){ $_condicionTipo = "TRUE";
} else {$_condicionTipo = "ptliquidado=".$tipo;}
if (empty($desde) || is_null($desde) || empty($hasta) || is_null($hasta)){ $_condicionDate = "TRUE";
} else { $_condicionDate = "ptfechapedido BETWEEN '".$desde."' AND '".$hasta."'";}
if ((empty($idVendedor) && $idVendedor != '0') || is_null($idVendedor)){ $_condicionVendedor = "TRUE";
} else {$_condicionVendedor = "ptidvendedor=".$idVendedor;}
if ((empty($idPedido) && $idPedido != '0') || is_null($idPedido)){ $_condicionNroTransfer = "TRUE";
} else {$_condicionNroTransfer = "ptidpedido=".$idPedido;}
if ((empty($idCuenta) && $idCuenta != '0') || is_null($idCuenta)){ $_condicionCuenta = "TRUE";
} else {$_condicionCuenta = "ptidclineo=".$idCuenta;}
$sql = "SELECT * FROM pedidos_transfer WHERE ($_condicionDate) AND ($_condicionDrogueria) AND ($_condicionTipo) AND ($_condicionActivos) AND ($_condicionVendedor) AND ($_condicionNroTransfer) AND ($_condicionCuenta) ORDER BY ptidpedido DESC, ptidart ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//---------------------
// LISTADO TRANSFER por VENDEDOR AGRUPADO por pedido para exportar XLS
//---------------------
public static function getTransfersVendedorXLS($mostrarTodos = NULL, $_IDVendedor) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "ptactivo=".$mostrarTodos;}
$_condicionVendedor = "ptidvendedor=".$_IDVendedor;
$sql = "SELECT * FROM pedidos_transfer WHERE ($_condicionActivos) AND ($_condicionVendedor) GROUP BY ptidpedido, ptclirs ORDER BY ptidpedido DESC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//--------------------
// LISTADO TRANSFER DISTINCT
//--------------------
public static function getTransfers($mostrarTodos = NULL, $_IDVendedor = NULL, $dateFrom = NULL, $dateTo = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "ptactivo=".$mostrarTodos;}
if (empty($dateFrom) || is_null($dateFrom)){ $_conditionFrom = "TRUE";
} else {$_conditionFrom = "ptfechapedido >= '".$dateFrom."'";}
if (empty($dateTo) || is_null($dateTo)){ $_conditionTo = "TRUE";
} else {$_conditionTo = "ptfechapedido <= '".$dateTo."'";}
if (empty($_IDVendedor) || is_null($_IDVendedor)){ $_condicionVendedor = "TRUE";
} else {$_condicionVendedor = "ptidvendedor=".$_IDVendedor;}
$sql = "SELECT DISTINCT ptidpedido, ptclirs, ptfechapedido FROM pedidos_transfer WHERE ($_condicionActivos) AND ($_conditionFrom) AND ($_conditionTo) AND ($_condicionVendedor) ORDER BY ptidpedido DESC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//**********************************//
// ULTIMO NÚMERO DEL CAMPO INDICADO //
//**********************************//
public static function dacLastId($_tabla, $_campo) {
$max = 0;
$hDB = DataManager::_getConnection();
$sql = "SELECT MAX($_campo) AS MaxNroPedido FROM $_tabla";
try {
$_numero = $hDB->getOne($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return ($_numero+1);
}
//--------------------
// TABLA DROGUERIAS p/TRANSFERs
//--------------------
public static function getDrogueria($mostrarTodos = NULL, $empresa = NULL, $drogueriaCad = NULL, $destino = NULL, $drogueriaCuenta = NULL ) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "drogtactiva=".$mostrarTodos;}
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "drogtidemp=".$empresa;}
if ((empty($drogueriaCuenta) && $drogueriaCuenta != 0) || is_null($drogueriaCuenta)){ $_condicionCuenta = "TRUE";
} else {$_condicionCuenta = "drogtcliid=".$drogueriaCuenta;}
if ((empty($drogueriaCad) && $drogueriaCad != 0) || is_null($drogueriaCad)){ $_condicionDrogueria = "TRUE";
} else {$_condicionDrogueria = "drgdcadId=".$drogueriaCad;}
if ((empty($destino) && $destino != 0) || is_null($destino)){ $_condicionDestino = "TRUE";
} else {$_condicionDestino = "drogtcorreotransfer = '".$destino."'";}
$sql = "SELECT * FROM droguerias WHERE ($_condicionActivos) AND ($_condicionEmpresa) AND ($_condicionDrogueria) AND ($_condicionDestino) AND ($_condicionCuenta) ORDER BY drogtcliid ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// SELECCIONA DROGUERIA agrupadas por destino de correo
//********************
public static function getDrogueriaTransferTipo( $mostrarTodos=NULL ) {
$hDB = DataManager::_getConnection();
$_condicionActivos = ($mostrarTodos == NULL) ? "true" : "drogtactiva=$mostrarTodos";
$sql = "SELECT * FROM droguerias WHERE ($_condicionActivos) GROUP BY drogtcorreotransfer";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// TABLA de las DROGUERIAS CAD
//********************
public static function getDrogueriaCAD( $mostrarTodos = NULL, $empresa = NULL, $_ID = NULL ) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "drogtactiva=".$mostrarTodos;}
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "dcadIdEmpresa=".$empresa;}
if ((empty($_ID) && $_ID != '0') || is_null($_ID)){ $_condicionID = "TRUE";
} else {$_condicionID = "dcadId=".$_ID;}
$sql = "SELECT * FROM drogueriasCAD WHERE ($_condicionActivos) AND ($_condicionEmpresa) AND ($_condicionID) ORDER BY dcadNombre ASC, dcadActivo DESC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//-----------------
// Tabla USUARIOS
public static function getUsuarios( $_pag=0, $_rows=0, $mostrarTodos = NULL, $_zona = NULL, $_rol = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "uactivo=".$mostrarTodos;}
if ((empty($_zona) && $_zona != '0') || is_null($_zona)){ $_condicionZona = "TRUE";
} else {$_condicionZona = "zona IN (".$_zona.")";}
if ((empty($_rol) && $_zona != '0') || is_null($_rol)){ $_condicionRol = "TRUE";
} else {$_condicionRol = "urol IN (".$_rol.")";}
$sql = "SELECT *
FROM usuarios
WHERE ($_condicionActivos)
AND ($_condicionRol)
ORDER BY uactivo DESC, unombre ASC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//---------------------
// Tabla USUARIO
public static function getUsuario($_field=NULL, $_ID) {
if ($_ID) {
$sql = "SELECT $_field FROM usuarios WHERE uid='$_ID' LIMIT 1";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//-----------------
// Tabla AREAS
public static function getAreas( $mostrarTodos = NULL ) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "activo=".$mostrarTodos;}
$sql = "SELECT *
FROM areas
WHERE ($_condicionActivos)
ORDER BY descripcion DESC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//-----------------------
// Tabla PROVEEDORES
public static function getProveedores( $_pag=0, $_rows=0, $empresa=NULL, $mostrarTodos = TRUE) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "provactivo=".$mostrarTodos;}
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "providempresa=".$empresa;}
$sql = "SELECT * FROM proveedor WHERE ($_condicionActivos) AND ($_condicionEmpresa) ORDER BY provactivo DESC, providempresa ASC, provnombre ASC";
//($_rows == NULL) ? DataManager::getCount($sql) : $_rows;
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//----------------------------------------
// Tabla FACTURAS A PAGAR DE PROVEEDORES
public static function getFacturasProveedor( $empresa = NULL, $mostrarTodos = NULL, $fechaPago = NULL, $tipo = NULL, $factNumero = NULL, $idProv = NULL, $fechaDesde = NULL, $fechaHasta = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "factidemp=".$empresa;}
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "factactiva=".$mostrarTodos;}
if ((empty($fechaPago) && $fechaPago != '0000-00-00') || is_null($fechaPago) ){ $_condicionFechaPago = "TRUE";
} else {$_condicionFechaPago = "factfechapago='".$fechaPago."'";}
if (empty($tipo) || is_null($tipo) ){ $_condicionTipo = "TRUE";
} else {$_condicionTipo = "facttipo='".$tipo."'";}
if ((empty($factNumero) && $factNumero != '0') || is_null($factNumero) ){ $_condicionFactNumero = "TRUE";
} else {$_condicionFactNumero = "factnumero='".$factNumero."'";}
if ((empty($idProv) && $idProv != '0') || is_null($idProv) ){ $_condicionIdProv = "TRUE";
} else {$_condicionIdProv = "factidprov='".$idProv."'";}
if ((empty($fechaDesde) && $fechaDesde != '0000-00-00') || is_null($fechaDesde) ){ $_condicionFechaDesde = "TRUE";
} else {$_condicionFechaDesde = "factfechapago >='".$fechaDesde."'";}
if ((empty($fechaHasta) && $fechaHasta != '0000-00-00') || is_null($fechaHasta) ){ $_condicionFechaHasta = "TRUE";
} else {$_condicionFechaHasta = "factfechapago <='".$fechaHasta."'";}
$sql = "SELECT * FROM facturas_proveedor WHERE ($_condicionEmpresa) AND ($_condicionActivos) AND ($_condicionFechaPago) AND ($_condicionTipo) AND ($_condicionFactNumero) AND ($_condicionIdProv) AND ($_condicionFechaDesde) AND ($_condicionFechaHasta) ORDER BY factidemp ASC, factidprov DESC, factnumero DESC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// Select datos de un proveedor
public static function getProveedor($_field=NULL, $_ID, $empresa=NULL) {
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "providempresa=".$empresa;}
if ($_ID) {
$sql = "SELECT * FROM proveedor WHERE ($_field='$_ID') AND ($_condicionEmpresa) LIMIT 1";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//********************
// Tabla NOTICIAS
//********************
public static function getNoticias( $_pag=0, $_rows=20, $mostrarTodos = TRUE ) {
$hDB = DataManager::_getConnection();
$_condicionActivos = ($mostrarTodos) ? "true" : "ntactiva=1";
$sql = "SELECT * FROM noticias WHERE ($_condicionActivos) ORDER BY ntfecha DESC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// Tabla NOTICIAS
//********************
public static function getNoticiasActivas( $_pag=0, $_rows=20, $mostrarTodos = TRUE ) {
$hDB = DataManager::_getConnection();
$_condicionActivos = ($mostrarTodos) ? "true" : "ntactiva=1";
$sql = sprintf ("SELECT * FROM noticias WHERE ($_condicionActivos) ORDER BY ntfecha DESC");
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//----------------------------
// Tabla ZONA y por Vendedor
//----------------------------
public static function getZonas($_pag=0, $_rows=0, $mostrarTodos = TRUE) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){
$_condicionActivos = "TRUE";
} else {$_condicionActivos = "zactivo=".$mostrarTodos;}
$sql = "SELECT * FROM zona WHERE ($_condicionActivos) ORDER BY zzona ASC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//----------------------------
// Tabla ZONA Excepciones
//----------------------------
public static function getZonasExcepcion($idLoc = NULL, $zona = NULL, $ctaId = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($idLoc) && $idLoc != '0') || is_null($idLoc)){ $_condicionLocalidad = "TRUE";
} else {$_condicionLocalidad = "zeIdLoc=".$idLoc;}
if ((empty($zona) && $zona != '0') || is_null($zona)){ $_condicionZona = "TRUE";
} else {$_condicionZona = "zeZona=".$zona;}
if (empty($ctaId) || is_null($ctaId)){ $_condicionCta = "TRUE";
} else {$_condicionCta = "zeCtaId=".$ctaId;}
$sql = "SELECT * FROM zona_excepcion WHERE ($_condicionZona) AND ($_condicionLocalidad) AND ($_condicionCta)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//**************************
//Selecciona todas las zonas de un vendedor
public static function getZonasVendedor($_ID) { //, $mostrarTodos = TRUE
$hDB = DataManager::_getConnection();
//$_condicionActivos = ($mostrarTodos) ? "true" : "zactivo=1";
$_condicion = "uid = $_ID";
$sql = "SELECT * FROM zonas_vend WHERE ($_condicion) ORDER BY zona";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//----------------------------
// Tabla ZONA DISTRIBUCION
//----------------------------
public static function getZonasDistribucion($_pag=0, $_rows=0) {
$hDB = DataManager::_getConnection();
$sql = "SELECT * FROM zonas ORDER BY IdZona ASC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//----------------------------
// ZONA DISTRIBUCION
//----------------------------
public static function getZonaDistribucion($_field=NULL, $_field2=NULL, $_ID) {
$hDB = DataManager::_getConnection();
if ((empty($_ID) && $_ID != '0') || is_null($_ID)){ $_condicionID = "TRUE";
} else {$_condicionID = "IdZona=".$_ID;}
$sql = "SELECT $_field FROM zonas WHERE ($_field2='$_ID') LIMIT 1";
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//-------------------
// Tabla ARTICULOS
//-------------------
public static function getArticulos( $_pag=0, $_rows=20, $mostrarStock, $mostrarTodos=NULL, $laboratorio=NULL, $empresa=NULL) {
$hDB = DataManager::_getConnection();
$_condicionStock = ($mostrarStock) ? "artstock=1" : "TRUE"; //!?
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "artactivo=".$mostrarTodos;}
if ((empty($laboratorio) && $laboratorio != '0') || is_null($laboratorio)){ $_condicionLab = "TRUE";
} else {$_condicionLab = "artidlab=".$laboratorio;}
if ((empty($empresa) && $empresa != '0') || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "artidempresa=".$empresa;}
$sql = "SELECT * FROM articulo WHERE ($_condicionActivos) AND ($_condicionStock) AND ($_condicionLab) AND ($_condicionEmpresa) ORDER BY artactivo DESC, artidart ASC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//----------------------
// CAMPO DE UN ARTICULO
//----------------------
public static function getArticulo($_field=NULL, $_ID, $empresa=NULL, $laboratorio=NULL) {
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "1"; //"TRUE";
} else {$_condicionEmpresa = "artidempresa=".$empresa;}
if ((empty($laboratorio) && $laboratorio != 0) || is_null($laboratorio)){ $_condicionLaboratorio = "1"; //"TRUE";
} else {$_condicionLaboratorio = "artidlab=".$laboratorio;}
$_condicionArticulo = "artidart=".$_ID;
if ($_ID) {
$sql = "SELECT $_field FROM articulo WHERE ($_condicionArticulo) AND ($_condicionEmpresa) AND ($_condicionLaboratorio) LIMIT 1";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//----------------------
// CAMPO DE UN ARTICULO
//----------------------
public static function getArticuloAll($_field=NULL, $_field2=NULL, $_ID) {
if ($_ID) {
$sql = "SELECT $_field FROM articulo WHERE ($_field2 LIKE '$_ID') ORDER BY $_field2"; //AND ($_condicionEmpresa)
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//-------------------
// BUSCAR ARTICULO
//-------------------
public static function getFieldArticulo($_field = NULL, $_value = NULL) {
$hDB = DataManager::_getConnection();
$_condicionCampo = "$_field = $_value";
$sql = "SELECT * FROM articulo WHERE ($_condicionCampo) AND artidempresa=1 AND artidlab=1";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//-------------------------
// TABLA ARTICULO DISPONE
//-------------------------
public static function getArticuloDispone( $id=NULL ) {
$hDB = DataManager::_getConnection();
if (empty($id) || is_null($id)){ $_condicionID = "FALSE";
} else {$_condicionID = "adartid=".$id;}
$sql = "SELECT * FROM articulodispone WHERE ($_condicionID) LIMIT 1";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//-------------------------
// TABLA ARTICULO FORMULA
//-------------------------
public static function getArticuloFormula( $id=NULL ) {
$hDB = DataManager::_getConnection();
if (empty($id) || is_null($id)){ $_condicionID = "FALSE";
} else {$_condicionID = "afidartdispone=".$id;}
$sql = "SELECT * FROM articuloformula WHERE ($_condicionID) ORDER BY afid ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//-------------------------
// TABLA CODIGO FAMILIA ARTICULOS
//-------------------------
public static function getCodFamilias( $_pag=0, $_rows=0, $empresa=NULL, $familia=NULL) {
$hDB = DataManager::_getConnection();
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "Idempresa=".$empresa;}
if ((empty($familia) && $familia != 0) || is_null($familia)){ $_condicionFamilia = "TRUE";
} else {$_condicionFamilia = "IdFamilia=".$familia;}
$sql = "SELECT * FROM codfamilia WHERE ($_condicionEmpresa) AND ($_condicionFamilia) ORDER BY Nombre ASC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//-----------------
// TABLA RUBROS
//-----------------
public static function getRubros($id=NULL) {
$hDB = DataManager::_getConnection();
if ((empty($id) && $id != 0) || is_null($id)){ $_condicionId = "TRUE";
} else {$_condicionId = "IdRubro=".$id;}
$sql = "SELECT * FROM rubros WHERE ($_condicionId) ORDER BY Descripcion";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//--------------------
// Tabla PROVINCIAS
//--------------------
public static function getProvincias() {
$hDB = DataManager::_getConnection();
$sql = "SELECT * FROM provincia ORDER BY provid ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//--------------------
// Select PROVINCIA
//--------------------
public static function getProvincia($_field=NULL, $_ID) {
if ($_ID) {
$sql = "SELECT $_field FROM provincia WHERE provid='$_ID' LIMIT 1";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//--------------------
// Tabla LOCALIDADES
//--------------------
public static function getLocalidades($idLoc = NULL, $idProv = NULL, $zonaVend = NULL, $zonaEntrega = NULL, $_pag=0, $_rows=0) {
$hDB = DataManager::_getConnection();
if (empty($idLoc) || is_null($idLoc)){ $_condicionLocalidad = "TRUE"; }
else {$_condicionLocalidad = 'locidloc='.$idLoc;}
if (empty($idProv) || is_null($idProv)){ $_condicionProvincia = "TRUE"; }
else {$_condicionProvincia = 'locidprov='.$idProv;}
if (empty($zonaVend) || is_null($zonaVend)){ $_condicionZonaVend = "TRUE"; }
else {$_condicionZonaVend = 'loczonavendedor='.$zonaVend;}
if (empty($zonaEntrega) || is_null($zonaEntrega)){ $_condicionZonaEnt = "TRUE"; }
else {$_condicionZonaEnt = 'loczonaentrega='.$zonaEntrega;}
$sql = "SELECT * FROM localidad WHERE ($_condicionLocalidad) AND ($_condicionProvincia) AND ($_condicionZonaVend) AND ($_condicionZonaEnt) ORDER BY locidprov, locnombre ASC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//--------------------
// Select LOCALIDAD
public static function getLocalidad($_field=NULL, $_ID) {
if ($_ID) {
$sql = "SELECT $_field FROM localidad WHERE locidloc='$_ID' LIMIT 1";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//********************
// Tabla CUIDADES
//********************
public static function getDirecciones() {
$hDB = DataManager::_getConnection();
$sql = "SELECT * FROM direccion ORDER BY dirnombre ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// Tabla EMPRESAS
//********************
public static function getEmpresas($mostrarTodos = NULL) {
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "empactiva=".$mostrarTodos;}
$hDB = DataManager::_getConnection();
$sql = "SELECT * FROM empresas WHERE ($_condicionActivos) ORDER BY empid ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// EMPRESA
//********************
public static function getEmpresa($_field=NULL, $_ID) {
if ($_ID) {
$sql = "SELECT $_field FROM empresas WHERE empid='$_ID' LIMIT 1";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//********************
// Tabla LABORATORIOS
//********************
public static function getLaboratorios() {
$hDB = DataManager::_getConnection();
$sql = "SELECT * FROM laboratorios WHERE labactivo=1 ORDER BY idLab";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//------------------
// LABORATORIO
//------------------
public static function getLaboratorio($_field=NULL, $_ID) {
if ($_ID) {
$sql = "SELECT $_field FROM laboratorios WHERE idLab='$_ID' LIMIT 1";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//********************
// Tabla CONDICIONES DE PAGO
//********************
public static function getCondicionesDePago($_pag=0, $_rows=0, $mostrarTodos = NULL, $condPago = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != 0) || is_null($mostrarTodos)){ $_condicionActivos = "TRUE"; } else {$_condicionActivos = "condactiva=".$mostrarTodos;}
if ((empty($condPago) && $condPago != 0) || is_null($condPago)){ $_condicionPago = "TRUE"; } else {$_condicionPago = "IdCondPago=".$condPago;}
$sql = "SELECT * FROM condiciones_de_pago WHERE ($_condicionActivos) AND ($_condicionPago) ORDER BY condactiva DESC, Nombre1CP, Dias1CP ASC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// CAMPO CONDICION DE PAGO
//********************
public static function getCondicionDePago($_field=NULL, $_field2=NULL, $_ID=0) {
if ($_ID) {
$sql = "SELECT $_field FROM condiciones_de_pago WHERE ($_field2='$_ID') LIMIT 1";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//---------------------------------
// Tabla CONDICIONES DE PAGO TIPO
//---------------------------------
public static function getCondicionesDePagoTipo($mostrarTodos = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != 0) || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "condactiva=".$mostrarTodos;}
$sql = "SELECT * FROM condiciones_de_pago_tipos WHERE ($_condicionActivos) ORDER BY condactiva DESC, Descripcion, ID ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// CAMPO CONDICION DE PAGO TIPO
//********************
public static function getCondicionDePagoTipos($_field=NULL, $_field2=NULL, $_ID=0) {
if ($_ID) {
$sql = "SELECT $_field FROM condiciones_de_pago_tipos WHERE ($_field2='$_ID') LIMIT 1";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//********************
// Tabla CONDICIONES DE PAGO TRANSFER
//********************
public static function getCondicionesDePagoTransfer($_pag=0, $_rows=10, $mostrarTodos = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "condactiva=".$mostrarTodos;}
$sql = "SELECT * FROM condicion_de_pago_transfer WHERE ($_condicionActivos) ORDER BY condactiva DESC, conddias ASC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// CAMPO DE UNA CONDICION
//********************
public static function getCondicionDePagoTransfer($_field=NULL, $_field2=NULL, $_ID=0) {
if ($_ID) {
$sql = "SELECT $_field FROM condicion_de_pago_transfer WHERE ($_field2='$_ID') AND condidemp=1 LIMIT 1";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//********************
// Tabla PACKS
//********************
public static function getPacks( $_pag=0, $_rows=10, $mostrarTodos = NULL, $_date = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "packactiva=".$mostrarTodos;}
$_condicionDate = empty($_date) ? "TRUE" : "'".$_date."'"." BETWEEN packfechainicio AND packfechafin";
$sql = "SELECT * FROM pack WHERE ($_condicionActivos) AND ($_condicionDate) ORDER BY packfechainicio DESC, packnombre ASC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// DETALLE PACK
//********************
public static function getDetallePack($_idpack) {
$hDB = DataManager::_getConnection();
$_condicionPack = "pdpackid=".$_idpack;
$sql = "SELECT * FROM pack_detalle WHERE ($_condicionPack) ORDER BY pdartid ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//***********************
// DETALLE PLANIFICACION
//***********************
public static function getDetallePlanificacion($_fecha_planif, $idUsr) {
list($dia, $mes, $ano) = explode('-', str_replace('/', '-', $_fecha_planif));
$_fecha = $ano."-".$mes."-".$dia;
$hDB = DataManager::_getConnection();
$_condicionUsuario = "planifidvendedor=".$idUsr;
$_condicionFecha = "planiffecha LIKE '".$_fecha."'";
$sql = "SELECT * FROM planificado WHERE ($_condicionUsuario) AND ($_condicionFecha)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getDetallePlanifExportar($_fecha_inicio, $_fecha_fin) {
$hDB = DataManager::_getConnection();
$_condicionFecha = "planiffecha BETWEEN '".$_fecha_inicio."' AND '".$_fecha_fin."'";
$sql = "SELECT * FROM planificado WHERE ($_condicionFecha) ORDER BY planiffecha, planifidvendedor ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getControlEnvioPlanif($_fecha_inicio, $_fecha_fin, $_ID){
$hDB = DataManager::_getConnection();
$_condicionFecha = "planiffecha BETWEEN '".$_fecha_inicio."' AND '".$_fecha_fin."'";
$_condicionUsr = "planifidvendedor=".$_ID;
$sql = "SELECT * FROM planificado WHERE( $_condicionUsr) AND($_condicionFecha) ORDER BY planiffecha, planifidvendedor ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//***********************
// DETALLE PARTE DIARIO
//***********************
public static function getDetalleParteDiario($_fecha_parte, $idUsr) {
list($dia, $mes, $ano) = explode('-', str_replace('/', '-', $_fecha_parte));
$_fecha = $ano."-".$mes."-".$dia;
$hDB = DataManager::_getConnection();
$_condicionUsuario = "parteidvendedor=".$idUsr;
$_condicionFecha = "partefecha LIKE '".$_fecha."'";
$sql = "SELECT * FROM parte_diario WHERE ($_condicionUsuario) AND ($_condicionFecha) ORDER BY parteid ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getDetalleParteExportar($_fecha_inicio, $_fecha_fin) {
$hDB = DataManager::_getConnection();
$_condicionFecha = "partefecha BETWEEN '".$_fecha_inicio."' AND '".$_fecha_fin."'";
$sql = "SELECT * FROM parte_diario WHERE ($_condicionFecha) ORDER BY partefecha, parteidvendedor ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getControlEnvioPartes($_fecha_inicio, $_fecha_fin, $_ID){
$hDB = DataManager::_getConnection();
$_condicionFecha = "partefecha BETWEEN '".$_fecha_inicio."' AND '".$_fecha_fin."'";
$_condicionUsr = "parteidvendedor=".$_ID;
$sql = "SELECT * FROM parte_diario WHERE ($_condicionUsr) AND ($_condicionFecha) ORDER BY partefecha, parteidvendedor ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//***********************************************************//
// DELETE los registros planificacos en dicha fecha y vendedor
public static function deleteFromPlanificado($_ID, $_fecha) {
$_tabla = "planificado";
$_condicionVend = "planifidvendedor=$_ID";
$_condicionFecha = "planiffecha='".$_fecha."'";
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
$_rows = 0;
try {
$_theSQL = sprintf("DELETE FROM %s WHERE (%s) AND (%s)", $_tabla, $_condicionVend, $_condicionFecha);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_rows;
}
//***********************************************************//
// DELETE los registros DEL PARTE en dicha fecha y vendedor
public static function deleteFromParte($_ID, $_fecha) {
$_tabla = "parte_diario";
$_condicionVend = "parteidvendedor=$_ID";
$_condicionFecha = "partefecha='".$_fecha."'";
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
$_rows = 0;
try {
$_theSQL = sprintf("DELETE FROM %s WHERE (%s) AND (%s)", $_tabla, $_condicionVend, $_condicionFecha);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_rows;
}
//********************
// Tabla ACCIONES
//********************
public static function getAcciones($_pag=0, $_rows=20, $mostrarTodos) {
$hDB = DataManager::_getConnection();
$_condicionActivos = ($mostrarTodos)? "acactiva=".$mostrarTodos : TRUE;
$sql = "SELECT * FROM accion WHERE ($_condicionActivos) ORDER BY acid ASC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// Selecciona ACCION
//********************
public static function getAccion($_ID = NULL) {
$hDB = DataManager::_getConnection();
$_condicionAccion = ($_ID) ? "acid=".$_ID: "true";
$sql = "SELECT acnombre FROM accion WHERE ($_condicionAccion)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// Selecciona RENDICION
//********************
public static function getRendicion($_ID = NULL, $_NroRend, $mostrarTodos = NULL) {
$hDB = DataManager::_getConnection();
$_condicionUsr = "rendidusr = ".$_ID;
$_condicionRendicion = "rendnumero = ".$_NroRend;
$_condicionActivos = ($mostrarTodos == NULL) ? "true" : "rendactiva=".$mostrarTodos;
$sql = "SELECT * FROM rendicion WHERE ($_condicionUsr) AND ($_condicionRendicion) AND ($_condicionActivos)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql");
}
return $data;
}
//***********************************
// Selecciona Detalle de RENDICIÓN
//***********************************
public static function getDetalleRendicion($_ID = NULL, $_NroRend, $mostrarTodos = NULL) {
$hDB = DataManager::_getConnection();
$_condicionUsr = ($_ID) ? "rendicion.rendidusr =".$_ID : "true";
$_condicionRend = ($_NroRend) ? "rendicion.rendnumero =".$_NroRend : "true";
$_condicionActivos = ($mostrarTodos == NULL) ? "true" : "rendactiva=".$mostrarTodos;
$sql = "SELECT rendicion.rendid AS IDR, rendicion.rendactiva AS Activa, rendicion.rendretencion AS RetencionVend, rendicion.renddeposito AS Deposito, cuenta.ctaidcuenta AS Codigo, cuenta.ctanombre AS Nombre, cuenta.ctazonaentrega AS Zona, recibos.recid AS IDRecibo, recibos.rectalonario AS Tal, recibos.recnro AS RNro, recibos.recobservacion AS Observacion, recibos.recdiferencia AS Diferencia, facturas.factnro AS FNro, facturas.factfecha AS FFecha, facturas.factbruto AS Bruto, facturas.factdesc AS Dto, facturas.factneto AS Neto, facturas.factefectivo AS Efectivo, facturas.facttransfer AS Transf, facturas.factretencion AS Retencion, cheques.cheqid AS IDCheque, cheques.cheqbanco AS Banco, cheques.cheqnumero AS Numero, cheques.cheqfecha AS Fecha, cheques.cheqimporte AS Importe
FROM rendicion
INNER JOIN rend_rec ON rendicion.rendid = rend_rec.rendid
INNER JOIN recibos ON rend_rec.recid = recibos.recid
LEFT JOIN rec_fact ON recibos.recid = rec_fact.recid
LEFT JOIN facturas ON rec_fact.factid = facturas.factid
LEFT JOIN fact_cheq ON facturas.factid = fact_cheq.factid
LEFT JOIN cheques ON fact_cheq.cheqid = cheques.cheqid
LEFT JOIN cuenta ON facturas.factidcliente = cuenta.ctaidcuenta
WHERE ($_condicionUsr) AND ($_condicionRend) AND ($_condicionActivos) AND (cuenta.ctaidempresa = 1 OR cuenta.ctaidempresa IS NULL)
ORDER BY recibos.recid, cuenta.ctaidcuenta, facturas.factnro, cheques.cheqid ASC
";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//******************//
// DELETE Rendicion //
//******************//
public static function deleteRendicion($_ID) {
$_condicionRend = "rendid = ".$_ID;
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
$_rows = 0;
try {
$_theSQL = sprintf(" DELETE FROM rendicion
WHERE %s", $_condicionRend);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_rows;
}
//**************************************//
// DELETE Recibo Rendicion Sin Factura
//**************************************//
public static function deleteReciboSinFantura($_ID) {
$_condicionRec = "recibos.recid = ".$_ID;
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
$_rows = 0;
try {
$_theSQL = sprintf(" DELETE rend_rec, recibos
FROM rend_rec
JOIN recibos ON recibos.recid = rend_rec.recid
WHERE %s", $_condicionRec);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_rows;
}
//***********************************************************//
// DELETE Recibo Rendicion Sin Cheques
//***********************************************************//
public static function deleteReciboSinCheque($_ID){
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
$_rows = 0;
try {
$_theSQL = sprintf(" DELETE rec_fact, facturas
FROM rec_fact
JOIN facturas ON facturas.factid = rec_fact.factid
WHERE rec_fact.recid=%s", $_ID);
$hDB->select($_theSQL);
$_theSQL = sprintf("DELETE FROM rend_rec WHERE recid = %s", $_ID);
$hDB->select($_theSQL);
$_theSQL = sprintf("DELETE FROM recibos WHERE recid = %s", $_ID);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_rows;
}
public static function deleteChequesFactura($factID) {
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
$_rows = 0;
try {
$_theSQL = sprintf(" DELETE fact_cheq, cheques
FROM fact_cheq
LEFT OUTER JOIN cheques ON fact_cheq.cheqid = cheques.cheqid
WHERE fact_cheq.factid=%s", $factID);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_rows;
}
public static function getFacturasRecibo($_ID){
$hDB = DataManager::_getConnection();
$_theSQL = sprintf("SELECT factid FROM rec_fact WHERE recid = %s", $_ID);
try {
$data = $hDB->getAll($_theSQL);
} catch (Exception $e) {
die("error ejecutando $_theSQL");
}
return $data;
}
//********************
// Consulta NRO MAX de RENDICIÓN del Usuario
//********************
public static function getMaxRendicion($_ID = NULL) {
$hDB = DataManager::_getConnection();
$_condicionUsr = ($_ID) ? "rendidusr=".$_ID: "true";
$sql = "SELECT MAX(rendnumero) AS maximo FROM rendicion WHERE ($_condicionUsr)";
try {
$_numero = $hDB->getOne($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $_numero;
}
//********************
// Consulta RECIBOS según el talonario
//********************
public static function getRecibos($_nroTal, $_nroRec = NULL) {
$hDB = DataManager::_getConnection();
$_condicionTal = "rectalonario=".$_nroTal;
$_condicionRec = ($_nroRec) ? "recnro=".$_nroRec : "true";
$sql = "SELECT * FROM recibos WHERE ($_condicionTal) AND ($_condicionRec)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql");
}
return $data;
}
//********************
// Consulta NRO MAX de RECIBOS utilizados según el talonario
//********************
public static function getMaxRecibo($_nroTal) {
$hDB = DataManager::_getConnection();
$_condicionTal = "rectalonario=".$_nroTal;
$sql = "SELECT MAX(recnro) AS maximo FROM recibos WHERE ($_condicionTal)";
try {
$_numero = $hDB->getOne($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $_numero;
}
//********************
// Consulta NRO MIN de RECIBOS utilizados según el talonario
//********************
public static function getMinRecibo($_nroTal) {
$hDB = DataManager::_getConnection();
$_condicionTal = "rectalonario=".$_nroTal;
$sql = "SELECT MIN(recnro) AS minimo FROM recibos WHERE ($_condicionTal)";
try {
$_numero = $hDB->getOne($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $_numero;
}
//********************
// Consulta talonarios Incompletos
//********************
public static function getTalonariosIncompletos() {
$hDB = DataManager::_getConnection();
$sql = "
SELECT `recibos`.`rectalonario`, `recibos`.`recnro`, `usuarios`.`unombre`
FROM recibos
LEFT JOIN `talonario_idusr` ON `talonario_idusr`.`nrotalonario` = `recibos`.`rectalonario`
LEFT JOIN `usuarios` ON `usuarios`.`uid` = `talonario_idusr`.`idusr`
WHERE `usuarios`.`uactivo`= 1
GROUP BY rectalonario
HAVING (
COUNT( recnro ) <25
)
";
try {
$_numero = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $_numero;
}
//********************
// Consulta de Recibos ANULADOS de talonarios PENDIENTES
//********************
public static function getRecibosAnuladosPendientes() {
$hDB = DataManager::_getConnection();
$sql = "
SELECT `recibos`.`rectalonario`, `recibos`.`recnro`, `usuarios`.`unombre`
FROM recibos
LEFT JOIN `talonario_idusr` ON `talonario_idusr`.`nrotalonario` = `recibos`.`rectalonario`
LEFT JOIN `usuarios` ON `usuarios`.`uid` = `talonario_idusr`.`idusr`
WHERE `usuarios`.`uactivo`= 1
GROUP BY rectalonario, recobservacion, recnro
HAVING (
COUNT( recnro ) <25
)
AND (
recobservacion LIKE 'ANULADO'
)
ORDER BY `recibos`.`rectalonario` ASC
";
try {
$_numero = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $_numero;
}
//********************
// Saber si hay Recibos
//********************
public static function getContarRecibos($_recid) {
$hDB = DataManager::_getConnection();
$_condicionRecibo = "rendid = ".$_recid;
$sql = "SELECT COUNT(*) FROM rend_rec
WHERE ($_condicionRecibo)
";
try {
$_numero = $hDB->getOne($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $_numero;
}
//********************
// Saber si hay FACTURAS
//********************
public static function getContarFacturas($_recid) {
$hDB = DataManager::_getConnection();
$_condicionRecibo = "recid = ".$_recid;
$sql = "SELECT COUNT(*) FROM rec_fact
WHERE ($_condicionRecibo)
";
try {
$_numero = $hDB->getOne($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $_numero;
}
//********************
// Saber si hay CHEQUES
//********************
public static function getContarCheques($_recid) {
$hDB = DataManager::_getConnection();
$_condicionRecibo = "rec_fact.recid = ".$_recid;
$sql = "SELECT COUNT(*) FROM rec_fact
INNER JOIN fact_cheq ON rec_fact.factid = fact_cheq.factid
WHERE ($_condicionRecibo)
";
try {
$_numero = $hDB->getOne($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $_numero;
}
//********************
// Selecciona BANCOS
//********************
public static function getBancos() {
$hDB = DataManager::_getConnection();
$sql = "SELECT * FROM banco ORDER BY nombre ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//**************************
// BUSCAR NRO DE TALONARIO
//**************************
public static function getBuscarTalonario($_nroTal) {
$hDB = DataManager::_getConnection();
$_condicionTalon = "nrotalonario=$_nroTal";
$sql = "SELECT * FROM talonario_idusr WHERE ($_condicionTalon)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//************************//
// DETALLE BONIFICACION
//************************//
public static function getDetalleBonificacion($_mes, $_anio) {
$hDB = DataManager::_getConnection();
$_condicionMes = ($_mes) ? "bonifmes=".$_mes : "bonifmes=".date("d");
$_condicionAnio = ($_anio) ? "bonifanio=".$_anio : "bonifanio=".date("Y");
$sql = "SELECT * FROM bonificacion WHERE ($_condicionMes) AND ($_condicionAnio) ORDER BY bonifartid ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//************************//
// DETALLE BONIFICACIONES
//************************//
public static function getDetalleBonificaciones($_activa=NULL) {
$_condicionActiva = ($_activa) ? "bonifactiva=".$_activa : "TRUE";
$hDB = DataManager::_getConnection();
$sql = "SELECT * FROM bonificacion WHERE ($_condicionActiva) ORDER BY bonifid ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//************************//
// BONIFICACION de Artículo
//************************//
public static function getBonificacionArticulo($_ID = NULL, $_mes = NULL, $_anio = NULL) {
$hDB = DataManager::_getConnection();
$_condicionArt = ($_ID) ? "bonifartid =".$_ID : true;
$_condicionMes = ($_mes) ? "bonifmes =".$_mes : true;
$_condicionAnio = ($_anio)? "bonifanio =".$_anio : true;
$sql = "SELECT * FROM bonificacion WHERE ($_condicionArt) AND ($_condicionMes) AND ($_condicionAnio)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//************************//
// DETALLE ABM //
//************************//
public static function getDetalleAbm($_mes, $_anio, $_drogid, $_tipo = NULL) {
$hDB = DataManager::_getConnection();
$_condicionMes = ($_mes) ? "abmmes=".$_mes : "abmmes=".date("d");
$_condicionAnio = ($_anio) ? "abmanio=".$_anio : "abmanio=".date("Y");
$_condicionDrogueria = ($_drogid)? "abmdrogid=".$_drogid : 0;
$_condicionTipo = ($_tipo) ? "abmtipo='".$_tipo."'" : TRUE;
$sql = "SELECT * FROM abm WHERE ($_condicionMes) AND ($_condicionAnio) AND ($_condicionDrogueria) AND ($_condicionTipo) ORDER BY abmartid ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//****************************//
// DETALLE ABM por Artículo //
//****************************//
public static function getDetalleArticuloAbm($_mes, $_anio, $_drogid, $_artID, $_tipo = NULL) {
$hDB = DataManager::_getConnection();
$_condicionMes = ($_mes) ? "abmmes=".$_mes : "abmmes=".date("d");
$_condicionAnio = ($_anio) ? "abmanio=".$_anio : "abmanio=".date("Y");
$_condicionDrogueria = ($_drogid)? "abmdrogid=".$_drogid : FALSE;
$_condicionIDart = ($_artID) ? "abmartid=".$_artID : FALSE;
$_condicionTipo = ($_tipo) ? "abmtipo='".$_tipo."'" : TRUE;
$sql = "SELECT * FROM abm WHERE ($_condicionMes) AND ($_condicionAnio) AND ($_condicionDrogueria) AND ($_condicionIDart) AND ($_condicionTipo)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//*****************************//
// DETALLE ABM POR DROGUERÍA //
//*****************************//
public static function getDetalleAbmDrogueria($_drogid, $_activo) {
$hDB = DataManager::_getConnection();
$_condicionDrogueria = ($_drogid)? "abmdrogid=".$_drogid : 0;
$_condicionActivo = ($_activo)? "abmactivo=".$_activo : TRUE;
$sql = "SELECT * FROM abm WHERE ($_condicionDrogueria) AND ($_condicionActivo)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//**********************//
// LISTADO Tabla ABM //
//**********************//
public static function getAbms($mostrarTodos = NULL, $desde = NULL, $hasta = NULL, $drogid = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){
$_condicionActivos = "TRUE";
} else {$_condicionActivos = "abmactivo=".$mostrarTodos;}
if (empty($drogid) || is_null($drogid)){ $_condicionDrogueria = "TRUE";
} else {$_condicionDrogueria = "abmdrogid=".$drogid;}
$fechaInicio = new DateTime($desde);
$_condicionDate = "abmmes = '".$fechaInicio->format("m")."' AND abmanio = '".$fechaInicio->format("Y")."'";
$sql = "SELECT * FROM abm WHERE ($_condicionDate) AND ($_condicionDrogueria) AND ($_condicionActivos) ORDER BY abmid DESC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//************************//
// DETALLE LIQUIDACION //
//************************//
public static function getDetalleLiquidacion($_mes=NULL, $_anio=NULL, $_drogid, $_tipo=NULL) {
$hDB = DataManager::_getConnection();
$_condicionMes = ($_mes) ? "MONTH(liqfecha) =".$_mes : "TRUE"; //"MONTH(liqfecha) =".date("d");
$_condicionAnio = ($_anio) ? "YEAR(liqfecha) =".$_anio : "TRUE"; // "YEAR(liqfecha) =".date("Y");
$_condicionDrogueria = ($_drogid)? "liqdrogid=".$_drogid : 0;
$_condicionTipo = ($_tipo) ? "liqtipo='".$_tipo."'" : TRUE;
$sql = "SELECT * FROM liquidacion WHERE ($_condicionMes) AND ($_condicionAnio) AND ($_condicionDrogueria) AND ($_condicionTipo) ORDER BY liqnrotransfer, liqid ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//************************//
// DETALLE LIQUIDACIONES //
//************************//
public static function getDetalleLiquidaciones($mostrarTodos=NULL, $desde=NULL, $hasta=NULL, $drogid, $tipo=NULL) {
$hDB = DataManager::_getConnection();
$_condicionDate = "liqfecha BETWEEN '".$desde."' AND '".$hasta."'";
$_condicionDrogueria = ($drogid)? "liqdrogid=".$drogid : 0;
$_condicionTipo = ($tipo) ? "liqtipo='".$tipo."'" : TRUE;
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "liqactiva=".$mostrarTodos;}
$sql = "SELECT * FROM liquidacion WHERE ($_condicionDate) AND ($_condicionDrogueria) AND ($_condicionTipo) AND ($_condicionActivos) ORDER BY liqnrotransfer, liqid ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//************************************//
// Detalle Liquidacion por TRANSFER //
//***********************************//
public static function getDetalleLiquidacionTransfer($_ID, $_drogid, $_nroTransfer, $_ean) {
$hDB = DataManager::_getConnection();
$_condicionID = ($_ID) ? "liqid <> ".$_ID : TRUE;
//$_condicionFecha = ($_fecha) ? "liqfecha <> '".$_fecha."'" : "liqfecha < ".date("Y-m-d");
$_condicionDrogueria = ($_drogid) ? "liqdrogid=".$_drogid : TRUE;
$_condicionTransfer = ($_nroTransfer) ? "liqnrotransfer=".$_nroTransfer : FALSE;
$_condicionEan = ($_ean) ? "liqean=".$_ean : TRUE;
$sql = "SELECT * FROM liquidacion WHERE ($_condicionID) AND ($_condicionDrogueria) AND ($_condicionTransfer) AND ($_condicionEan) ORDER BY liqnrotransfer, liqid ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// LISTADO TRANSFER
//********************
public static function getTransfersLiquidados($mostrarTodos = NULL, $_estado = NULL, $_drogueria = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "ptactivo=".$mostrarTodos;}
if ((empty($_estado) && $_estado != 0) || is_null($_estado)){ $_condicionEstado = "TRUE";
} else {$_condicionEstado = "ptliquidado='".$_estado."'";}
//La consulta muestra el listado de pedidos dentro de todos los ID droguería que tenga en mismo correo de TRANSFER
if ((empty($_drogueria) && $_drogueria != 0) || is_null($_drogueria)){ $_condicionDrogueria = "TRUE";
} else {$_condicionDrogueria = "ptiddrogueria IN (SELECT drogtcliid FROM droguerias WHERE drogtcorreotransfer IN (SELECT drogtcorreotransfer FROM droguerias WHERE drogtcliid = ".$_drogueria."))";}
$sql = "SELECT DISTINCT ptidpedido, ptclirs, ptfechapedido FROM pedidos_transfer WHERE ($_condicionActivos) AND ($_condicionEstado) AND ($_condicionDrogueria) ORDER BY ptidpedido DESC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//***********************
// DELETE LIQUIDACIONES
//***********************
public static function deleteFromLiquidacion($_ID, $_fecha, $_tipo) {
$_tabla = "liquidacion";
$_condicionDrog = "liqdrogid=".$_ID;
$_condicionFecha = "liqfecha='".$_fecha."'";
$_condicionTipo = "liqtipo='".$_tipo."'";
$hDB = DataManager::_getConnection();
$hDB->startTransaction();
$_rows = 0;
try {
$_theSQL = sprintf("DELETE FROM %s WHERE (%s) AND (%s) AND (%s)", $_tabla, $_condicionDrog, $_condicionFecha, $_condicionTipo);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_rows;
}
//******************************//
// LISTADO CONDICIONES ESPECIAL //
//******************************//
public static function getCondicionesEspeciales($empresa = NULL, $laboratorio = NULL, $mostrarTodos = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "condidemp=".$empresa;}
if ((empty($laboratorio) && $laboratorio != 0) || is_null($laboratorio)){ $_condicionLaboratorio = "TRUE";
} else {$_condicionLaboratorio = "condidlab=".$laboratorio;}
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "condactiva=".$mostrarTodos;}
$sql = "SELECT * FROM condicion_especial WHERE ($_condicionEmpresa) AND ($_condicionLaboratorio) AND ($_condicionActivos) ORDER BY condidemp, condidlab, condidcliente ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//**********************//
// LISTADO DE CONTACTOS //
//**********************//
public static function getContactosPorCuenta( $_ID = NULL, $_origen = NULL, $mostrarTodos) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "ctoactivo=".$mostrarTodos;}
$_condicionID = "ctoorigenid=".$_ID;
$_condicionOrigen = "ctoorigen='".$_origen."'";
if (!empty($_ID) && !empty($_origen)) {
$sql = "SELECT * FROM contacto WHERE ($_condicionActivos) AND ($_condicionID) AND ($_condicionOrigen) ORDER BY ctoapellido ASC, ctonombre ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
}
//********************
// Tabla SECTOR
//********************
public static function getSectores($mostrarTodos = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "sectactivo=".$mostrarTodos;}
$sql = "SELECT * FROM sector WHERE ($_condicionActivos) ORDER BY sectnombre ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//********************
// Tabla PUESTO
//********************
public static function getPuestos($mostrarTodos = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "ptoactivo=".$mostrarTodos;}
$sql = "SELECT * FROM puesto WHERE ($_condicionActivos) ORDER BY ptonombre ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//**********************//
// Tabla RELEVAMIENTOS //
//**********************//
public static function getRelevamientos( $_pag=0, $_rows=20, $mostrarTodos = TRUE) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "relactivo=".$mostrarTodos;}
$sql = "SELECT * FROM relevamiento WHERE ($_condicionActivos) ORDER BY relidrel DESC, relpregorden ASC, relactivo DESC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getRelevamiento( $_nroRel = NULL, $mostrarTodos = TRUE) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "relactivo=".$mostrarTodos;}
if (empty($_nroRel) || is_null($_nroRel)){ $_condicionRelev = "FALSE";
} else {$_condicionRelev = "relidrel=".$_nroRel;}
$sql = "SELECT * FROM relevamiento WHERE ($_condicionActivos) AND ($_condicionRelev) ORDER BY relpregorden ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//**********************//
// Tabla RESPUESTAS //
//**********************//
public static function getRespuesta( $_ID = NULL, $_origen = NULL, $_IDRelevamiento = NULL, $mostrarTodos = NULL) {
$hDB = DataManager::_getConnection();
$_condicionID = "resorigenid=".$_ID;
$_condicionOrigen = "resorigen='".$_origen."'";
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "resactiva=".$mostrarTodos;}
if (empty($_IDRelevamiento) || is_null($_IDRelevamiento)){ $_condicionIdRelev = "TRUE";
} else {$_condicionIdRelev = "resrelid=".$_IDRelevamiento;}
$sql = "SELECT * FROM respuesta WHERE ($_condicionID) AND ($_condicionOrigen) AND ($_condicionIdRelev) AND ($_condicionActivos)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//******************//
// Tabla LLAMADAS //
//******************//
public static function getLlamadas( $_pag=NULL, $_rows=NULL, $_IDorigen = NULL, $_origen = NULL, $mostrarTodos = NULL, $desde = NULL, $hasta = NULL) {
$hDB = DataManager::_getConnection();
$_condicionOrigen = "llamorigen='".$_origen."'";
if (!$_IDorigen){ $_condicionID = "TRUE";
} else {$_condicionID = "llamorigenid=".$_IDorigen;}
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "llamactiva=".$mostrarTodos;}
if (empty($desde) || is_null($desde) || empty($hasta) || is_null($hasta)){ $_condicionFecha = "TRUE";
} else { $_condicionFecha = "llamlastupdate BETWEEN '".$desde."' AND '".$hasta."'";}
$sql = "SELECT * FROM llamada WHERE ($_condicionID) AND ($_condicionOrigen) AND ($_condicionActivos) AND ($_condicionFecha) ORDER BY llamid DESC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//----------------------------------//
// Tabla CONDICIONES COMERCIALES //
public static function getCondiciones( $_pag=0, $_rows=0, $mostrarTodos=NULL, $empresa=NULL, $laboratorio=NULL, $fecha=NULL, $tipo=NULL, $fechaDesde=NULL, $fechaHasta=NULL, $id=NULL, $lista=NULL) {
$hDB = DataManager::_getConnection();
if ((empty($id) && $id != '0') || is_null($id)){ $_condicionId = "TRUE";
} else {$_condicionId = "condid=".$id;}
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "condactiva=".$mostrarTodos;}
if (empty($empresa) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "condidemp=".$empresa;}
if (empty($laboratorio) || is_null($laboratorio)){ $_condicionLaboratorio = "TRUE";
} else {$_condicionLaboratorio = "condidlab=".$laboratorio;}
if (empty($fecha) || is_null($fecha)){ $_condicionFecha = "TRUE";
} else {$_condicionFecha = "'".$fecha."' BETWEEN condfechainicio AND condfechafin";}
if (empty($fechaDesde) || is_null($fechaDesde)){ $_condicionDesde = "TRUE";
} else {$_condicionDesde = "condfechainicio >= '".$fechaDesde."'";}
if (empty($fechaHasta) || is_null($fechaHasta)){ $_condicionHasta = "TRUE";
} else {$_condicionHasta = "condfechafin >= '".$fechaHasta."'";}
if (empty($tipo) || is_null($tipo)){ $_condicionTipo = "TRUE";
} else {$_condicionTipo = "condtipo=".$tipo;}
if ((empty($lista) && $lista != '0') || is_null($lista)){ $_condicionLista = "TRUE";
} else {$_condicionLista = "condlista=".$lista;}
$sql = "SELECT * FROM condicion WHERE ($_condicionId) AND ($_condicionEmpresa) AND ($_condicionActivos) AND ($_condicionLaboratorio) AND ($_condicionFecha) AND ($_condicionTipo) AND ($_condicionDesde) AND ($_condicionHasta) AND ($_condicionLista) ORDER BY condfechafin DESC, condactiva DESC, condtipo ASC, condnombre ASC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//---------------------------------------//
// Artículos de CONDICION COMERCIAL //
public static function getCondicionArticulos($idCond = NULL, $order = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($idCond) && $idCond != '0') || is_null($idCond)){ $_condicionId = "TRUE";
} else {$_condicionId = "cartidcond=".$idCond; }
if ((empty($order) && $order <= 0) || is_null($idCond)){ $_condicionOrder = "TRUE";
} else {
switch($order){
case 1: $_condicionOrder = "cartoferta DESC";
break;
default: $_condicionOrder = "TRUE";
break;
}
}
$sql = "SELECT * FROM condicion_art WHERE ($_condicionId) ORDER BY $_condicionOrder, cartidart ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//****************************************//
// Bonificaciones de CONDICION COMERCIAL //
//****************************************//
public static function getCondicionBonificaciones($idCond = NULL, $idArt = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($idCond) && $idCond != '0') || is_null($idCond)){ $_condicionId = "TRUE";
} else {$_condicionId = "cbidcond=".$idCond; }
if (empty($idArt) || is_null($idArt)){ $_condicionArt = "TRUE"; //"FALSE"
} else {$_condicionArt = "cbidart=".$idArt;}
$sql = "SELECT * FROM condicion_bonif WHERE ($_condicionId) AND ($_condicionArt) ORDER BY cbcant, cbidart ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//******************************//
// SELECT Eventos de AGENDA //
//******************************//
public static function getEventos($idUsr) { //, $start, $end
if ((empty($idUsr) && $idUsr != 0) || is_null($idUsr)){ $condicionUsr = "NULL";
} else { $condicionUsr = "agidusr=".$idUsr;}
$dtInicio = new DateTime("now");
$dtInicio->modify("-6 month");
$dtFin = new DateTime("now");
$dtFin->modify("+6 month");
$hDB = DataManager::_getConnection();
$sql = "SELECT * FROM agenda WHERE ($condicionUsr) AND agstartdate BETWEEN '".$dtInicio->format("Y-m-d")."' AND '".$dtFin->format("Y-m-d")."'";
// agstartdate BETWEEN '".$start."' AND '".$end."'"; //agstartdate BETWEEN '".$start."' AND '".$end."'"
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//----------------
// Tabla CUENTAS
public static function getCuentas( $_pag = 0, $_rows = 0, $empresa = NULL, $mostrarTodos = NULL, $tipo = NULL, $zonas = NULL, $sort = 1, $estado = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "ctaactiva=".$mostrarTodos;}
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "ctaidempresa=".$empresa;}
if (empty($tipo) || is_null($tipo)){ $_condicionTipo = "TRUE";
} else {$_condicionTipo = "ctatipo IN (".$tipo.")";}
if ((empty($zonas) && $zonas != '0') || is_null($zonas)){ $_condicionZonas = "ctazona LIKE ''"; //Devuelve vacío ya que no existen cuentas sin zona
} else {$_condicionZonas = "ctazona IN (".$zonas.")";}
if (empty($estado) || is_null($estado)){ $_condicionEstado = "TRUE";
} else {$_condicionEstado = "ctaestado='$estado'";}
switch ($sort){
case 1:
$condicionOrder = "ctaactiva DESC, ctaidprov ASC, ctaidloc ASC";
break;
case 2:
$condicionOrder = "ctaactiva DESC, ctanombre ASC";
break;
case 3:
$condicionOrder = "ctaupdate DESC";
break;
default:
$condicionOrder = "ctaactiva DESC";
break;
}
$sql = "SELECT * FROM cuenta WHERE ($_condicionActivos) AND ($_condicionEmpresa) AND ($_condicionTipo) AND ($_condicionZonas) AND ($_condicionEstado) ORDER BY $condicionOrder";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//------------------------------------------//
// Select 1 campo de cuentas pasando el uid //
//------------------------------------------//
public static function getCuenta($_field=NULL, $_field2=NULL, $_ID, $empresa=NULL) {
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "ctaidempresa=".$empresa;}
if ($_ID) {
$sql = "SELECT $_field FROM cuenta WHERE ($_field2='$_ID') AND ($_condicionEmpresa) LIMIT 1";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//---------------------------------------------
// Select 1 campo de cuentas pasando el uid
public static function getCuentaAll($_field=NULL, $_field2=NULL, $_ID, $empresa=NULL, $zonas=NULL) {
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "ctaidempresa=".$empresa;}
if ((empty($zonas) && $zonas != '0') || is_null($zonas)){
$_condicionZonas = "TRUE"; //OJO! Al pasar TRUE devuelve cualquier zona, ésto es IMPORTANTE al controlar existencia de CUIT EN ALTA DE CUENTAS. En FALSE devuelve todas las posibles ZONAS, tener cuidado si un usuario no tiene zonas registradas al mostrar los datos.
} else {
$_condicionZonas = "ctazona IN (".$zonas.")";
}
if ($_ID) {
$sql = "SELECT $_field FROM cuenta WHERE ($_field2 LIKE '$_ID') AND ($_condicionEmpresa) AND ($_condicionZonas)";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//**************************//
// Tabla Tipos de cuentas //
//**************************//
public static function getTiposCuenta($mostrarTodos) {
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "ctaactiva=".$mostrarTodos;}
$hDB = DataManager::_getConnection();
$sql = "SELECT * FROM cuenta_tipo WHERE ($_condicionActivos) ORDER BY ctatipo ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function dac_consultarNumerosCuenta($empresa=NULL, $zona) {
$hDB = DataManager::_getConnection();
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "ctaidempresa=".$empresa;}
$_digitosZona = strlen($zona)+4;
$_condicionZona = "'".$zona."%1'";
$sql = "SELECT ctaidcuenta
FROM cuenta
WHERE ctaidcuenta LIKE $_condicionZona
AND LENGTH(ctaidcuenta) = $_digitosZona
AND ($_condicionEmpresa)
ORDER BY ctaidcuenta ASC;";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
//---------------------------
// Tabla CUENTAS RELACIONADAS
//---------------------------
public static function getCuentasRelacionadas($idCta) { //$empresa, $idCuenta
$hDB = DataManager::_getConnection();
$_condicionCuenta = ($idCta) ? "ctarelctaid=".$idCta : FALSE;//"ctarelidcuenta=".$idCuenta;
$sql = "SELECT * FROM cuenta_relacionada WHERE ($_condicionCuenta) ORDER BY ctarelidcuentadrog ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//-------------------------------
// Tabla CATEGORÍAS COMERCIALES
public static function getCategoriasComerciales($mostrarTodos = TRUE) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "catactiva=".$mostrarTodos;}
$sql = "SELECT * FROM categoriacomercial WHERE ($_condicionActivos) ORDER BY catactiva DESC, catidcat ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getCategoriaComercial($_field=NULL, $_field2=NULL, $_ID) {
if ((empty($_ID) && $_ID != '0') || is_null($_ID)){ $_condicionID = "";
} else {$_condicionID = "$_field2='".$_ID."'";}
if ($_condicionID) {
$sql = "SELECT $_field FROM categoriacomercial WHERE ($_condicionID) LIMIT 1";
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//********************
// Tabla CATEGORÍAS IVA
//********************
public static function getCategoriasIva($mostrarTodos = TRUE) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "catactiva=".$mostrarTodos;}
$sql = "SELECT * FROM categoriaIVA WHERE ($_condicionActivos) ORDER BY catactiva DESC, catnombre ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//--------------------
// Tabla CADENAS
//-------------------
public static function getCadenas($empresa=NULL, $idCadena=NULL) {
$hDB = DataManager::_getConnection();
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "IdEmpresa=".$empresa;}
if ((empty($idCadena) && $idCadena != 0) || is_null($idCadena)){ $_condicionCadena = "TRUE";
} else {$_condicionCadena = "IdCadena=".$idCadena;}
$sql = "SELECT * FROM cadenas WHERE ($_condicionEmpresa) AND ($_condicionCadena) ORDER BY NombreCadena ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//-------------------------
// Select CUENTAS CADENAS
//-------------------------
public static function getCuentasCadena($empresa=NULL, $cadena=NULL, $cuenta=NULL) {
$hDB = DataManager::_getConnection();
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmpresa = "TRUE";
} else {$_condicionEmpresa = "IdEmpresa=".$empresa;}
if ((empty($cadena) && $cadena != 0) || is_null($cadena)){ $_condicionCadena = "TRUE";
} else {$_condicionCadena = "IdCadena=".$cadena;}
if ((empty($cuenta) && $cuenta != 0) || is_null($cuenta)){ $_condicionCuenta = "TRUE";
} else {$_condicionCuenta = "IdCliente=".$cuenta;}
$sql = "SELECT * FROM cnCadenasClientes WHERE ($_condicionEmpresa) AND ($_condicionCadena) AND ($_condicionCuenta) ORDER BY IdCadena ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//--------------------
// Tabla PROPUESTAS
public static function getPropuestas($idCuenta=NULL, $mostrarTodos=NULL, $idUsr=NULL, $dateFrom=NULL, $dateTo=NULL) {
$hDB = DataManager::_getConnection();
if (empty($idCuenta) || is_null($idCuenta)){ $_condicionCuenta = "TRUE";
} else {$_condicionCuenta = "propidcuenta=".$idCuenta;}
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "propactiva=".$mostrarTodos;}
if (empty($idUsr) || is_null($idUsr)){ $_condicionUsr = "TRUE";
} else { $_condicionUsr = "propusr=".$idUsr;}
if (empty($dateFrom) || is_null($dateFrom)){ $_conditionFrom = "TRUE";
} else {$_conditionFrom = "propfecha >= '".$dateFrom."'";}
if (empty($dateTo) || is_null($dateTo)){ $_conditionTo = "TRUE";
} else {$_conditionTo = "propfecha <= '".$dateTo."'";}
$sql = "SELECT * FROM propuesta WHERE ($_condicionCuenta) AND ($_condicionActivos) AND ($_condicionUsr) AND ($_conditionFrom) AND ($_conditionTo) ORDER BY propfecha DESC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getPropuesta($idPropuesta=NULL) {
$hDB = DataManager::_getConnection();
if (empty($idPropuesta) || is_null($idPropuesta)){ $_condicionID = NULL;
} else {$_condicionID = "propid=".$idPropuesta;}
$sql = "SELECT * FROM propuesta WHERE ($_condicionID)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getPropuestaDetalle($idPropuesta=NULL, $mostrarTodos = NULL) {
$hDB = DataManager::_getConnection();
if (empty($idPropuesta) || is_null($idPropuesta)){ $_condicionID = NULL;
} else {$_condicionID = "pdpropid=".$idPropuesta;}
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "pdactivo=".$mostrarTodos;}
$sql = "SELECT * FROM propuesta_detalle WHERE ($_condicionID) AND ($_condicionActivos) ORDER BY pdidart ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getEstado($_field=NULL, $_field2=NULL, $_ID) {
if ((empty($_ID) && $_ID != '0') || is_null($_ID)){ $_condicionID = "";
} else {$_condicionID = "$_field2='".$_ID."'";}
if ($_condicionID) {
$sql = "SELECT $_field FROM estados WHERE ($_condicionID) LIMIT 1"; //($_field2='$_ID')
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
public static function getTicket($_pag = 0, $_rows = 0, $_ID = NULL, $usrCreate = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($_ID) && $_ID != '0') || is_null($_ID)){ $_condicionID = TRUE;
} else {$_condicionID = "tkid=".$_ID;}
if ((empty($usrCreate) && $usrCreate != '0') || is_null($usrCreate)){ $_condicionUsrId = TRUE;
} else {$_condicionUsrId = "tkusrcreated=".$usrCreate;}
$sql = "SELECT * FROM ticket WHERE ($_condicionID) AND ($_condicionUsrId) ORDER BY tkid DESC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getTicketSector() {
$hDB = DataManager::_getConnection();
$sql = "SELECT * FROM ticket_sector";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getTicketMotivos($_IdSector = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($_IdSector) && $_IdSector != '0') || is_null($_IdSector)){ $_condicionSector = TRUE;
} else {$_condicionSector = "tkmotidsector=".$_IdSector;}
$sql = "SELECT * FROM ticket_motivo WHERE ($_condicionSector)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getTicketMensajes($idTicket = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($idTicket) && $idTicket != '0') || is_null($idTicket)){ $_condicionTicket = "FALSE";
} else {$_condicionTicket = "tkmsgidticket=".$idTicket;}
$sql = "SELECT * FROM ticket_mensaje WHERE ($_condicionTicket)";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//--------------------------
// Tabla LISTAS de Precios
public static function getListas( $mostrarTodos = NULL, $id = NULL) {
$hDB = DataManager::_getConnection();
if ((empty($mostrarTodos) && $mostrarTodos != '0') || is_null($mostrarTodos)){ $_condicionActivos = "TRUE";
} else {$_condicionActivos = "Activa=".$mostrarTodos; }
if ((empty($id) && $id != 0) || is_null($id)){ $_condicionLista = "TRUE";
} else {$_condicionLista = "IdLista=".$id;}
$sql = "SELECT * FROM listas WHERE ($_condicionLista) AND ($_condicionActivos) ORDER BY IdLista ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
public static function getLista($_field=NULL, $_field2=NULL, $_ID) {
if ((empty($_ID) && $_ID != '0') || is_null($_ID)){ $_condicionID = "";
} else {$_condicionID = "$_field2='".$_ID."'";}
if ($_condicionID) {
$sql = "SELECT $_field FROM listas WHERE ($_condicionID) LIMIT 1"; //($_field2='$_ID')
$hDB = DataManager::_getConnection();
try {
$data = $hDB->getOne($sql);
} catch (Exception $e) {
die("Error en el SGBD : Q = $sql<br>");
}
return $data;
}
}
//--------------------------
// Tabla MOVIMIENTOS
public static function getMovimientos( $_pag = 0, $_rows = 0 ) {
$hDB = DataManager::_getConnection();
$sql = "SELECT * FROM movimiento ORDER BY movid DESC";
if (($_pag) && ($_rows)) {
$_from = ($_pag-1)*$_rows;
$_offset = " LIMIT $_rows OFFSET $_from";
$sql .= $_offset;
}
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
} ?><file_sep>/includes/class/class.imagen.php
<?php
require_once('class.PropertyObject.php');
//if (!defined('BASEPATH')) exit('No direct script access allowed');
class TImagen extends PropertyObject {
protected $_tablename = 'imagen';
protected $_fieldid = 'imgid';
protected $_timestamp = 0;
protected $_id = 0;
//private $table = 'imagenes';
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'imgid';
$this->propertyTable['Imagen'] = 'imgnombre';
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
/* function insert($data) {
if ($this->db->insert($this->table, $data))
return $this->db->insert_id();
return NULL;
}
function save($id, $data) {
$this->db->where('mrc_id', $id);
return $this->db->update($this->table, $data);
}*/
}
<file_sep>/articulos/logica/eliminar.articulo.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$artId = empty($_REQUEST['artid']) ? 0 : $_REQUEST['artid'];
$backURL = '/pedidos/articulos/';
if ($artId) {
//Delete Hiperwin
$artObjectHiper = DataManagerHiper::newObjectOfClass('THiperArticulo', $artId);
$artObjectHiper->__set('ID', $artId);
DataManagerHiper::deleteSimpleObject($artObjectHiper, $artId);
// Elimia artículo, dispone y fórmula
$artObject = DataManager::newObjectOfClass('TArticulo', $artId);
$artIdDispone = $artObject->__get('Dispone');
$artImagen = $artObject->__get('Imagen');
$artObject->__set('ID', $artId );
//Delete Web
DataManager::deleteSimpleObject($artObject);
//FALTA desarrollar ELIMINAR IMAGEN DEL ARTÍCULO
if($artImagen){
$rutaFile = "/pedidos/images/imagenes/";
$imagenObject = DataManager::newObjectOfClass('TImagen', $idImagen);
$imagenObject->__set('Imagen' , $imagenNombre);
$dir = $_SERVER['DOCUMENT_ROOT'].$rutaFile.$artImagen;
if (file_exists($dir)) { unlink($dir); }
}
//---------------
if($artIdDispone){
$dispObject = DataManager::newObjectOfClass('TArticuloDispone', $artIdDispone);
$dispObject->__set('ID', $artIdDispone);
DataManager::deleteSimpleObject($dispObject);
$formulas = DataManager::getArticuloFormula( $artId );
if (count($formulas)) {
foreach ($formulas as $k => $form) {
$fmId = $form["afid"];
$formObject = DataManager::newObjectOfClass('TArticuloFormula', $fmId);
$formObject->__set('ID', $fmId );
DataManager::deleteSimpleObject($formObject);
}
}
}
}
header('Location: '.$backURL);
?><file_sep>/transfer/gestion/abmtransfer/logica/jquery/jquery.processabm.js
$(document).ready(function() {
$("#guardar_abm").click(function () {
var idabm = "";
var selectArt = "";
var descuento = "";
var difcompens = "";
var plazo = "";
drogid = $('input[name="drogid_abm"]:text').val();
mes = $('input[name="mes_abm"]:text').val();
anio = $('input[name="anio_abm"]:text').val();
$('input[name="idabm[]"]:text').each(function() { idabm = idabm+"-"+$(this).val();});
$('input[name="art[]"]:text').each(function() { selectArt = selectArt+"-"+$(this).val();});
$('input[name="desc[]"]:text').each(function() { descuento = descuento+"-"+$(this).val();});
$('select[name="plazoid[]"]').each(function() { plazo = plazo+"-"+$(this).val();});
$('input[name="difcompens[]"]:text').each(function(){ difcompens = difcompens+"-"+$(this).val();});
if(selectArt == ""){ alert("Debe completar algun articulo para guardar los cambios.");
} else { dac_enviarDatosAbm(); }
function dac_enviarDatosAbm(){
$.ajax({
type: "POST",
url: "logica/update.abm.php",
data: { idabm : idabm,
mes : mes,
anio : anio,
drogid : drogid,
selectArt : selectArt,
descuento : descuento,
plazo : plazo,
difcompens : difcompens
},
success: function(result) {
if(result){
if(result == 1){ alert("Los cambios se han guardado"); window.location = "/pedidos/transfer/gestion/abmtransfer/index.php?fecha_abm="+mes+"-"+anio+"&drogid="+drogid;
}else{ alert(result);}
}
}
});
}
});
});<file_sep>/localidades/logica/update.zonasLocalidad.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo "LA SESION HA CADUCADO."; exit;
}
$zonasVProhibidas = [95, 99, 100, 199];
$radioZonas = (isset($_POST['radioZonas'])) ? $_POST['radioZonas'] : NULL;
switch($radioZonas){
case 'localidad':
$zonaVDestino = (isset($_POST['zonaVSelect'])) ? $_POST['zonaVSelect'] : NULL;
$zonaDDestino = (isset($_POST['zonaDSelect'])) ? $_POST['zonaDSelect'] : NULL;
if(empty($zonaVDestino) && empty($zonaDDestino)) {
echo "Seleccione una Zona de Venta o Distribución para actualizar las localidades seleccionadas."; exit;
}
//---------------
//Recorrer LOCALIDADES seleccionadas
$editSelected = (isset($_POST['editSelected2']))? $_POST['editSelected2'] : NULL;
if(empty($editSelected)) {
echo "Seleccione alguna localidad para momdificar."; exit;
}
$localidades = explode(",", $editSelected);
if(count($localidades)) {
for($k=0; $k<count($localidades); $k++){
$localObject = DataManager::newObjectOfClass('TLocalidad', $localidades[$k]);
$zonaVOriginal = $localObject->__get('ZonaVenta');
$zonaDOriginal = $localObject->__get('ZonaEntrega');
$movimiento = 'CAMBIO';
if($zonaVDestino){
//consultar usuario asignado para cuentas
$usrAssigned = 0;
$zonas = DataManager::getZonas();
foreach($zonas as $q => $zona){
$zZona = $zona['zzona'];
if($zZona == $zonaVDestino){
$usrAssigned = $zona['zusrassigned'];
}
}
$localObject->__set('ZonaVenta', $zonaVDestino);
$movimiento .= '_zonaV_'.$zonaVOriginal.'a'.$zonaVDestino;
}
if($zonaDDestino){
$localObject->__set('ZonaEntrega', $zonaDDestino);
$movimiento .= '_zonaD_'.$zonaDOriginal.'a'.$zonaDDestino;
}
if($movimiento != 'CAMBIO'){
//Actualzar Zona de Localidad
DataManagerHiper::updateSimpleObject($localObject, $localidades[$k]);
DataManager::updateSimpleObject($localObject);
//--------------//
// MOVIMIENTO //
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TLocalidad", $localidades[$k]);
}
//BUSCAR EXCEPCIONES
$zeCtaIdDDBB= [];
$zonasExpecion = DataManager::getZonasExcepcion($localidades[$k]);
if(count($zonasExpecion)) {
foreach ($zonasExpecion as $j => $ze) {
$zeCtaIdDDBB[] = $ze['zeCtaId'];
}
}
//Recorrer CUENTAS de c/Localidad
$cuentas = DataManager::getCuentaAll('*', 'ctaidloc', $localidades[$k]);
if (count($cuentas)) {
foreach ($cuentas as $q => $cuenta) {
$ctaId = $cuenta['ctaid'];
$ctaZona = $cuenta['ctazona'];
$ctaObjectHiper = DataManagerHiper::newObjectOfClass('THiperCuenta', $ctaId);
$ctaObject = DataManager::newObjectOfClass('TCuenta', $ctaId);
$ctaZonaVOriginal = $ctaObject->__get('Zona');
$ctaZonaDOriginal = $ctaObject->__get('ZonaEntrega');
$movimiento = 'CAMBIO';
//Si pasa con zona Y no es una zona prohibida Y no es una excepción
if(!empty($zonaVDestino) && !in_array($ctaZona, $zonasVProhibidas) && !in_array($ctaId, $zeCtaIdDDBB)) {
$ctaObject->__set('Zona', $zonaVDestino);
$ctaObject->__set('UsrAssigned', $usrAssigned);
$ctaObjectHiper->__set('Zona', $zonaVDestino);
$ctaObjectHiper->__set('UsrAssigned', $usrAssigned);
$movimiento .= '_zonaV_'.$ctaZonaVOriginal.'a'.$zonaVDestino;
}
if($zonaDDestino){
$ctaObject->__set('ZonaEntrega', $zonaDDestino);
$ctaObjectHiper->__set('ZonaEntrega', $zonaDDestino);
$movimiento .= '_zonaD_'.$ctaZonaDOriginal.'a'.$zonaDDestino;
}
//Si hay CAMBIOS, hacer UPDATE y MOVIMIENTO
if($movimiento != 'CAMBIO'){
DataManagerHiper::updateSimpleObject($ctaObjectHiper, $ctaId);
DataManager::updateSimpleObject($ctaObject);
// MOVIMIENTO //
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", $ctaId);
}
}
}
}
} else {
echo "Error al seleccionar localidad para momdificar."; exit;
}
break;
case 'provincia':
$zonaVDestino = (isset($_POST['zonaVSelect'])) ? $_POST['zonaVSelect'] : NULL;
$zonaDDestino = (isset($_POST['zonaDSelect'])) ? $_POST['zonaDSelect'] : NULL;
if(empty($zonaVDestino) && empty($zonaDDestino)) {
echo "Seleccione una Zona de Venta o Distribución para actualizar las localidades seleccionadas."; exit;
}
$provincia = (isset($_POST['provincia'])) ? $_POST['provincia'] : NULL;
if(empty($provincia)){
echo "Indique una provincia."; exit;
}
//BUSCAR EXCEPCIONES para NO realizar update
$zeCtaIdDDBB= [];
$localidades = DataManager::getLocalidades(NULL, $provincia);
if (count($localidades)) {
foreach ($localidades as $k => $loc) {
$idLoc = $loc['locidloc'];
$zonasExpecion = DataManager::getZonasExcepcion($idLoc);
if(count($zonasExpecion)){
foreach ($zonasExpecion as $j => $ze) {
$zeCtaIdDDBB[] = $ze['zeCtaId'];
}
}
}
}
$ctaZonasProhibidas = implode(",", $zonasVProhibidas);
$condicionExcepcion = "ctazona NOT IN (".$ctaZonasProhibidas.")";
$condicionExcepcionHiper = "IdVendedor NOT IN (".$ctaZonasProhibidas.")";
if (count($zeCtaIdDDBB)) {
$ctaIdExcepciones = implode(",", $zeCtaIdDDBB);
$condicionExcepcion .= " AND ctaid NOT IN (".$ctaIdExcepciones.")";
$condicionExcepcionHiper .= " AND ctaid NOT IN (".$ctaIdExcepciones.")";
}
//Realizo update en PROVINCIA Y en CUENTAS
if($zonaVDestino){
//update de zona venta de las localidades de la provincia
$fieldSet = "loczonavendedor=$zonaVDestino";
$condition= "locidprov=$provincia";
DataManagerHiper::updateToTable('localidad', $fieldSet, $condition);
DataManager::updateToTable('localidad', $fieldSet, $condition);
// MOVIMIENTO //
$movimiento = 'CAMBIOLocalidadesDeProvId_'.$provincia.'_a_zonaVendedor_'.$zonaVDestino;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TLocalidad", 0);
//consultar usuario asignado para cuentas
$usrAssigned = 0;
$zonas = DataManager::getZonas();
foreach($zonas as $k => $zona){
$zZona = $zona['zzona'];
if($zZona == $zonaVDestino){
$usrAssigned = $zona['zusrassigned'];
}
}
//update de zona venta de las cuentas de la provincia
$fieldSet = "IdVendedor=$zonaVDestino, ctausrassigned=$usrAssigned";
$condition= "IdProvincia=$provincia AND ($condicionExcepcionHiper)";
DataManagerHiper::updateToTable('clientes', $fieldSet, $condition);
$fieldSet = "ctazona=$zonaVDestino, ctausrassigned=$usrAssigned";
$condition= "ctaidprov=$provincia AND ($condicionExcepcion)";
DataManager::updateToTable('cuenta', $fieldSet, $condition);
// MOVIMIENTO //
$movimiento = 'CAMBIOLocalidadesDeProvId_'.$provincia.'_a_zonaVendedor_'.$zonaVDestino;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", 0);
}
if($zonaDDestino){
//update de zona entrega de las localidades de la provincia
$fieldSet = "loczonaentrega=$zonaDDestino";
$condition= "locidprov=$provincia";
DataManagerHiper::updateToTable('localidad', $fieldSet, $condition);
DataManager::updateToTable('localidad', $fieldSet, $condition);
// MOVIMIENTO //
$movimiento = 'CAMBIOLocalidadesDeProvId_'.$provincia.'_a_zonaEntrega_'.$zonaDDestino;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TLocalidad", 0);
//update de zona entrega de las cuentas de la provincia
$fieldSet = "Zona=$zonaVDestino"; //zona Entrega
$condition= "IdProvincia=$provincia";
DataManagerHiper::updateToTable('clientes', $fieldSet, $condition);
$fieldSet = "ctazonaentrega=$zonaVDestino";
$condition= "ctaidprov=$provincia";
DataManager::updateToTable('cuenta', $fieldSet, $condition);
// MOVIMIENTO //
$movimiento = 'CAMBIOLocalidadesDeProvId_'.$provincia.'_a_zonaEntrega_'.$zonaDDestino;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", 0);
}
break;
case 'vendedor':
$zonaVOrigen = (isset($_POST['zonaVOrigen'])) ? $_POST['zonaVOrigen'] : NULL;
$zonaVDestino = (isset($_POST['zonaVDestino'])) ? $_POST['zonaVDestino'] : NULL;
if(empty($zonaVOrigen)){ echo "Indique una zona de origen."; exit; }
if(empty($zonaVDestino)){ echo "Indique una zona de destino."; exit; }
//consultar usuario asignado para cuentas
$usrAssigned = 0;
$zonas = DataManager::getZonas();
foreach($zonas as $k => $zona){
$zZona = $zona['zzona'];
if($zZona == $zonaVDestino){
$usrAssigned = $zona['zusrassigned'];
}
}
//update de zona en LOCALIDADES
$fieldSet = "loczonavendedor=$zonaVDestino";
$condition= "loczonavendedor=$zonaVOrigen";
DataManagerHiper::updateToTable('localidad', $fieldSet, $condition);
DataManager::updateToTable('localidad', $fieldSet, $condition);
// MOVIMIENTO //
$movimiento = 'CAMBIO_ZonaVendedor_'.$zonaVOrigen.'_a_'.$zonaVDestino;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TLocalidad", 0);
//update de zona en CUENTAS
$fieldSet = "IdVendedor=$zonaVDestino, ctausrassigned=$usrAssigned";
$condition= "IdVendedor=$zonaVOrigen";
DataManagerHiper::updateToTable('clientes', $fieldSet, $condition);
$fieldSet = "ctazona=$zonaVDestino, ctausrassigned=$usrAssigned";
$condition= "ctazona=$zonaVOrigen";
DataManager::updateToTable('cuenta', $fieldSet, $condition);
// MOVIMIENTO //
$movimiento = 'CAMBIO_ZonaVendedor_de_'.$zonaVOrigen.'_a_'.$zonaVDestino;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", 0);
//update de zona y cuentas en EXCEPCIONES
$zonasExpecion = DataManager::getZonasExcepcion(NULL, $zonaVOrigen);
if(count($zonasExpecion) > 0){
foreach ($zonasExpecion as $j => $ze) {
$zeIdLocDDBB= $ze['zeIdLoc'];
$zeCtaIdDDBB= $ze['zeCtaId'];
//Redefinir ZONA en excepcion
$fieldSet = "zeZona=$zonaVDestino";
$condition= "zeCtaId=$zeCtaIdDDBB";
DataManager::updateToTable('zona_excepcion', $fieldSet, $condition);
// MOVIMIENTO //
$movimiento = 'CAMBIO_zonaV_'.$zonaVOrigen.'a'.$zonaVDestino.'_Cuenta_'.$zeCtaIdDDBB;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "zona_excepcion", $zeCtaIdDDBB);
//Redefinir ZONA en Cuenta excepcion
$ctaObjectHiper = DataManagerHiper::newObjectOfClass('THiperCuenta', $zeCtaIdDDBB);
$ctaObjectHiper->__set('Zona', $zonaVDestino);
$ctaObject = DataManager::newObjectOfClass('TCuenta', $zeCtaIdDDBB);
$ctaObject->__set('Zona', $zonaVDestino);
DataManagerHiper::updateSimpleObject($ctaObjectHiper, $zeCtaIdDDBB);
DataManager::updateSimpleObject($ctaObject);
// MOVIMIENTO //
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", $zeCtaIdDDBB);
}
}
break;
case 'distribucion':
$zonaDOrigen = (isset($_POST['zonaDOrigen'])) ? $_POST['zonaDOrigen'] : NULL;
$zonaDDestino = (isset($_POST['zonaDDestino'])) ? $_POST['zonaDDestino'] : NULL;
if(empty($zonaDOrigen)){ echo "Indique una zona de origen."; exit; }
if(empty($zonaDDestino)){ echo "Indique una zona de destino."; exit; }
//update de zona distribucion de localidades
$fieldSet = "loczonaentrega=$zonaDDestino";
$condition= "loczonaentrega=$zonaDOrigen";
DataManagerHiper::updateToTable('localidad', $fieldSet, $condition);
DataManager::updateToTable('localidad', $fieldSet, $condition);
// MOVIMIENTO //
$movimiento = 'CAMBIO_ZonaEntrega_'.$zonaDOrigen.'_a_'.$zonaDDestino;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TLocalidad", 0);
//update de zona entrega de las cuentas de la provincia
$fieldSet = "Zona=$zonaVDestino"; //zona Entrega
$condition= "Zona=$zonaDOrigen";
DataManagerHiper::updateToTable('clientes', $fieldSet, $condition);
$fieldSet = "ctazonaentrega=$zonaVDestino";
$condition= "ctazonaentrega=$zonaDOrigen";
DataManager::updateToTable('cuenta', $fieldSet, $condition);
// MOVIMIENTO //
$movimiento = 'CAMBIO_ZonaEntrega_'.$zonaDOrigen.'_a_'.$zonaDDestino;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", 0);
break;
default:
echo "Debe seleccionar una opción para modificar las zonas"; exit;
break;
}
echo "1"; exit; ?><file_sep>/rendicion/logica/ajax/anular.rendicion.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//*******************************************
$_idusr = (isset($_POST['idusr'])) ? $_POST['idusr'] : NULL;
$_nro_anular = (isset($_POST['nro_anular'])) ? $_POST['nro_anular'] : NULL;
//*************************************************
//Controles
//*************************************************
if ($_idusr == 0) { echo "Debe seleccionar un vendedor."; exit; }
if (empty($_nro_anular) || !is_numeric($_nro_anular)) { echo "Número de rendición incorrecto."; exit; }
//*************************************************
// Desactivo la rendición (con esa fecha y usuario)
//*************************************************
$_rendicion = DataManager::getRendicion($_idusr, $_nro_anular);
if (count($_rendicion)){
foreach ($_rendicion as $k => $_rend){
$_rend = $_rendicion[$k];
$_rendid = $_rend["rendid"];
/*se anula la rendicion*/
$_rendobject = DataManager::newObjectOfClass('TRendicion', $_rendid);
$_rendobject->__set('ID', $_rendid);
if(($_rendobject->__get('Activa')) == 0){
$_rendobject->__set('ID', $_rendid);
$_rendobject->__set('Activa', 1);
$ID = DataManager::updateSimpleObject($_rendobject);
if (empty($ID)) { echo "Error al anular la rendición. $ID."; exit; }
} else {
echo "El recibo indicado no se puede anular porque no fue enviado."; exit;
}
}
} else {
echo "No se verifica que haya datos de rendición para anular en esa fecha."; exit;
}
//*******************************************************************
echo "Se ha anulado el envío de la rendición. Si no ve los cambios presione la tecla F5";
//*******************************************************************
?>
<file_sep>/zonas/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$zId = empty($_REQUEST['zid']) ? 0 : $_REQUEST['zid'];
if ($zId) {
$zObject = DataManager::newObjectOfClass('TZonas', $zId);
$zZona = $zObject->__get('Zona');
$zNombre = $zObject->__get('Nombre');
$usrAssigned= $zObject->__get('UsrAssigned');
} else {
$zZona = "";
$zNombre = "";
$usrAssigned= '';
} ?>
<!DOCTYPE html>
<html lang="es">
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = 'planificar';
$_subsection = 'nueva_zona';
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav> <!-- fin menu -->
<main class="cuerpo">
<div class="box_body">
<form name="fmZona" method="post">
<input type="hidden" name="zid" value="<?php echo @$zId; ?>" />
<fieldset>
<legend>Zona</legend>
<div class="bloque_1" align="center">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<div class="bloque_8">
<label for="zzona">Zona</label>
<input name="zzona" type="text" maxlength="3" value="<?php echo @$zZona;?>"/>
</div>
<div class="bloque_6">
<label for="znombre">Nombre</label>
<input type="text" name="znombre" maxlength="30" value="<?php echo @$zNombre;?>"/>
</div>
<div class="bloque_6">
<label for="asignado">Asignado a</label>
<select name="asignado">
<option id="0" value="0" selected></option> <?php
$vendedores = DataManager::getUsuarios( 0, 0, 1, NULL, '"V"');
if (count($vendedores)) {
foreach ($vendedores as $k => $vend) {
$idVend = $vend["uid"];
$nombreVend = $vend['unombre'];
if ($idVend == $usrAssigned){ ?>
<option id="<?php echo $idVend; ?>" value="<?php echo $idVend; ?>" selected><?php echo $nombreVend; ?></option><?php
} else { ?>
<option id="<?php echo $idVend; ?>" value="<?php echo $idVend; ?>"><?php echo $nombreVend; ?></option><?php
}
}
} ?>
</select>
</div>
<div class="bloque_8">
<br>
<?php $urlSend = '/pedidos/zonas/logica/update.zona.php';?>
<a id="btnSend" title="Enviar" style="cursor:pointer;">
<img class="icon-send" onclick="javascript:dac_sendForm(fmZona, '<?php echo $urlSend;?>');"/>
</a>
</div>
</fieldset>
</form>
</div> <!-- boxbody -->
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/transfer/logica/reasignar.pedido.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$nroPedido = empty($_POST['nroPedido']) ? 0 : $_POST['nroPedido'];
$usrAsignado = empty($_POST['ptAsignar']) ? NULL : $_POST['ptAsignar'];
if(empty($usrAsignado)){
echo "Debe indicar usuario asignado."; exit;
}
if ($nroPedido) {
$detalles = DataManager::getTransfersPedido(NULL, NULL, NULL, NULL, NULL, NULL, $nroPedido); //DataManager::getDetallePedidoTransfer($nroPedido);
if ($detalles) {
foreach ($detalles as $k => $det) {
$ptId = $det['ptid'];
if($ptId) {
$ptObject = DataManager::newObjectOfClass('TPedidosTransfer', $ptId);
$ptObject->__set('ParaIdUsr', $usrAsignado);
DataManagerHiper::updateSimpleObject($ptObject, $ptId);
DataManager::updateSimpleObject($ptObject);
//MOVIMIENTO de CUENTA
$movimiento = 'REASIGNA_USR_'.$usrAsignado;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, 'TPedidosTransfer', $ptId);
}
}
}
}
echo "1"; exit;
?><file_sep>/includes/cargaWeb.php
<div id="imgBloqueo" class="parpadeo">
<img id="bloqueoContenido">
</div>
<script>
$('html, body, .cuerpo').css('overflow', 'hidden');
$('#bloqueoContenido').css({
'margin-left': ($(window).width() / 2 - $(bloqueoContenido).width() / 2) + 'px',
'margin-top': ($(window).height() / 2 - $(bloqueoContenido).height() / 2) + 'px'
});
$(window).resize(function(){
$('#bloqueoContenido').css({
'margin-left': ($(window).width() / 2 - $(bloqueoContenido).width() / 2) + 'px',
'margin-top': ($(window).height() / 2 - $(bloqueoContenido).height() / 2) + 'px'
});
});
window.onload = function() {
$('#imgBloqueo').fadeOut('slow');
$('#imgBloqueo').remove;
$('html, body, .cuerpo').css('overflow', 'auto');
}
</script><file_sep>/cadenas/logica/ajax/getCuentasCadena.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
//*************************************************
$empresa = (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
$cadena = (isset($_POST['cadena'])) ? $_POST['cadena'] : NULL;
//*************************************************
$datosJSON;
$cuentas = DataManager::getCuentasCadena($empresa, $cadena);
if (count($cuentas)) {
foreach ($cuentas as $k => $cta) {
$idCuenta = $cta['IdCliente'];
$tipoCadena= $cta['TipoCadena'];
$ctaid = DataManager::getCuenta('ctaid', 'ctaidcuenta', $idCuenta, $empresa);
$nombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $idCuenta, $empresa);
$datosJSON[] = array(
"id" => $ctaid,
"cuenta" => $idCuenta,
"nombre" => $nombre,
"tipocad" => $tipoCadena
);
}
}
/*una vez tenemos un array con los datos los mandamos por json a la web*/
header('Content-type: application/json');
echo json_encode($datosJSON);
?><file_sep>/rendicion/logica/ajax/nuevo.talonario.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//*************************************************
$_nrotalonario = (isset($_REQUEST['nrotalonario'])) ? $_REQUEST['nrotalonario'] : NULL;
$salir = 0;
//*************************************************
if((empty($_nrotalonario) or !is_numeric($_nrotalonario))){
echo "Debe completar el número de talonario correctamente.\n"; $salir = 1; exit;
}
if ($salir == 0){
$_talorarios = DataManager::getBuscarTalonario($_nrotalonario);
if ($_talorarios){ echo "El talonario ya existe."; exit;
} else {
//Consulto último talonario cargado en las rendiciones y que tenga 25 recibos para crear uno nuevo.
$_ultima_rendicion = DataManager::getMaxRendicion($_SESSION["_usrid"]);
$_rendiciones = DataManager::getDetalleRendicion($_SESSION["_usrid"], $_ultima_rendicion);
if ($_rendiciones){
$_talAnt = 0;
foreach ($_rendiciones as $k => $_rend){
$_rend = $_rendiciones[$k];
//Guardo el mayor nro de Talonario
$_rendTal = $_rend['Tal'];
if($_rendTal > $_talAnt){
$_talAnt = $_rendTal;
$_rendIDRecibo = $_rend['IDRecibo'];
}
}
// Cuento cuantos recibos tiene ese talonario
$_reciboobject = DataManager::newObjectOfClass('TRecibos', $_rendIDRecibo);
$_max_Talonario = $_reciboobject->__get('Talonario');
$_tot_recibos = DataManager::ExistFromDatabase($_reciboobject, 'rectalonario', $_max_Talonario);
if($_tot_recibos < 25){
echo "Faltan cargar recibos del talonario $_max_Talonario"; exit;
} else {
$_insertar = DataManager::insertToTable('talonario_idusr', 'nrotalonario, idusr', "'".$_nrotalonario."','".$_SESSION["_usrid"]."'");
echo "1"; exit;
}
}else{
//Por acá significa que no existen talonarios grabados en la tabla
$_insertar = DataManager::insertToTable('talonario_idusr', 'nrotalonario, idusr', "'".$_nrotalonario."','".$_SESSION["_usrid"]."'");
echo "1"; exit;
//echo "Error en la consulta de sus rendiciones. Consulte con el administrador de la web.";
}
}
}
?><file_sep>/articulos/logica/ajax/cargar.formulas.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
$artId = (isset($_POST['artId'])) ? $_POST['artId'] : NULL;
if(empty($artId)){ exit;}
$formulas = DataManager::getArticuloFormula( $artId );
if (count($formulas)) {
foreach ($formulas as $k => $form) {
$fmId = $form["afid"];
$fmIfa = $form["afifa"];
$fmCant = $form["afcantidad"];
$fmMedida = $form["afumedida"];
$fmIfaComo = $form["afifacomo"];
$fmCantComo = $form["afcantidadcomo"];
$fmMedidaComo = $form["afumedidacomo"];
echo "<script>";
echo "javascript:dac_cargarFormula('".$fmId."', '".$fmIfa."', '".$fmCant."', '".$fmMedida."', '".$fmIfaComo."', '".$fmCantComo."', '".$fmMedidaComo."');";
echo "</script>";
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr id=formula".$fmId." class=".$clase." onclick=\"javascript:dac_cargarFormula('$fmId', '$fmIfa', '$fmCant', '$fmMedida', '$fmIfaComo', '$fmCantComo', '$fmMedidaComo' )\" style=\"cursor:pointer;\"><td>".$idCuenta."</td><td>".$nombre."</td><td>".$localidad."</td></tr>";
}
}
exit;
?><file_sep>/transfer/gestion/liquidacion/logica/jquery/jquery.process.emitirnc.js
$(document).ready(function() {
$("#emitirnc").click(function () {
var idliquid = "";
var fecha = "";
var transfer = "";
var fechafact = "";
var nrofact = "";
var ean = "";
var idart = "";
var cant = "";
var unitario = "";
var desc = "";
var importe = "";
var estado = "";
var activa = 0;
//CONTROL//
//Si liquidación está ACTIVA (liquidada) NO permitirá EMITIR NUEVAMENTE
$('input[name="activa[]"]:text').each(function(){
if($(this).val() == "1"){ activa = 1; }
});
if(activa == 0){
drogid = $('input[name="drogid_liquidacion"]:text').val();
mes = $('input[name="mes_liquidacion"]:text').val();
anio = $('input[name="anio_liquidacion"]:text').val();
conciliar = $('input[name="conciliar"]:text').val();
$('input[name="idliquid[]"]:text').each(function() { idliquid = idliquid+"|"+$(this).val();});
$('input[name="fecha[]"]:text').each(function() { fecha = fecha+"|"+$(this).val();});
$('input[name="transfer[]"]:text').each(function() { transfer = transfer+"|"+$(this).val();});
$('input[name="fechafact[]"]:text').each(function() { fechafact = fechafact+"|"+$(this).val();});
$('input[name="desc[]"]:text').each(function() { desc = desc+"|"+$(this).val();});
$('input[name="nrofact[]"]:text').each(function() { nrofact = nrofact+"|"+$(this).val();});
$('input[name="cant[]"]:text').each(function() { cant = cant+"|"+$(this).val();});
$('input[name="idart[]"]:text').each(function() { idart = idart+"|"+$(this).val();});
$('input[name="ean[]"]:text').each(function() { ean = ean+"|"+$(this).val();});
$('input[name="unitario[]"]:text').each(function() { unitario = unitario+"|"+$(this).val();});
$('input[name="importe[]"]:text').each(function() { importe = importe+"|"+$(this).val();});
$('input[name="estado[]"]:text').each(function() { estado = estado+"|"+$(this).val();});
dac_conciliarLiquidacion();
function dac_conciliarLiquidacion(){
$.ajax({
type: "POST",
url: "logica/update.liquidacion.php",
data: { idliquid : idliquid,
mes : mes,
anio : anio,
drogid : drogid,
fecha : fecha,
fechafact : fechafact,
transfer : transfer,
desc : desc,
nrofact : nrofact,
ean : ean,
idart : idart,
cant : cant,
unitario : unitario,
importe : importe,
conciliar : conciliar,
estado : estado
},
success: function(result) {
if(result){
if(result == 1){
alert("Los cambios se han actualizado.");
location.reload();
}else{ alert(result);}
}
}
});
}
} else {
alert("ATENCI\u00D3N! No puede volver a EMITIR NC de \u00E9sta liquidaci\u00F3n.");
}
});
});<file_sep>/planificacion/logica/ajax/select.acciones.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//Éste header se utiliza porqe sino los caracteres con acento los pasa como signos de pregunta
header("Content-Type: text/plain; charset=iso-8859-1");
//*******************************************
// CONSULTO ACCIONES ACTIVAS
//*******************************************
$_accobject = DataManager::getAcciones('', '', 1);
if (count($_accobject)) {
foreach ($_accobject as $k => $_accion) {
$_array_acid = (empty($_array_acid)) ? $_array_acid=$_accion["acid"] : $_array_acid.",".$_accion["acid"];
$_array_acnombre = (empty($_array_acnombre)) ? $_array_acnombre=$_accion["acnombre"] : $_array_acnombre.",".$_accion["acnombre"];
}
$_acciones = $_array_acid."/".$_array_acnombre;
echo $_acciones;
} else {
echo "0/0";
//echo "No se han encontrado acciones registradas para cargar.";
}
?><file_sep>/proveedores/fechaspago/logica/exportar.historial.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$fechaDesde = empty($_REQUEST['desde']) ? NULL : $_REQUEST['desde'];
$fechaHasta = empty($_REQUEST['hasta']) ? NULL : $_REQUEST['hasta'];
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment; filename=FechaPagosDel".$fechaDesde."al".$fechaHasta.".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos .::</TITLE>
<head></head>
<body>
<div id="cuadro-fechaspago">
<div id="muestra_fechaspago">
<table border="0">
<thead>
<tr>
<th colspan="10" align="left"> Fecha de Pago del <?php echo $fechaDesde;?> al <?php echo $fechaHasta;?></th>
</tr>
<tr><th colspan="10" align="left"></th> </tr>
<tr height="60px;"> <!-- Títulos de las Columnas -->
<th align="center" style="background-color:#333; color:#FFF;">Emp</th>
<th align="center" style="background-color:#333; color:#FFF;">Código</th>
<th style="background-color:#333; color:#FFF;">Proveedor</th>
<th align="center" style="background-color:#333; color:#FFF;">Plazo</th>
<th align="center" style="background-color:#333; color:#FFF;">Vencimiento</th>
<th align="center" style="background-color:#333; color:#FFF;">Tipo</th>
<th align="center" style="background-color:#333; color:#FFF;">Nro</th>
<th align="center" style="background-color:#333; color:#FFF;">Fecha de cbte</th>
<th align="center" style="background-color:#333; color:#FFF;">Saldo</th>
<th align="center" style="background-color:#333; color:#FFF;">Observación</th>
</tr>
</thead>
<tbody id="lista_fechaspago"> <?php
//hago consulta de fechas de pago en la fecha actual ordenada por proveedor
$saldoTotal = 0;
$facturasPago = DataManager::getFacturasProveedor( NULL, 1, NULL, NULL, NULL, NULL, dac_invertirFecha($fechaDesde), dac_invertirFecha($fechaHasta)) ;
if($facturasPago) {
foreach ($facturasPago as $k => $fact) {
$idFact = $fact['factid'];
$idEmpresa = $fact['factidemp'];
$idProv = $fact['factidprov'];
//Saco el nombre del proveedor
$proveedor = DataManager::getProveedor('providprov', $idProv, $idEmpresa);
$nombre = ($proveedor) ? $proveedor['0']['provnombre'] : '';
$plazo = $fact['factplazo'];
$tipo = $fact['facttipo'];
$factNro = $fact['factnumero'];
$fechaCbte = dac_invertirFecha($fact['factfechacbte']);
$fechaVto = dac_invertirFecha($fact['factfechavto']);
$saldo = $fact['factsaldo'];
$observacion= $fact['factobservacion'];
$activa = $fact['factactiva'];
((($k % 2) != 0)? $clase="background-color:#CCC; color:#000; font-weight:bold;" : $clase="");
$saldoTotal += $saldo; ?>
<tr id="rutfact<?php echo $k;?>">
<td style=" <?php echo $clase; ?> " align="center"><?php echo $idEmpresa;?></td>
<td style=" <?php echo $clase; ?> " align="left"><?php echo $idProv;?></td>
<td style=" <?php echo $clase; ?> "><?php echo $nombre;?></td>
<td style=" <?php echo $clase; ?> " align="center"><?php echo $plazo;?></td>
<td style=" <?php echo $clase; ?> "><?php echo $fechaVto;?></td>
<td style=" <?php echo $clase; ?> "><?php echo $tipo;?></td>
<td style=" <?php echo $clase; ?> " align="left"><?php echo $factNro;?></td>
<td style=" <?php echo $clase; ?> "><?php echo $fechaCbte;?></td>
<td style=" <?php echo $clase; ?> " align="right"><?php echo $saldo;?></td>
<td style=" <?php echo $clase; ?> " align="left"><?php echo $observacion;?></td>
</tr> <?php
}
} else { ?>
<tr class="impar"><td colspan="9" align="center">No hay pagos cargados</td></tr><?php
} ?>
</tbody>
<tfoot>
<tr>
<th colspan="7" height="30px" style="border:none; font-weight:bold;"></th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;">Total</th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;" align="right"><?php echo $saldoTotal; ?></th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;"></th>
</tr>
</tfoot>
</table>
</div> <!-- FIN fechaspago -->
</div> <!-- FIN fechaspago -->
</body>
</html>
<file_sep>/includes/class/class.propuesta.detalle.php
<?php
require_once('class.PropertyObject.php');
class TPropuestaDetalle extends PropertyObject {
protected $_tablename = 'propuesta_detalle';
protected $_fieldid = 'pdid';
protected $_fieldactivo = 'pdactivo';
protected $_timestamp = 0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'pdid';
$this->propertyTable['IDPropuesta'] = 'pdpropid';
$this->propertyTable['CondicionPago'] = 'pdcondpago';
$this->propertyTable['IDArt'] = 'pdidart';
$this->propertyTable['Cantidad'] = 'pdcantidad';
$this->propertyTable['Precio'] = 'pdprecio';
$this->propertyTable['Bonificacion1'] = 'pdbonif1';
$this->propertyTable['Bonificacion2'] = 'pdbonif2';
$this->propertyTable['Descuento1'] = 'pddesc1';
$this->propertyTable['Descuento2'] = 'pddesc2';
$this->propertyTable['Estado'] = 'pdestado'; //estado de la propuesta PENDIENTE/APROBADA/RECHAZADA
$this->propertyTable['Fecha'] = 'pdfecha';
$this->propertyTable['Activo'] = 'pdactivo'; //Si est áinactivo, es de una propuesta viehaja
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
/*
public function Autenticado() {
return $this->_autenticado;
}*/
public function __newID() {
// Devuelve '#petid' para el alta de un nuevo registro
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/includes/class/class.prospecto.php
<?php
require_once('class.PropertyObject.php');
class TProspecto extends PropertyObject {
protected $_tablename = 'prospecto';
protected $_fieldid = 'proid';
protected $_fieldactivo = 'proactivo';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'proid';
$this->propertyTable['Categoria'] = 'procategoria';
$this->propertyTable['Cadena'] = 'procadena'; //Si es cadena o no!
$this->propertyTable['Nombre'] = 'pronombre';
$this->propertyTable['Tipo'] = 'protipo'; //si es prospecto, cliente, transfer
$this->propertyTable['DireccionCompleta'] = 'prodircompleta'; //Completa//
$this->propertyTable['Direccion'] = 'prodireccion';
$this->propertyTable['Localidad'] = 'prolocalidad';
$this->propertyTable['Provincia'] = 'proprovincia';
$this->propertyTable['CP'] = 'procp';
$this->propertyTable['CUIT'] = 'procuit';
$this->propertyTable['Pais'] = 'propais';
$this->propertyTable['Telefono'] = 'protelefono';
$this->propertyTable['Web'] = 'proweb';
$this->propertyTable['Email'] = 'procorreo';
$this->propertyTable['MapLink'] = 'promaplink';
$this->propertyTable['Longitud'] = 'prolongitud';
$this->propertyTable['Latitud'] = 'prolatitud';
$this->propertyTable['DetalleLink'] = 'prodetallelink';
$this->propertyTable['Observacion'] = 'proobservacion';
$this->propertyTable['UsrUpdate'] = 'prousrupdate';
$this->propertyTable['LastUpdate'] = 'prolastupdate';
$this->propertyTable['Activo'] = 'proactivo';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
// Devuelve '#petid' para el alta de un nuevo registro
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/localidades/lista.php
<?php
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/localidades/': $_REQUEST['backURL'];
$btnNuevo = sprintf( "<a href=\"editar.php\" title=\"Nuevo\"><img class=\"icon-new\"/></a>");
$btnNuevo2 = sprintf( "<a href=\"/pedidos/zonas/editar.php\" title=\"Nuevo\"><img class=\"icon-new\"/></a>");
?>
<script type="text/javascript">
function dac_addLocalidad(){
var selected = [];
$("input:checkbox[name=editSelected]:checked").each(function() {
selected.push( $(this).val() );
});
$("#editSelected2").val(selected);
}
function dac_searchSelect(idProv, idZonaV, idZonaD){
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/localidades/logica/ajax/getLocalidades.php',
data: { idProv : idProv,
idZonaV : idZonaV,
idZonaD : idZonaD
},
beforeSend : function () {
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
if (resultado){
var tabla = resultado;
document.getElementById('tablaLocalidades').innerHTML = tabla;
$('#box_cargando').css({'display':'none'});
} else {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
},
});
}
</script>
<div class="box_body">
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<div class="barra">
<div class="bloque_3">
<h1>Localidades</h1>
</div>
<div class="bloque_9">
<a href="logica/exportar.localidades.php" title="Exportar">
<img class="icon-xls-export"/>
</a>
</div>
<div class="bloque_9">
<?php echo $btnNuevo; ?>
</div>
<hr>
<div class="bloque_7">
<select id="provSelect" onchange="javascript:dac_searchSelect(provSelect.value, zonaVSelect.value, zonaDSelect.value);"> <?php
$provincias = DataManager::getProvincias();
if (count($provincias)) { ?>
<option id="0" value="0">Provincia</option> <?php
foreach ($provincias as $k => $prov) {
$provId = $prov["provid"];
$provNombre = $prov["provnombre"]; ?>
<option id="<?php echo $provId; ?>" value="<?php echo $provId; ?>"><?php echo $provNombre; ?></option>
<?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<select id="zonaVSelect" onchange="javascript:dac_searchSelect(provSelect.value, zonaVSelect.value, zonaDSelect.value);"> <?php
$zonasVenta = DataManager::getZonas(0, 0, 1);
if (count($zonasVenta)) { ?>
<option id="0" value="0">Zona Venta</option> <?php
foreach ($zonasVenta as $k => $zonasV) {
$zonaVNro = $zonasV["zzona"];
$zonaVNombre= $zonasV["znombre"]; ?>
<option value="<?php echo $zonaVNro; ?>"><?php echo $zonaVNro." - ".$zonaVNombre; ?></option> <?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<select id="zonaDSelect" onchange="javascript:dac_searchSelect(provSelect.value, zonaVSelect.value, zonaDSelect.value);"><?php
$zonasDistribucion = DataManager::getZonasDistribucion();
if (count($zonasDistribucion)) {?>
<option id="0" value="0">Zona Distribución</option> <?php
foreach ($zonasDistribucion as $k => $zonasD) {
$zonaDId = $zonasD["IdZona"];
$zonaDNombre= $zonasD["NombreZN"]; ?>
<option value="<?php echo $zonaDId; ?>"><?php echo $zonaDId." - ".$zonaDNombre; ?></option>
<?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar por Página">
<input id="txtBuscarEn" type="text" value="tblLocalidades" hidden>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<div id='tablaLocalidades'></div>
<?php
echo "<script>";
echo "javascript:dac_searchSelect('1')";
echo "</script>"; ?>
</div>
<div class="barra">
<div class="bloque_5">
<h1>Excepciones</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar2" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn2" type="text" value="tblExcepciones" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista"> <?php
$zonasExpecion = DataManager::getZonasExcepcion();
if(count($zonasExpecion)){
echo "<table id=\"tblExcepciones\" style=\"table-layout:fixed;\">";
echo "<thead><tr align=\"left\"><th>Localidad</th><th>Zona</th><th>Emp</th><th>Cuenta</th><th>Zona Excepción</th></thead>";
echo "<tbody>";
foreach ($zonasExpecion as $k => $ze) {
$zeIdLoc = $ze['zeIdLoc'];
$zeCtaId = $ze['zeCtaId'];
$zeZona = $ze['zeZona'];
$idCuenta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $zeCtaId);
$empresa = DataManager::getCuenta('ctaidempresa', 'ctaid', $zeCtaId);
$localidad = DataManager::getLocalidad('locnombre', $zeIdLoc);
$zonasLoc = DataManager::getLocalidad('loczonavendedor', $zeIdLoc);
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class=".$clase.">";
echo "<td height=\"15\">".$localidad."</td><td >".$zonasLoc."</td><td >".$empresa."</td><td >".$idCuenta."</td><td >".$zeZona."</td>";
echo "</tr>";
}
echo "</tbody></table>";
} ?>
</div> <!-- Fin lista -->
</div> <!-- Fin box_cuerpo -->
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Zonas</h1>
</div>
<div class="bloque_5">
<?php echo $btnNuevo2; ?>
</div>
<hr>
</div>
<div class="lista_super">
<?php
$_LPP = 10;
$_total = DataManager::getNumeroFilasTotales('TZonas', 0);
$_paginas = ceil($_total/$_LPP);
$_pag = isset($_REQUEST['pag']) ? min(max(1,$_REQUEST['pag']),$_paginas) : 1;
$_GOFirst = sprintf("<a class=\"icon-go-first\" href=\"%s?pag=%d\"></a>", $backURL, 1);
$_GOPrev3 = sprintf("<a href=\"%s?pag=%d\">%s</a>", $backURL, $_pag-3 , $_pag-3);
$_GOPrev2 = sprintf("<a href=\"%s?pag=%d\">%s</a>", $backURL, $_pag-2 , $_pag-2);
$_GOPrev = sprintf("<a class=\"icon-go-previous\" href=\"%s?pag=%d\"></a>", $backURL, $_pag-1);
$_GOActual = sprintf("%s", $_pag);
$_GONext = sprintf("<a class=\"icon-go-next\" href=\"%s?pag=%d\"></a>", $backURL, $_pag+1);
$_GONext2 = sprintf("<a href=\"%s?pag=%d\">%s</a>", $backURL, $_pag+2 , $_pag+2);
$_GONext3 = sprintf("<a href=\"%s?pag=%d\">%s</a>", $backURL, $_pag+3 , $_pag+3);
$_GOLast = sprintf("<a class=\"icon-go-last\" href=\"%s?pag=%d\"></a>", $backURL, $_paginas);
?>
<table>
<thead>
<tr>
<th scope="col" align="center" width="25%" height="18">Zona</th>
<th scope="col" width="50%">Nombre</th>
<th scope="colgroup" colspan="3" align="center" width="25%">Acciones</th>
</tr>
</thead>
<tbody>
<?php
$_zonas = DataManager::getZonas($_pag, $_LPP, NULL);
$_max = count($_zonas); // la última página vendrá incompleta
for( $k=0; $k < $_LPP; $k++ ) {
if ($k < $_max) {
$_zona = $_zonas[$k];
$_numero = $_zona['zzona'];
$_nombre = $_zona['znombre'];
$_status = ($_zona['zactivo']) ? "<img class=\"icon-status-active\"/>" : "<img class=\"icon-status-inactive\"/>";
if ($_SESSION["_usrrol"]=="A"){
$_editar = sprintf( "<a href=\"/pedidos/zonas/editar.php?zid=%d&backURL=%s\" title=\"editar zona\">%s</a>", $_zona['zid'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit\" />");
$_borrar = sprintf( "<a href=\"/pedidos/zonas/logica/changestatus.php?zid=%d&backURL=%s&pag=%s\" title=\"Cambiar Estado\">%s</a>", $_zona['zid'], $_SERVER['PHP_SELF'], $_pag, $_status);
$_eliminar = sprintf ("<a href=\"/pedidos/zonas/logica/eliminar.zona.php?zid=%d&backURL=%s&nrozona=%s\" title=\"eliminar zona\" onclick=\"return confirm('¿Está Seguro que desea ELIMINAR LA ZONA?')\"> <img class=\"icon-delete\" /> </a>", $_zona['zid'], $_SERVER['PHP_SELF'], $_numero, "eliminar");
} else {
$_editar = " ";
$_borrar = " ";
$_eliminar = " ";
}
} else {
$_numero = " ";
$_nombre = " ";
$_editar = " ";
$_borrar = " ";
$_eliminar = " ";
}
if ($_SESSION["_usrrol"]=="V"){
$_editar = " ";
$_borrar = " ";
$_eliminar = " ";
}
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\" align=\"center\">%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_numero, $_nombre, $_editar, $_borrar, $_eliminar);
echo sprintf("</tr>");
} ?>
</tbody>
</table>
</div>
<?php
if ( $_paginas > 1 ) {
$_First = ($_pag > 1) ? $_GOFirst : " ";
$_Prev = ($_pag > 1) ? $_GOPrev : " ";
$_Last = ($_pag < $_paginas) ? $_GOLast : " ";
$_Next = ($_pag < $_paginas) ? $_GONext : " ";
$_Prev2 = $_Next2 = $_Prev3 = $_Next3 = '';
$_Actual= $_GOActual;
if ( $_paginas > 4 ) {
$_Prev2 = ($_pag > 2) ? $_GOPrev2 : " ";
$_Next2 = ($_pag < $_paginas-2) ? $_GONext2 : " ";
}
if ( $_paginas > 6 ) {
$_Prev3 = ($_pag > 3) ? $_GOPrev3 : " ";
$_Next3 = ($_pag < $_paginas-3) ? $_GONext3 : " ";
}
echo("<table class=\"paginador\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
echo sprintf("<td height=\"16\">Mostrando página %d de %d</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td>", $_pag, $_paginas, $_First, $_Prev3, $_Prev2, $_Prev, $_Actual, $_Next, $_Next2, $_Next3, $_Last);
echo("</tr></table>");
} ?>
<?php if ($_SESSION["_usrrol"]!="V"){ ?>
<form id="frmZonaLocalidades" method="POST">
<fieldset>
<fieldset id='box_observacion' class="msg_alerta" style="display: block;">
<div id="msg_atencion" align="center">Las zonas de venta [95, 99, 100, 199] serán discriminadas en el cambio. <br> Ante cualquier duda revise el listado de zonas.</div>
</fieldset>
<legend>Cambiar ZONAS</legend>
<div class="bloque_5">
<input type="radio" name="radioZonas" value="localidad">
<input type="text" id="editSelected2" name="editSelected2" hidden="hidden">
<laber><h2>POR LOCALIDAD</h2></laber>
</div>
<div class="bloque_5">
<input type="radio" name="radioZonas" value="provincia">
<laber><h2>POR PROVINCIA</h2></laber>
</div>
<div class="bloque_1">
<select name="provincia">
<option value="0" selected> Provincia... </option> <?php
$provincias = DataManager::getProvincias();
if (count($provincias)) {
$idprov = 0;
foreach ($provincias as $k => $prov) {
$selected = ($provincia == $prov["provid"]) ? "selected" : ""; ?>
<option id="<?php echo $prov["provid"]; ?>" value="<?php echo $prov["provid"]; ?>" <?php echo $selected; ?>><?php echo $prov["provnombre"]; ?></option> <?php
}
} ?>
</select>
</div>
<div class="bloque_5">
<select name="zonaVSelect"><?php
$zonasVenta = DataManager::getZonas(0, 0, 1);
if (count($zonasVenta)) { ?>
<option id="0" value="0">Zona Venta</option> <?php
foreach ($zonasVenta as $k => $zonasV) {
$zonaVNro = $zonasV["zzona"];
$zonaVNombre= $zonasV["znombre"]; ?>
<option value="<?php echo $zonaVNro; ?>"><?php echo $zonaVNro." - ".$zonaVNombre; ?></option> <?php
}
} ?>
</select>
</div>
<div class="bloque_5">
<select name="zonaDSelect"><?php
$zonasDistribucion = DataManager::getZonasDistribucion();
if (count($zonasDistribucion)) {?>
<option id="0" value="0">Zona Distribución</option> <?php
foreach ($zonasDistribucion as $k => $zonasD) {
$zonaDId = $zonasD["IdZona"];
$zonaDNombre= $zonasD["NombreZN"]; ?>
<option value="<?php echo $zonaDId; ?>"><?php echo $zonaDId." - ".$zonaDNombre; ?></option>
<?php
}
} ?>
</select>
</div>
<hr>
<div class="bloque_1">
<input type="radio" name="radioZonas" value="vendedor">
<laber><h2>POR ZONA DE VENTA (VENDEDOR DE HIPER)</h2></laber>
</div>
<div class="bloque_5">
<label>Origen</label>
<select name="zonaVOrigen"><?php
$zonasVenta = DataManager::getZonas(0, 0, 1);
if (count($zonasVenta)) { ?>
<option id="0" value="0">Zona Venta 1</option> <?php
foreach ($zonasVenta as $k => $zonasV) {
$zonaVNro = $zonasV["zzona"];
$zonaVNombre= $zonasV["znombre"]; ?>
<option value="<?php echo $zonaVNro; ?>"><?php echo $zonaVNro." - ".$zonaVNombre; ?></option> <?php
}
} ?>
</select>
</div>
<div class="bloque_5">
<label>Destino</label>
<select name="zonaVDestino"><?php
$zonasVenta = DataManager::getZonas(0, 0, 1);
if (count($zonasVenta)) { ?>
<option id="0" value="0">Zona Venta 2</option> <?php
foreach ($zonasVenta as $k => $zonasV) {
$zonaVNro = $zonasV["zzona"];
$zonaVNombre= $zonasV["znombre"]; ?>
<option value="<?php echo $zonaVNro; ?>"><?php echo $zonaVNro." - ".$zonaVNombre; ?></option> <?php
}
} ?>
</select>
</div>
<hr>
<div class="bloque_1">
<input type="radio" name="radioZonas" value="distribucion">
<laber><h2>POR ZONA DE DISTRIBUCIÓN</h2></laber>
</div>
<div class="bloque_5">
<label>Origen</label>
<select name="zonaDOrigen"><?php
$zonasDistribucion = DataManager::getZonasDistribucion();
if (count($zonasDistribucion)) {?>
<option id="0" value="0">Zona Distribución 1</option> <?php
foreach ($zonasDistribucion as $k => $zonasD) {
$zonaDId = $zonasD["IdZona"];
$zonaDNombre= $zonasD["NombreZN"]; ?>
<option value="<?php echo $zonaDId; ?>"><?php echo $zonaDId." - ".$zonaDNombre; ?></option> <?php
}
} ?>
</select>
</div>
<div class="bloque_5">
<label>Destino</label>
<select name="zonaDDestino"><?php
$zonasDistribucion = DataManager::getZonasDistribucion();
if (count($zonasDistribucion)) {?>
<option id="0" value="0">Zona Distribución 2</option> <?php
foreach ($zonasDistribucion as $k => $zonasD) {
$zonaDId = $zonasD["IdZona"];
$zonaDNombre= $zonasD["NombreZN"]; ?>
<option value="<?php echo $zonaDId; ?>"><?php echo $zonaDId." - ".$zonaDNombre; ?></option>
<?php
}
} ?>
</select>
</div>
<div class="bloque_1">
<?php $urlSend = '/pedidos/localidades/logica/update.zonasLocalidad.php';?>
<?php $urlBack = '/pedidos/localidades/';?>
<a id="btnSend" title="Enviar" style="cursor:pointer;">
<img class="icon-save" onclick="javascript:dac_sendForm(frmZonaLocalidades, '<?php echo $urlSend;?>', '<?php echo $urlBack;?>');"/>
</a>
</div>
</fieldset>
</form>
<?php } ?>
</div> <!-- Fin box_seccion -->
<hr>
<file_sep>/includes/class/class.facturas.php
<?php
require_once('class.PropertyObject.php');
class TFacturas extends PropertyObject {
protected $_tablename = 'facturas';
protected $_fieldid = 'factid';
//protected $_fieldactivo = 'cheqactivo';
protected $_timestamp = 0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'factid'; //Relación con tabla "rec_fact" para IDRecibo
// También relación con tabla "fact_cheq" para IDFactura
$this->propertyTable['Numero'] = 'factnro';
$this->propertyTable['Cliente'] = 'factidcliente'; //Relación con tabla "cliente"
$this->propertyTable['Fecha'] = 'factfecha';
$this->propertyTable['Bruto'] = 'factbruto';
$this->propertyTable['Descuento'] = 'factdesc';
$this->propertyTable['Neto'] = 'factneto';
$this->propertyTable['Efectivo'] = 'factefectivo';
$this->propertyTable['Transfer'] = 'facttransfer';
$this->propertyTable['Retencion'] = 'factretencion';
//$this->propertyTable['Activa'] = 'cheqactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
/*
public function Autenticado() {
return $this->_autenticado;
}*/
public function __newID() {
// Devuelve '#petid' para el alta de un nuevo registro
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/planificacion/logica/jquery/jqueryAdminFooter.js
var g_globalObject3 = new JsDatePick({
useMode:2,
target:"f_fecha_anular",
dateFormat:"%d-%M-%Y"
});
var g_globalObject4 = new JsDatePick({
useMode:2,
target:"f_fecha_anular_parte",
dateFormat:"%d-%M-%Y"
});<file_sep>/js/jquery/jquery.paging.js
/**
* @license jQuery paging plugin v1.1.1 01/01/2019
* La humildad es madre de la modestia
* Copyright (c) 2019, <NAME>.
**/
(function($, window, undefined) {
"use strict";
$.fn.paging = function(rows, totalRows, data, url, tableName, selectChange) {
//Construye el paginador
var PAGINATOR= $('paginator');
PAGINATOR.empty();
var tappage = '<select id="tabpage"><option></option> </select>',
first = '<pagFirst><img id="goFirst" class="paginadores" src="../images/icons/icono-first.png"/></pagFirst>',
prev = '<pagPrev><img id="goPrev" class="paginadores" src="../images/icons/icono-previous.png"/></pagPrev>',
next = '<pagNext><img id="goNext" class="paginadores" src="../images/icons/icono-next.png" /></pagNext>',
last = '<pagLast><img id="goLast" class="paginadores" src="../images/icons/icono-last.png" /></pagLast>',
stat = '<span id="stat"></span>';
PAGINATOR.append(tappage);
PAGINATOR.append(first);
PAGINATOR.append(prev);
PAGINATOR.append(stat);
PAGINATOR.append(next);
PAGINATOR.append(last);
var TAPPAGE = $('#tabpage'),
FIRST = $('pagFirst'),
PREV = $('pagPrev'),
NEXT = $('pagNext'),
LAST = $('pagLast'),
STAT = $('#stat');
FIRST.click(function() { setPage(rows, 'first'); });
PREV.click(function() { setPage(rows, 'prev'); });
NEXT.click(function() { setPage(rows, 'next'); });
LAST.click(function() { setPage(rows, 'last'); });
if(selectChange){
for(var i=0; i < selectChange.length; i++){
$("#"+selectChange[i]).change(function(select) {
var selected = select.currentTarget.id;
data[selected] = $("#"+select.currentTarget.id ).val();
//------------------
dac_filas(function(totalRows) {
$("#totalRows").val(totalRows);
setPage(rows, 'first');
});
});
}
}
function dac_paginar(page, rows, totalRows, paginas){
//-----------------------
//edita select paginador inicial
$("#tabpage option").remove();
var selected = '';
for(var k=1; k <= paginas; k++){
selected = (page === k) ? 'selected' : '';
TAPPAGE.append("<option value=" + k + " " + selected + ">" + k + "</option>");
}
//------------------------
var data = [],
inicial = 0,
final = 0;
for(var q = 0; q <= totalRows; q++) {
inicial = (page * rows) - (rows - 1);
final = page * rows;
final = (final > totalRows) ? totalRows : final;
data[q] = '(' + inicial + ' - ' + final + ')';
}
STAT.html(data[page]);
}
TAPPAGE.change(function() { setPage(rows, this.value);});
TAPPAGE.select(function() { setPage(rows, 'fill'); });
function dac_selectRegistros(data, url, tableName){
$.ajax({
type : 'POST',
url : url,
data : data,
success : function(result) {
var tabla = result;
$( "#"+tableName ).html(tabla);
},
});
}
//setea número de páginas
function setPage(rows, type) {
var page = parseInt(TAPPAGE.val());
page = (undefined === page || page < 0) ? -1 : page;
var totalRows = parseInt($("#totalRows").val());
if(totalRows === 0){ PAGINATOR.hide();
} else {
PAGINATOR.show();
var paginas = totalRows / rows;
paginas = Math.ceil(paginas);
//----------------
switch (type) {
case 'first':
page = 1;
PREV.hide(); LAST.show();
FIRST.hide(); NEXT.show();
break;
case 'prev':
page = page - 1;
page = (page <= 0) ? 1 : page;
if(page === 1){FIRST.hide(); PREV.hide();}
LAST.show(); NEXT.show();
break;
case 'next':
page = page + 1;
page = (page > paginas) ? paginas : page;
if(page === paginas){LAST.hide(); NEXT.hide();}
FIRST.show(); PREV.show();
break;
case 'last':
page = paginas;
NEXT.hide(); LAST.hide();
FIRST.show(); PREV.show();
break;
case 'fill': //llenar
setPage(rows, 'first');
break;
}
if(paginas === 1){
FIRST.hide();
PREV.hide();
NEXT.hide();
LAST.hide();
TAPPAGE.hide();
} else {
TAPPAGE.show();
}
TAPPAGE.val(page);
//-------------
dac_paginar(page, rows, totalRows, paginas);
for(var k = 0; k < data.length; k++) {
$("#"+data[k]).val();
}
//---------------
}
data.pag = page;
data.rows = rows;
dac_selectRegistros(data, url, tableName);
}
setPage(rows, 'first');
};
}(jQuery, this));<file_sep>/includes/class/class.agenda.php
<?php
require_once('class.PropertyObject.php');
class TAgenda extends PropertyObject {
protected $_tablename = 'agenda';
protected $_fieldid = 'agid';
protected $_fieldactivo = 'agactiva';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'agid';
$this->propertyTable['IdUsr'] = 'agidusr';
//$this->propertyTable['Tipo'] = 'agtipo';
$this->propertyTable['Color'] = 'agcolor';
$this->propertyTable['StartDate'] = 'agstartdate';
$this->propertyTable['EndDate'] = 'agenddate';
$this->propertyTable['Title'] = 'agtitle';
$this->propertyTable['Texto'] = 'agtexto';
$this->propertyTable['Url'] = 'agurl';
$this->propertyTable['Restringido'] = 'agrestringido';
//$this->propertyTable['Start_Date'] = 'ag_startdate';
//$this->propertyTable['End_Date'] = 'ag_enddate';
//$this->propertyTable['RecType'] = 'agrectype'; //day - week
//$this->propertyTable[''] = '';
$this->propertyTable['UsrUpdate'] = 'agusr';
$this->propertyTable['LastUpdate'] = 'adlastupdate';
$this->propertyTable['Activa'] = 'agactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/rendicion/lista.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_max_rendicion = 0;
$_rendID = 0;
//Busco último nro rendición del usuario
$_nro_rendicion = (!isset($_POST['nro_rendicion'])) ? 0 : $_POST['nro_rendicion'];
if (empty($_nro_rendicion)) {
$_nro_rendicion = DataManager::getMaxRendicion($_SESSION["_usrid"]);
if(empty($_nro_rendicion)){$_nro_rendicion = 0;}
}
//Consulto si la rendición fue enviada (activa)
$_rendActiva = 0;
$_rendiciones = DataManager::getRendicion($_SESSION["_usrid"], $_nro_rendicion, '1');
if (count($_rendiciones) > 0) {
$_rendActiva = 1; //Rendición Activa
}
/*************************************************************************************************/
$_button_print = sprintf( "<a id=\"imprimir\" href=\"detalle_rendicion.php?nro_rendicion=%s\" target=\"_blank\" title=\"Imprimir\" >%s</a>", $_nro_rendicion, "<img class=\"icon-print\"/>");
$_button_print2 = sprintf( "<input type=\"submit\" title=\"Imprimir\" value=\"Ver\" target=\"_blank\" />");
$_button_nuevo = sprintf( "<a id=\"open_talonario\" class=\"botones_rend\" title=\"Agregar\">%s</a>", "<img class=\"icon-new\" />");
$_btn_close_popup = sprintf( "<a id=\"close-talonario\" href=\"#\">%s</a>", "<img id=\"close_rend\" src=\"/pedidos/images/icons/icono-close20.png\" border=\"0\" align=\"absmiddle\" />");
$_button_eliminar = sprintf( "<a id=\"eliminar_talonario\" title=\"Eliminar\" href=\"#\" onclick=\"dac_deleteRecibo()\">%s</a>", "<img id=\"close_rend\" class=\"icon-delete\"/>");
$_button_enviar = sprintf( "<a id=\"enviar\" title=\"Enviar Rendicion\" href=\"#\" onclick=\"dac_EnviarRendicion()\">%s</a>", "<img class=\"icon-send\"/>");
//---------------------//
$_btn_anularrendi = sprintf("<input type=\"button\" id=\"btsend\" value=\"Anular\" title=\"Anular Rendición\" onclick=\"javascript:dac_Anular_Rendicion()\"/>");
?>
<script type="text/javascript" src="logica/jquery/jquery.rendicion.js"></script>
<script type="text/javascript" src="logica/jquery/jquery.add.factura.js"></script>
<script type="text/javascript" src="logica/jquery/jquery.add.cheque.js"></script>
<script type="text/javascript" src="logica/jquery/jqueryHeader.js"></script>
<script>
function dac_GrabarEfectivo(ret, dep){
$.ajax({
type: 'GET',
url : 'logica/ajax/update.rendicion.php',
data:{ ret : ret,
dep : dep,
rendicion : <?php echo $_nro_rendicion; ?>
},
beforeSend: function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
$('#box_cargando').css({'display':'none'});
if (result.replace("\n","") === '1'){
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('Los cambios se han guardado');
document.getElementById("total_efectivo").value = document.getElementById("total").value - ret - dep;
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("ERROR! al guardar los Pagos");
}
});
}
function dac_EnviarRendicion(){
$.ajax({
url : 'logica/ajax/enviar.rendicion.php',
data : {nro_rendicion : <?php echo $_nro_rendicion;?>},
type : 'GET',
success : function (result) {
if (result){
if (result.replace("\n","") === '1'){
alert("Rendición enviada.");
javascript:location.reload();
} else {
alert(result);
}
}
},
error: function () {
alert("Error");
}
});
}
</script>
<div class="box_down" style="overflow: auto;">
<fieldset id='box_observacion' class="msg_alerta">
<div id="msg_atencion" align="center"></div>
</fieldset>
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
<?php if ($_SESSION["_usrrol"]!= "M"){
//Consulta última Rendición del usuario
$_rendicion = DataManager::getDetalleRendicion($_SESSION["_usrid"], $_nro_rendicion);
if (count($_rendicion) > 0) {
$readonly = '';?>
<!--div id="muestra-rendicion" style="overflow-x: auto;" align="center"-->
<table id="tabla_rendicion" border="1" class="display">
<thead>
<tr align="left">
<th colspan="7" align="center"><?php echo $_SESSION["_usrname"]; ?></th>
<th colspan="6" align="center"> <?php
echo $_button_nuevo;
if ($_SESSION["_usrrol"]!="M"){echo $_button_print;}?>
<input id="deleterendicion" type="text" hidden /> <?php
if($_rendActiva == 1) {
echo $_button_eliminar;
echo $_button_enviar;
} else { ?>
<b>RENDICIÓN YA ENVIADA</b>
<?php
$readonly = 'readonly';
} ?>
</th>
<th colspan="6">
<form id="f_consultar" action="#" method="post" enctype="multipart/form-data">
<div class="bloque_7">
<br>
<label for="nro_rendicion" >Rendición: </label>
</div>
<div class="bloque_8">
<select id="nro_rendicion" name="nro_rendicion" style="border:none;" onChange="document.getElementById('ver').click()"/> <?php
$_max_rendicion = DataManager::getMaxRendicion($_SESSION["_usrid"]);
for($i = $_max_rendicion; $i > 0; $i--){
if ($i == $_nro_rendicion){ ?>
<option id="<?php echo $i; ?>" name="<?php echo $i; ?>" value="<?php echo $i; ?>" selected><?php echo $i; ?></option><?php
} else { ?>
<option id="<?php echo $i; ?>" name="<?php echo $i; ?>" value="<?php echo $i; ?>"><?php echo $i; ?></option> <?php
}
} ?>
</select>
</div>
<input hidden id="ver" name="ver" Value="Ver" type="submit"/>
</form>
</th>
</tr>
<tr align="center" style="font-weight:bold; background-color:#EAEAEA" height="40px">
<td colspan="3" align="center" style="background-color:#d9ebf4; color:#2D567F" >DATOS CLIENTE</td>
<td colspan="2" align="center" style="background-color:#d9ebf4; color:#2D567F" >RECIBO</td>
<td colspan="2" align="center" style="background-color:#d9ebf4; color:#2D567F" >FACTURA</td>
<td colspan="3" align="center" style="background-color:#d9ebf4; color:#2D567F" >IMPORTE</td>
<td colspan="3" align="center" style="background-color:#d9ebf4; color:#2D567F" >FORMA DE PAGO</td>
<td colspan="4" align="center" style="background-color:#d9ebf4; color:#2D567F" >PAGO POR BANCO</td>
<td colspan="2" align="center" style="background-color:#d9ebf4; color:#2D567F" >OTROS</td>
</tr>
<tr style="font-weight:bold;" height="30px"> <!-- Títulos de las Columnas -->
<td align="center" hidden>Idrend</td>
<td align="center" >Código</td>
<td align="center" >Nombre</td>
<td align="center" >Zona</td>
<td align="center" >Tal</td>
<td align="center" >Nro</td>
<td align="center" >Nro</td>
<td align="center" >Fecha</td>
<td align="center" >Bruto</td>
<td align="center" >Dto</td>
<td align="center" >Neto</td>
<td align="center" >Efectivo</td>
<td align="center" >Transf</td>
<td align="center" >Retención</td>
<td align="center" >Banco</td>
<td align="center" >Número</td>
<td align="center" >Fecha</td>
<td align="center" >Importe</td>
<td align="center" >Observación</td>
<td align="center" >Diferencia</td>
</tr>
</thead>
<tbody>
<input id="ultimocssth" value="1" hidden/>
<input id="ultimorecibo" value="1" hidden/>
<?php
//SACAMOS LOS REGISTROS DE LA TABLA
$total_efectivo = 0;
$id_anterior = 0;
$id_cheque_anterior = 0;
$id_cheque = array();
$idfact_anterior = 0;
$ocultar = 0;
$total_transfer = 0;
$total_retencion = 0;
$total_diferencia = 0;
$total_importe = 0;
foreach ($_rendicion as $k => $_rend){
$_rend = $_rendicion[$k];
$_rendID = $_rend['IDR'];
$_rendCodigo = $_rend['Codigo'];
$_rendNombre = ($_rendCodigo == 0) ? "" : $_rend['Nombre'];
$_rendZona = $_rend['Zona'];
$_rendTal = $_rend['Tal'];
$_rendIDRecibo = $_rend['IDRecibo'];
$_rendRnro = $_rend['RNro'];
$_rendFnro = $_rend['FNro'];
$_rendFactFecha = $_rend['FFecha'];
$_rendBruto = $_rend['Bruto'];
$_rendDto = ($_rend['Dto'] == '0') ? '' : $_rend['Dto'];
$_rendNeto = $_rend['Neto'];
$_rendEfectivo = ($_rend['Efectivo'] == '0.00') ? '' : $_rend['Efectivo'];
$_rendTransf = ($_rend['Transf'] == '0.00') ? '' : $_rend['Transf'];
$_rendRetencion = ($_rend['Retencion'] == '0.00') ? '' : $_rend['Retencion'];
$_rendIDCheque = $_rend['IDCheque'];
$_rendChequeBanco = $_rend['Banco'];
$_rendChequeNro = $_rend['Numero'];
$_rendChequefecha = $_rend['Fecha'];
$_rendChequeImporte = ($_rend['Importe'] == '0.00') ? '' : $_rend['Importe'];
$_rendObservacion = $_rend['Observacion'];
$_rendDiferencia = ($_rend['Diferencia'] == '0.00') ? '' : $_rend['Diferencia'];
$_rendDepositoVend = ($_rend['Deposito'] == '0.00') ? 0 : $_rend['Deposito'];
$_rendRetencionVend = ($_rend['RetencionVend']== '0.00') ? 0 : $_rend['RetencionVend'];
$_estilo = ((($_rendRnro % 2) == 0)? "par" : "impar");
//**************************************************//
//Controlo si repite registros de cheques y facturas//
//**************************************************//
if ($id_anterior == $_rendIDRecibo){
//********************//
// Al hacer el cambio a CUENTAS (que usa clientes en cero)
// debo discriminar los registros con nro cuenta cero y sin observación de ANULADO
//********************//
if($_rendCodigo == 0 && $_rendObservacion == "ANULADO") { } else {
//Busco cheque repetidos en la misma rendición para NO mostrarlos
for($j = 0; $j < (count($id_cheque)); $j++){
if($id_cheque[$j] == $_rendIDCheque){ $ocultar = 1;}
}
if ($ocultar == 1 && $_rendIDCheque != ""){
if ($idfact_anterior != $_rendFnro){
//CASO = 3; //CASO "C" VARIAS facturas - UN CHEQUE.
?><tr id="<?php echo $_rendIDRecibo; ?>" class="<?php echo $_estilo; ?>" onclick="dac_SelectFilaToDelete(<?php echo $_rendIDRecibo; ?>, <?php echo $_rendRnro; ?>)"> <?php
?> <td hidden> <?php echo $_rendID; ?> </td>
<td> <?php echo $_rendCodigo; ?> </td>
<td> <?php echo $_rendNombre; ?> </td>
<td> <?php echo $_rendZona; ?> </td>
<td> <?php echo $_rendTal; ?> </td>
<td> <?php echo $_rendRnro; ?> </td>
<td> <?php echo $_rendFnro; ?> </td>
<td> <?php echo $_rendFactFecha; ?> </td>
<td align="right"> <?php echo $_rendBruto; ?> </td>
<td align="center"> <?php echo $_rendDto; ?> </td>
<td> <?php echo $_rendNeto; ?> </td>
<td align="right"> <?php echo $_rendEfectivo; ?> </td>
<td align="right"> <?php echo $_rendTransf; ?> </td>
<td align="right"> <?php echo $_rendRetencion; ?> </td>
<td hidden> <?php echo $_rendIDCheque; ?> </td>
<td></td> <td></td> <td></td> <td></td> <td></td> <td></td>
<?php
//******************************//
// CALCULOS PARA LOS TOTALES //
$total_efectivo = $total_efectivo + floatval($_rendEfectivo);
$total_transfer = $total_transfer + floatval($_rendTransf);
$total_retencion = $total_retencion + floatval($_rendRetencion);
}
} else {
if ($idfact_anterior == $_rendFnro){
//CASO = 2; //CASO "B". VARIOS CHEQUES - UNA factura
?><tr id="<?php echo $_rendIDRecibo; ?>" class="<?php echo $_estilo; ?>" onclick="dac_SelectFilaToDelete(<?php echo $_rendIDRecibo; ?> , <?php echo $_rendRnro; ?>)"> <?php
?> <td hidden> <?php echo $_rendID; ?> </td>
<td></td> <td><?php //echo $_rendNombre; ?></td>
<td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td>
<td hidden> <?php echo $_rendIDCheque; ?> </td>
<td> <?php echo $_rendChequeBanco; ?> </td>
<td> <?php echo $_rendChequeNro; ?> </td>
<td> <?php echo $_rendChequefecha; ?> </td>
<td align="right"> <?php echo $_rendChequeImporte; ?> </td>
<td></td> <td></td> <?php
} else {
//CASO = 1; //CASO "A" SIN CHEQUES - VARIAS facturas.
?><tr id="<?php echo $_rendIDRecibo; ?>" class="<?php echo $_estilo; ?>" onclick="dac_SelectFilaToDelete(<?php echo $_rendIDRecibo; ?>, <?php echo $_rendRnro; ?>)"> <?php
?> <td hidden> <?php echo $_rendID; ?> </td>
<td> <?php //echo $_rendCodigo ; ?> </td>
<td> <?php //echo $_rendNombre; ?> </td>
<td> <?php //echo $_rendZona; ?> </td>
<td> <?php echo $_rendTal; ?> </td>
<td> <?php echo $_rendRnro; ?> </td>
<td> <?php echo $_rendFnro; ?> </td>
<td> <?php echo $_rendFactFecha; ?> </td>
<td align="right"> <?php echo $_rendBruto; ?> </td>
<td align="center"> <?php echo $_rendDto; ?> </td>
<td align="right"> <?php echo $_rendNeto; ?> </td>
<td align="right"> <?php echo $_rendEfectivo; ?> </td>
<td align="right"> <?php echo $_rendTransf; ?> </td>
<td align="right"> <?php echo $_rendRetencion; ?> </td>
<td hidden> <?php echo $_rendIDCheque; ?> </td>
<td> <?php echo $_rendChequeBanco; ?> </td>
<td> <?php echo $_rendChequeNro; ?> </td>
<td> <?php echo $_rendChequefecha; ?> </td>
<td align="right"> <?php echo $_rendChequeImporte; ?> </td>
<td></td> <td></td> <?php
//**********************************
// CALCULOS PARA LOS TOTALES
$total_efectivo = $total_efectivo + floatval($_rendEfectivo);
$total_transfer = $total_transfer + floatval($_rendTransf);
$total_retencion = $total_retencion + floatval($_rendRetencion);
}
}
} // fin if anulado
} else {
//***********************************
//si cambia el nro de cheque resetea id_cheque y completa toda la fila de datos
//**********************************
unset($id_cheque);
$id_cheque = array();
?>
<tr id="<?php echo $_rendIDRecibo; ?>" class="<?php echo $_estilo; ?>" onclick="dac_SelectFilaToDelete(<?php echo $_rendIDRecibo; ?>, <?php echo $_rendRnro; ?>)">
<td hidden> <?php echo $_rendID; ?> </td>
<td> <?php echo $_rendCodigo ; ?> </td>
<td> <?php echo $_rendNombre; ?> </td>
<td> <?php echo $_rendZona; ?> </td>
<td> <?php echo $_rendTal; ?> </td>
<td> <?php echo $_rendRnro; ?> </td>
<td> <?php echo $_rendFnro; ?> </td>
<td> <?php echo $_rendFactFecha; ?> </td>
<td align="right"> <?php echo $_rendBruto; ?> </td>
<td align="center"> <?php echo $_rendDto; ?> </td>
<td align="right"> <?php echo $_rendNeto; ?> </td>
<td align="right"> <?php echo $_rendEfectivo; ?> </td>
<td align="right"> <?php echo $_rendTransf; ?> </td>
<td align="right"> <?php echo $_rendRetencion; ?> </td>
<td hidden> <?php echo $_rendIDCheque; ?> </td>
<td> <?php echo $_rendChequeBanco; ?> </td>
<td> <?php echo $_rendChequeNro; ?> </td>
<td> <?php echo $_rendChequefecha; ?> </td>
<td align="right"> <?php echo $_rendChequeImporte; ?> </td>
<td> <?php echo $_rendObservacion; ?> </td>
<td align="right"> <?php echo $_rendDiferencia; ?></td> <?php
//**********************************
// CALCULOS PARA LOS TOTALES
$total_efectivo = $total_efectivo + floatval($_rendEfectivo);
$total_transfer = $total_transfer + floatval($_rendTransf);
$total_retencion = $total_retencion + floatval($_rendRetencion);
$total_diferencia = $total_diferencia + floatval($_rendDiferencia);
}
?>
</tr><?php
//**********************************
//CALCULOS PARA TOTALES IMPORTE. Sin discriminar si hay varios cheques
//**********************************
if ($id_cheque_anterior != $_rendIDCheque){
//controla que el cheque no pertenezca a varias facturas
for($j = 0; $j < (count($id_cheque)); $j++){
if($id_cheque[$j] == $_rendIDCheque){ $ocultar = 1; }
}
if ($ocultar != 1){
$total_importe = $total_importe + floatval($_rendChequeImporte);
}
}
//**********************************
if ($_rendIDCheque != ""){
if ($ocultar != 1){$id_cheque[] = $_rendIDCheque;}
}
$ocultar = 0;
$idfact_anterior = $_rendFnro;
$id_anterior = $_rendIDRecibo; //Cierrre de calculo de TOTALES
$id_cheque_anterior = $_rendIDCheque;
} //FIN del FOR Rendicion ?>
<input id="rendicionid" value="<?php echo $_rendID; ?>" hidden/>
</tbody>
<tfoot>
<tr>
<th colspan="10" align="right" style="background-color:#d9ebf4; color:#2D567F;">TOTALES</th>
<th align="right" ><?php
if ($total_efectivo != 0) {
$total = $total_efectivo;
$total_efectivo = $total_efectivo - (floatval($_rendRetencionVend) + floatval($_rendDepositoVend));
?>
<input hidden id="total" name="total" type="text" value="<?php echo $total ?>" readonly/>
<input id="total_efectivo" name="total_efectivo" type="text" style="width:50px; text-align:right; font-weight:bold; border:none" value="<?php echo number_format(round($total_efectivo,2),2); ?>" readonly/> <?php
}?>
</th>
<th align="right" style="font-weight:bold;"><?php if ($total_transfer != 0) {echo "$".$total_transfer;} ?></th>
<th align="right" style="font-weight:bold;"><?php if ($total_retencion != 0) {echo "$".$total_retencion;} ?></th>
<th colspan="3" style="background-color:#d9ebf4;"></th>
<th align="right"><?php if ($total_importe != 0) {echo "$".$total_importe;} ?></th>
<th style="background-color:#d9ebf4;"></th>
<th align="right"><?php if ($total_diferencia != 0) {echo "$".$total_diferencia;} ?></th>
</tr>
<tr>
<th colspan="19" style="height:20px; "></th>
</tr>
<tr >
<th colspan="13" align="right" style="background-color:#d9ebf4; color:#2D567F">
<button id="open-recibo" hidden></button>
<label>Boleta de Depósito: </label>
</th>
<th>
<input id="deposito" name="deposito" type="text" value="<?php if ($_rendDepositoVend != 0) {echo $_rendDepositoVend;} ?>" onChange="dac_GrabarEfectivo(ret.value, deposito.value);" onkeydown="javascript:ControlComa(this.id, this.value);" onkeyup="javascript:ControlComa(this.id, this.value);" <?php echo $readonly; ?> style="border:none; font-weight:bold; text-align:center;" />
</th>
<th align="right" style="background-color:#d9ebf4; color:#2D567F">
<label>Retención: </label>
</th>
<th >
<input id="ret" name="ret" type="text" value="<?php if ($_rendRetencionVend != 0) {echo $_rendRetencionVend;} ?>" onChange="dac_GrabarEfectivo(ret.value, deposito.value);" onkeydown="javascript:ControlComa(this.id, this.value);" onkeyup="javascript:ControlComa(this.id, this.value);" <?php echo $readonly; ?> style="border:none; font-weight:bold; text-align:center;"/>
</th>
<th colspan="3" style="background-color:#d9ebf4;">
</th>
</tr>
</tfoot>
</table>
<!--/div--> <!-- FIN muestra-rendicion --> <?php
} else {
if ($_SESSION["_usrrol"]== "V" || $_SESSION["_usrrol"]== "A") {?>
<table>
<tr align="center">
<th align="center">
<button id="open-recibo" hidden></button>
<?php echo "Nueva Rendición </br>".$_button_nuevo; ?>
</th>
</tr>
</table><?php
}
}
} ?>
</div> <!-- FIN box_bod -->
<!------------------------>
<!-- ADMINISTRAR -->
<?php if ($_SESSION["_usrrol"]== "G" || $_SESSION["_usrrol"]== "A" || $_SESSION["_usrrol"]== "M"){?>
<div class="box_seccion">
<div class="barra">
<h1>Administrar</h1> <hr>
</div> <!-- Fin barra -->
<fieldset>
<legend>Rendiciones</legend>
<form name="fm_anularrendi" method="POST" action="detalle_rendicion.php">
<div class="bloque_7">
<input id="nrorendi_anular" name="nro_anular" type="text" placeholder="* NRO" size="5"/>
</div>
<div class="bloque_3">
<select id="vendedor" name="vendedor"/>
<option>Vendedor...</option> <?php
$vendedores = DataManager::getUsuarios( 0, 0, 1, NULL, '"V"');
if (count($vendedores)) {
foreach ($vendedores as $k => $vend) { ?>
<option id="<?php echo $vend["unombre"]; ?>" value="<?php echo $vend["uid"]; ?>"><?php echo $vend["unombre"]; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_5"> <?php echo $_button_print2; ?> </div>
<?php if($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="M"){ ?>
<div class="bloque_5">
<?php echo $_btn_anularrendi; ?>
</div>
<?php } ?>
<hr>
</form>
</fieldset>
<?php
$recAnuladosPendientes = DataManager::getTalonariosIncompletos();
if (count($recAnuladosPendientes)) { ?>
<fieldset>
<legend> <?php echo count($recAnuladosPendientes); ?> Talonarios Incompletos</legend>
<div class="desplegable">
<table>
<thead>
<tr>
<td>Talonario</td>
<td>Recibo</td>
<td>Usuario</td>
</tr>
</thead>
<body><?php
foreach ($recAnuladosPendientes as $k => $anulado) { ?>
<tr>
<td ><?php echo $anulado["rectalonario"]; ?></td>
<td ><?php echo $anulado["recnro"]; ?></td>
<td ><?php echo $anulado["unombre"]; ?></td>
</tr>
<?php
} ?>
</body>
</table>
</div>
</fieldset>
<?php } ?>
<?php
$recAnuladosPendientes = DataManager::getRecibosAnuladosPendientes();
if (count($recAnuladosPendientes)) { ?>
<fieldset>
<legend> <?php echo count($recAnuladosPendientes); ?> Recibos ANULADOS de talonarios incompletos </legend>
<div class="desplegable">
<table>
<thead>
<tr>
<td>Talonario</td>
<td>Recibo</td>
<td>Usuario</td>
</tr>
</thead>
<body><?php
foreach ($recAnuladosPendientes as $k => $anulado) { ?>
<tr>
<td ><?php echo $anulado["rectalonario"]; ?></td>
<td ><?php echo $anulado["recnro"]; ?></td>
<td ><?php echo $anulado["unombre"]; ?></td>
</tr>
<?php
} ?>
</body>
</table>
</div>
</fieldset>
<?php } ?>
</div> <!-- Fin boxseccion-->
<?php }?>
<div id="popup-flotante"> <!-- INICIO popup-flotante POPUP TALONARIO DE RECIBOS-->
<div id="popup-talonario"> <!-- INICIO popup-talonario-->
<fieldset id='box_observacion2' class="msg_alerta">
<div id="msg_atencion2" align="center"></div>
</fieldset>
<fieldset id='box_error2' class="msg_error">
<div id="msg_error2" align="center"></div>
</fieldset>
<fieldset id='box_cargando2' class="msg_informacion">
<div id="msg_cargando2" align="center"></div>
</fieldset>
<fieldset id='box_confirmacion2' class="msg_confirmacion">
<div id="msg_confirmacion2" align="center"></div>
</fieldset>
<div class="content-popup-talonario"> <!-- INICIO content-popup-talonario-->
<div class="close-talonario"> <?php echo $_btn_close_popup; ?> </div>
<form id="fm_nvo_recibo" name="fm_nvo_recibo" method="POST" enctype="multipart/form-data">
<input id="rendid" type="text" name="rendid" value="<?php echo $_rendID;?>" hidden/>
<!-- Recibo -->
<div class="content-popup-recibo">
<div class="bloque_7">
<input id="nro_tal" name="nro_tal" type="text" placeholder="Talonario" style="text-align:center;"/>
</div>
<div class="bloque_7">
<input id="nro_rec" name="nro_rec" type="text" placeholder="Recibo" style="text-align:center"/>
</div>
<div class="bloque_8">
<input id="ir" type="button" name="ir" value="+" title="Abrir Recibo" onClick="dac_BuscarRecibo(nro_rec.value, nro_tal.value);" />
</div>
<div class="bloque_7">
<input id="nvo_tal" type="button" name="nvo_tal" value="Nuevo Talonario" onClick="dac_NuevoTalonario(nro_tal.value);"/>
</div>
<div class="bloque_8">
<input id="anular" type="button" name="anular" value="A" onClick="dac_AnularRecibo(rendid.value, nro_rend.value, nro_tal.value, nro_rec.value);"/>
</div>
<hr>
</div><!-- FIN rec_recuadro -->
<div id="popup-recibo"> <!-- INICIO popup-recibo-->
<div class="content-popup-recibo" align="center"><!-- Número de Rendición-->
<div class="bloque_3">
<b>Rendición de Cobranza Número:</b>
</div>
<div class="bloque_8">
<input id="nro_rend" name="nro_rend" type="text" size="2" style="font-weight:bold; text-align:center; border:none;" value="<?php if ($_nro_rendicion == "") {echo 1;} else { echo $_nro_rendicion; } ?>" readonly/>
</div>
<div class="bloque_8">
<input id="nvacbza" type="button" name="nvacbza" value="+" onClick="javascript:dac_NuevaRendicion('<?php echo $_max_rendicion; ?>')" />
</div>
<hr>
</div><!--FIN número de Rendición -->
<div class="content-popup-recibo"> <!-- CONTENIDO facturas-->
<button id="close-recibo" hidden></button>
<div class="bloque_1">
<label>Factura</label>
</div>
<div id="fact_1">
<div class="bloque_7">
<label for="nro_factura">Nro.</label>
<input id="nro_factura1" name="nro_factura[]" type="text" maxlength="10" onBlur="dac_ValidarNumero(this.value, this.id)"/>
</div>
<div class="bloque_7">
<label for="fecha_factura">Fecha</label>
<input id="fecha_factura1" name="fecha_factura[]" type="text" size="10" maxlength="10" onKeyUp="javascript:dac_ValidarCampoFecha(this.id, this.value, 'KeyUp');" onBlur="javascript:dac_ValidarCampoFecha(this.id, this.value, 'Blur');" placeholder="dd-mm-aaaa"/>
</div>
<div class="bloque_5">
<label>Cuenta</label>
<select id="nombrecli1" name="nombrecli[]"/>
<option > Seleccione Cuenta... </option> <?php
$_clientes = DataManager::getCuentas(0, 0, 1, 1, "'C'", $_SESSION["_usrzonas"], 2);
if (count($_clientes)) {
foreach ($_clientes as $k => $_cliente) {
$_cliid = $_cliente["ctaidcuenta"];
$_clinombre = $_cliente["ctanombre"];
?>
<option id="<?php echo $_clinombre; ?>" name="<?php echo $_clinombre; ?>" value=<?php echo "'".$_cliid."-".$_clinombre."'"; ?> ><?php echo $_clinombre." (".$_cliid.")"; ?></option>
<?php
}
}
?>
<option id="otro" name="otro" value="999999-otro">Otro Cliente...</option>
</select>
</div>
<div class="bloque_7">
<label for="importe_bruto"> A pagar</label>
<input id="importe_bruto1" name="importe_bruto[]" type="text" onBlur="dac_ValidarNumero(this.value, this.id)"/>
</div>
<div class="bloque_7">
<label for="pago_efectivo">Efectivo</label>
<input id="pago_efectivo1" name="pago_efectivo[]" type="text" onBlur="dac_ValidarNumero(this.value, this.id)"/>
</div>
<div class="bloque_7">
<label for="importe_dto"> % DTO.</label>
<input id="importe_dto1" name="importe_dto[]" type="text" onBlur="dac_ValidarNumero(this.value, this.id)" maxlength="2"/>
</div>
<div class="bloque_7">
<label for="pago_transfer">Transfer</label>
<input id="pago_transfer1" name="pago_transfer[]" type="text" onBlur="dac_ValidarNumero(this.value, this.id)"/>
</div>
<div class="bloque_7">
<label for="importe_neto">Neto</label>
<input id="importe_neto1" name="importe_neto[]" type="text" style="background-color:#CCC;" readonly/>
</div>
<div class="bloque_7">
<label for="pago_retencion">Retención</label>
<input id="pago_retencion1" name="pago_retencion[]" type="text" onBlur="dac_ValidarNumero(this.value, this.id)"/>
</div>
<div class="bloque_7">
<br>
<input id="btnuevo_1" class="btn_plus" type="button" value="+">
</div>
<hr class="hr-line">
</div> <!--FIN DATOS fact-->
</div> <!--FIN CONTENIDO facturas-->
<div class="content-popup-recibo"><!--CONTENIDO cheques--><!--DATOS DE BANCO que se clonan -->
<div class="bloque_1">
<label>Cheque</label>
</div>
<hr>
<div id="bank_1">
<div class="bloque_1">
<label>Banco</label>
<select id="pagobco_nombre1" name="pagobco_nombre[]" />
<option>Seleccione Banco...</option> <?php
$_bancos = DataManager::getBancos();
if ($_bancos) {
foreach ($_bancos as $k => $_bank){
$_bank = $_bancos[$k];
$_bconombre = $_bank["nombre"];
?> <option id="<?php echo $_bconombre; ?>" value=<?php echo "'".$_bconombre."'"; ?> > <?php echo $_bconombre; ?> </option> <?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<input id="pagobco_nrocheque1" name="pagobco_nrocheque[]" type="text" placeholder="<NAME>" onBlur="dac_ValidarNumero(this.value, this.id)"/>
</div>
<div class="bloque_7">
<input id="bco_fecha1" name="bco_fecha[]" type="text" placeholder="Fecha" maxlength="10" onKeyUp="javascript:dac_ValidarCampoFecha(this.id, this.value, 'KeyUp');" onBlur="javascript:dac_ValidarCampoFecha(this.id, this.value, 'Blur');"/>
</div>
<div class="bloque_7">
<input id="pagobco_importe1" name="pagobco_importe[]" type="text" placeholder="Importe" onBlur="dac_ValidarNumero(this.value, this.id)"/>
</div>
<div class="bloque_8">
<input id="boton_1" class="btn_checque_plus" type="button" value="+"/>
</div>
<hr class="hr-line">
</div>
</div> <!--FIN CONTENIDO cheques-->
<div class="content-popup-recibo" align="center"> <!--otros DATOS-->
<div class="bloque_5">
<div class="rec-contenido">
<textarea id="observacion" name="observacion" type="text" style="resize:none;" cols="16" rows="10" placeholder="Observación"></textarea>
</div>
</div>
<div class="bloque_5">
<div class="rec-contenido">
<input id="diferencia" name="diferencia" type="text" placeholder="Diferencia" style="background-color:#CCC;" onBlur="dac_ValidarNumero(this.value, this.id)" readonly/>
</div>
</div>
<hr>
</div> <!-- FIN otros DATOS-->
<div class="bloque_5"> </div>
<div class="bloque_7">
<input id="enviar_form" name="enviar_form" type="button" value="Enviar" title="Agregar Registro" onClick="dac_EnviarRecibo();"/>
</div>
<div class="bloque_7">
<input id="close-talonario" type="button" name="cerrar" value="Cancelar" onClick="document.getElementById('close-talonario').click();"/>
</div>
<hr>
</div><!-- fin popup-recibo-->
</form>
</div> <!-- FIN content-popup-talonario -->
</div><!-- FIN popup-talonario -->
</div><!-- FIN POPUP popup-flotante --> <file_sep>/movimientos/logica/ajax/getMovimientos.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
//---------------------------
/*$empresa = (isset($_POST['empselect'])) ? $_POST['empselect'] : NULL;
$activos = (isset($_POST['actselect'])) ? $_POST['actselect'] : NULL;
$tipo = (isset($_POST['tiposelect'])) ? $_POST['tiposelect']: NULL;*/
$pag = (isset($_POST['pag'])) ? $_POST['pag'] : NULL;
$_LPP = (isset($_POST['rows'])) ? $_POST['rows'] : NULL;
//----------------------------
//$tipo = ($tipo == '0') ? NULL : "'".$tipo."'";
$movimientos = DataManager::getMovimientos($pag, $_LPP); //, $activos, $empresa, NULL, NULL, $tipo
$rows = count($movimientos);
echo "<table id='tblMovimientos'>";
if ($rows) {
echo "<thead><tr><th scope='colgroup'>Id</th><th scope='colgroup'>Origen</th><th scope='colgroup'>Id Origen</th><th scope='colgroup'>Transacción</th><th scope='colgroup'>Operación</th><th scope='colgroup'>Fecha</th><th scope='colgroup'>Usuario</th>";
echo "</tr></thead>";
echo "<tbody>";
for( $k=0; $k < $_LPP; $k++ ) {
if ($k < $rows) {
$mov = $movimientos[$k];
$id = $mov['movid'];
$operacion = $mov['movoperacion'];
$transaccion= $mov['movtransaccion'];
$origen = $mov['movorigen'];
$origenId = $mov['movorigenid'];
$fecha = dac_invertirFecha( $mov['movfecha'] );
$usrId = $mov['movusrid'];
$usuario = DataManager::getUsuario('unombre', $usrId);
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class='".$clase."'>";
echo "<td>".$id."</td><td >".$origen."</td><td >".$origenId."</td><td >".$transaccion."</td><td>".$operacion."</td><td>".$fecha."</td><td>".$usuario."</td>";
echo "</tr>";
}
}
echo "</table> </div>";
} else {
echo "<tbody>";
echo "<thead><tr><th colspan='7' align='center'>No hay registros relacionados</th></tr></thead>"; exit;
}
echo "</tbody></table>";
?><file_sep>/proveedores/fechaspago/logica/jquery/jqueryFooter.js
$(document).ready(function() {
"use strict";
$("#guardar_pagos").click(function (event) {
var idfact = [];
var empresa = [];
var idprov = [];
var nombre = [];
var plazo = [];
var fechavto = [];
var tipo = [];
var factnro = [];
var fechacbte = [];
var saldo = [];
var fechapago = [];
var observacion = [];
$('input[name="idfact[]"]:text').each(function() { idfact = idfact+"-"+$(this).val();});
$('input[name="empresa[]"]:text').each(function() { empresa = empresa+"-"+$(this).val();});
$('input[name="idprov[]"]:text').each(function() { idprov = idprov+"-"+$(this).val();});
$('input[name="nombre[]"]:text').each(function() { nombre = nombre+"-"+$(this).val();});
$('input[name="plazo[]"]:text').each(function() { plazo = plazo+"-"+$(this).val();});
$('input[name="fechavto[]"]:text').each(function() { fechavto = fechavto+"-"+$(this).val();});
$('input[name="tipo[]"]:text').each(function() { tipo = tipo+"-"+$(this).val();});
$('input[name="factnro[]"]:text').each(function() { factnro = factnro+"-"+$(this).val();});
$('input[name="fechacbte[]"]:text').each(function() { fechacbte = fechacbte+"-"+$(this).val();});
$('input[name="saldo[]"]:text').each(function() { saldo = saldo+"-"+$(this).val();});
$('input[name="fechapago[]"]:text').each(function() { fechapago = fechapago+"-"+$(this).val();});
$('input[name="observacion[]"]:text').each(function() { observacion = observacion+"-"+$(this).val();});
var fecha = $('input[name="fecha"]:text').val();
$.ajax({
type : "POST",
cache : false,
url : "/pedidos/proveedores/fechaspago/logica/ajax/update.pagos.php",
data : { fecha : fecha,
idfact : idfact,
empresa : empresa,
idprov : idprov,
nombre : nombre,
plazo : plazo,
fechavto : fechavto,
tipo : tipo,
factnro : factnro,
fechacbte : fechacbte,
saldo : saldo,
fechapago : fechapago,
observacion : observacion },
beforeSend: function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function(result) {
if(result){
$('#box_cargando').css({'display':'none'});
if(result.replace("\n","") === '1'){
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('Los cambios se han guardado');
location.reload();
}else{
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("ERROR! al guardar los Pagos");
}
});
});
});
$(function(){ "use strict"; $('#importar').click(ImportarFacturasProveedores); });
// archivo de liquidacion //
function ImportarFacturasProveedores(){
"use strict";
var archivos = document.getElementById("file");
var archivo = archivos.files;
if(archivo.length !== 0){
var fecha = document.getElementById("f_fecha").value;
archivos = new FormData();
archivos.append('archivo',archivo);
for(var i=0; i<archivo.length; i++){
archivos.append('archivo'+i,archivo[i]); //Añadimos cada archivo al arreglo con un indice direfente
}
archivos.append('fecha', fecha);
$.ajax({
url : '/pedidos/proveedores/fechaspago/logica/importar_facturas.php',
type : 'POST',
contentType : false,
data : archivos,
processData : false,
cache : false,
beforeSend : function () {
alert("Se proceder\u00e1 a importar el archivo de facturas de pago");
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
afterSend : function() {
$('#box_cargando').css({'display':'none'});
},
success : function(result) {
if(result){
$('#box_cargando').css({'display':'none'});
if(!isNaN(parseInt(result))){
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('Archivo Subido correctamente con '+result+' registros');
location.reload();
}else{
$('#box_error').css({'display':'block'});
$("#msg_error").html(result);
}
}
},
}).fail( function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status === 0) {
alert('Not connect: Verify Network.');
} else if (jqXHR.status === 404) {
alert('Requested page not found [404]');
} else if (jqXHR.status === 500) {
alert('Internal Server Error [500].');
} else if (textStatus === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (textStatus === 'timeout') {
alert('Time out error.');
} else if (textStatus === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error: ' + jqXHR.responseText);
}
});
} else {
alert("Debe adjuntar un archivo para importar.");
}
}
g_globalObject = new JsDatePick({
useMode: 2,
isStripped: false, //borde gris
yearsRange: new Array (1971,2100),
target: "fechaDesde",
dateFormat:"%d-%M-%Y"
});
g_globalObject = new JsDatePick({
useMode: 2,
isStripped: false, //borde gris
yearsRange: new Array (1971,2100),
target: "fechaHasta",
dateFormat:"%d-%M-%Y"
});
g_globalObject = new JsDatePick({
useMode: 2,
isStripped: false, //borde gris
yearsRange: new Array (1971,2100),
//limitToToday: true,
target: "f_fecha",
dateFormat:"%d-%M-%Y"
});
g_globalObject.setOnSelectedDelegate(function(){
"use strict";
var obj = g_globalObject.getSelectedDay();
console.log(obj);
var fecha = ("0" + obj.day).slice (-2) + "-" + ("0" + obj.month).slice (-2) + "-" + obj.year;
document.getElementById("f_fecha").value = fecha;
var url = window.location.origin+'/pedidos/proveedores/fechaspago/index.php?fecha=' + fecha;
document.location.href=url;
});
$("#btnExporHistorial").click(function () {
"use strict";
var fechaDesde = $('#fechaDesde').val();
var fechaHasta = $('#fechaHasta').val();
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
if(fechaDesde === '' || fechaHasta === ''){
$('#box_error').css({'display':'block'});
$("#msg_error").html('Indique las fechas de descarga.');
} else {
if( (new Date(fechaDesde).getTime() > new Date(fechaHasta).getTime())){
$('#box_error').css({'display':'block'});
$("#msg_error").html('La fecha "Desde" debe ser menor a la fecha "Hasta"');
} else {
var url = "logica/exportar.historial.php?desde="+fechaDesde+"&hasta="+fechaHasta;
$("body").append("<iframe src='" + url + "' style='display: none;' ></iframe>");
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('Archivo exportado correctamente.');
}
}
});<file_sep>/usuarios/password/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="P" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_sms = empty($_GET['sms']) ? 0 : $_GET['sms'];
$_uid = $_SESSION["_usrid"];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/logout.php': $_REQUEST['backURL'];
if ($_sms) {
$_uusuario = $_SESSION['s_usuario'];
$_upassword = $_SESSION['s_password'];
$_unewpassword = $_SESSION['s_newpassword'];
$_unewpasswordbis = $_SESSION['s_newpasswordbis'];
switch ($_sms) {
case 1: $_info = "Usuario erróneo o inexistente"; break;
case 2: $_info = "Ingrese la clave actual"; break;
case 3: $_info = "La clave del usuario es incorrecta"; break; //Habría que controlar la cantidad de intentos para desloguearlo
case 4: $_info = "Complete la nueva clave"; break;
case 5: $_info = "Repita la nueva clave"; break;
case 6: $_info = "La nueva clave no coincide"; break;
case 7: $_info = "Error en el e-mail. Confirme con la empresa su cuenta de correo"; break;
case 8: $_info = "Su Contraseña ha sido modificada"; break;
} // mensaje de error
} else {
if ($_uid) {
$_usuario = DataManager::newObjectOfClass('TUsuario', $_uid);
$_uusuario = "";
$_unewpassword = "";
$_unewpasswordbis = "";
}
}
$_button = sprintf("<input type=\"submit\" id=\"f_enviar\" name=\"_accion\" value=\"Cambiar\"/>");
$_action = "/pedidos/usuarios/password/logica/update.password.php?backURL=".$backURL;
?>
<script type="text/javascript">
function dac_MostrarSms(sms){
document.getElementById('box_error').style.display = 'none';
if(sms){
if(sms > 0 && sms < 8){
document.getElementById('box_error').style.display = 'block';
document.getElementById('box_confirmacion').style.display = 'none';
} else {
document.getElementById('box_confirmacion').style.display = 'block';
document.getElementById('box_error').style.display = 'none';
window.setTimeout(window.location="/pedidos/login/index.php", 8000);
}
}
}
</script>
<div class="box_body">
<form id="fm_cambiar_clave" name="fm_cambiar_clave" method="post" action="<?php echo $_action;?>">
<fieldset>
<legend> Introduzca la nueva clave</legend>
<div class="bloque_1" align="center">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"> <?php echo $_info; ?> </div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"><?php echo $_info;?></div>
</fieldset>
<?php
echo "<script>";
echo "javascript:dac_MostrarSms(".$_sms.")";
echo "</script>";
?>
</div>
<div class="bloque_7">
<label for="uusuario">Usuario</label>
<input name="uusuario" id="uusuario" type="text" maxlength="10" value="<?php echo @$_uusuario;?>"/>
</div>
<div class="bloque_7">
<label for="upassword">Clave actual</label>
<input name="upassword" id="upassword" type="password" maxlength="10" value="<?php echo @$_upassword;?>"/>
</div>
<div class="bloque_7">
<label for="unewpassword">Nueva Clave</label>
<input name="unewpassword" id="unewpassword" type="password" maxlength="10" value="<?php echo @$_unewpassword;?>"/>
</div>
<div class="bloque_7">
<label for="unewpasswordbis">Repita Nueva Clave</label>
<input name="unewpasswordbis" id="unewpasswordbis" type="password" maxlength="10" value="<?php echo @$_unewpasswordbis;?>"/>
</div>
<div class="bloque_7"> <?php echo $_button;?></div>
</fieldset>
</form>
</div> <!-- boxbody --><file_sep>/usuarios/logica/update.usuario.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_uid = empty($_REQUEST['uid']) ? 0 : $_REQUEST['uid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/usuarios/': $_REQUEST['backURL'];
$_nombre = $_POST['unombre'];
$_usuario = $_POST['uusuario'];
$_password = $_POST['<PASSWORD>'];
$_passwordbis = $_POST['<PASSWORD>'];
$_dni = $_POST['udni'];
$_email = $_POST['uemail'];
$_rol = $_POST['urol'];
$_obs = $_POST['uobs'];
$_SESSION['s_nombre'] = $_nombre;
$_SESSION['s_email'] = $_email;
$_SESSION['s_usuario'] = $_usuario;
$_SESSION['s_password'] = <PASSWORD>;
$_SESSION['s_passwordbis'] = <PASSWORD>;
$_SESSION['s_dni'] = $_dni;
$_SESSION['s_rol'] = $_rol;
$_SESSION['s_obs'] = $_obs;
if (empty($_nombre)) {
$_goURL = sprintf("/pedidos/usuarios/editar.php?uid=%d&sms=%d", $_uid, 1);
header('Location:' . $_goURL);
exit;
}
if (!empty($_usuario)) {
$_loginid = DataManager::getIDByField('TUsuario','ulogin', $_usuario);
if ($_loginid && ($_loginid != $_uid)) {
$_goURL = sprintf("/pedidos/usuarios/editar.php?uid=%d&sms=%d", $_uid, 2);
header('Location:' . $_goURL);
exit;
}
} else {
$_goURL = sprintf("/pedidos/usuarios/editar.php?uid=%d&sms=%d", $_uid, 2);
header('Location:' . $_goURL);
exit;
}
if ((0 != strcmp($_password,$_passwordbis)) || empty($_password)) {
$_goURL = sprintf("/pedidos/usuarios/editar.php?uid=%d&sms=%d", $_uid, 3);
header('Location:' . $_goURL);
exit;
}
if (empty($_dni) || !is_numeric($_dni)) {
$_goURL = sprintf("/pedidos/usuarios/editar.php?uid=%d&sms=%d", $_uid, 4);
header('Location:' . $_goURL);
exit;
} else {
$_loginid = DataManager::getIDByField('TUsuario','udni', $_dni);
if ($_loginid && ($_loginid != $_uid)) {
$_goURL = sprintf("/pedidos/usuarios/editar.php?uid=%d&sms=%d", $_uid, 4);
header('Location:' . $_goURL);
exit;
}
}
/*
if (empty($_dni) || !is_numeric($_dni)) {
$_goURL = sprintf("/pedidos/usuarios/editar.php?uid=%d&sms=%d", $_uid, 4);
header('Location:' . $_goURL);
exit;
}
*/
if (!preg_match( "/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,4})$/", $_email )) {
$_goURL = sprintf("/pedidos/usuarios/editar.php?uid=%d&sms=%d", $_uid, 5);
header('Location:' . $_goURL);
exit;
}
//Si ya existe una clave, la lee de la ddbb cifrada y al querer grabar la vuelve a cifrar dando errores.
//Por eso mismo hago el siguiente control previo.
if (strlen($_password) <= 15){$_password = md5($_password);}
$_usrobject = ($_uid) ? DataManager::newObjectOfClass('TUsuario', $_uid) : DataManager::newObjectOfClass('TUsuario');
$_usrobject->__set('Nombre' , $_nombre);
$_usrobject->__set('Email' , $_email);
$_usrobject->__set('Login' , $_usuario);
$_usrobject->__set('Clave' , $_password);
$_usrobject->__set('Dni' , $_dni);
$_usrobject->__set('Rol' , $_rol);
$_usrobject->__set('Obs' , $_obs);
if ($_uid) {
$ID = DataManager::updateSimpleObject($_usrobject);
} else {
$_usrobject->__set('ID' , $_usrobject->__newID());
$_usrobject->__set('Activo' , 1);
$ID = DataManager::insertSimpleObject($_usrobject);
}
unset($_SESSION['s_nombre']);
unset($_SESSION['s_email'] );
unset($_SESSION['s_usuario']);
unset($_SESSION['s_password']);
unset($_SESSION['s_passwordbis']);
unset($_SESSION['s_dni']);
unset($_SESSION['s_rol']);
unset($_SESSION['s_obs']);
header('Location:' . $backURL);
?><file_sep>/pedidos/prefacturados/lista.php
<?php
$_LPP = 5000;
$_pag = 1;
if ($_SESSION["_usrrol"] == "A" || $_SESSION["_usrrol"] == "M" || $_SESSION["_usrrol"] == "G" ){ ?>
<div class="box_down" align="center"> <!-- datos -->
<div class="barra">
<div class="bloque_3" align="left">
<h1>Pre-Facturados</h1>
</div>
<div class="bloque_7" align="right">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn" type="text" value="tblPrefacturados" hidden/>
</div>
<hr>
</div> <!-- Fin Barra -->
<div class="lista_super">
<table id="tblPrefacturados" >
<thead>
<tr>
<td scope="col" width="20%" height="18">Fecha</td>
<td scope="col" width="20%">Pedido</td>
<td scope="col" width="50%">Cliente</td>
<td colspan="1" scope="colgroup" width="10%" align="center">Acciones</td>
</tr>
</thead>
<?php
$dateFrom = new DateTime('now');
$dateFrom ->modify('-1 month');
$_pedidos_facturados = DataManager::getPedidos(NULL, 0, NULL, NULL, NULL, NULL, $_pag, $_LPP, $dateFrom->format('Y-m-d'));
if ($_pedidos_facturados){
$_nro = 0;
$_fila = 0;
foreach ($_pedidos_facturados as $k => $_pedidoFact) {
$fecha = $_pedidoFact["pfechapedido"];
$_nropedido = $_pedidoFact["pidpedido"];
$_idemp = $_pedidoFact["pidemp"];
$_cliente = $_pedidoFact["pidcliente"];
$_nombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $_cliente, $_idemp);
if($_nro != $_nropedido) {
$_fila = $_fila + 1;
$_detalle = sprintf( "<a href=\"../detalle_pedido.php?nropedido=%d&backURL=%s\" target=\"_blank\" title=\"detalle pedido\">%s</a>", $_nropedido, $_SERVER['PHP_SELF'], "<img class=\"icon-detail\"/>");
echo sprintf("<tr class=\"%s\">", ((($_fila % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td>", $fecha, $_nropedido, $_nombre, $_detalle);
echo sprintf("</tr>");
}
$_nro = $_nropedido;
}
} else { ?>
<tr>
<td scope="colgroup" colspan="4" height="25" align="center">No hay pedidos Pre-Facturados</td>
</tr>
<?php
}
?>
</table>
</div> <!-- Fin lista -->
</div> <!-- Fin datos -->
<hr>
<?php } ?>
<?php if ($_SESSION["_usrrol"] == "A" || $_SESSION["_usrrol"] == "M" || $_SESSION["_usrrol"] == "V" || $_SESSION["_usrrol"] == "G"){ ?>
<div class="box_down"> <!-- datos -->
<div class="barra">
<div class="bloque_3">
<h1>Mis Pedidos Pre-Facturados</h1>
</div>
<div class="bloque_7" align="right">
<input id="txtBuscar2" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn2" type="text" value="tblMisPrefacturados" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblMisPrefacturados" >
<thead>
<tr>
<td scope="col" width="20%" height="18">Fecha</td>
<td scope="col" width="20%">Pedido</td>
<td scope="col" width="50%">Cliente</td>
</tr>
</thead>
<?php
$dateFrom = new DateTime('now');
$dateFrom ->modify('-3 month');
$_pedidos_facturados = DataManager::getPedidos($_SESSION["_usrid"], 0, NULL, NULL, NULL, NULL, $_pag, $_LPP, $dateFrom->format('Y-m-d'));
if ($_pedidos_facturados){
$_nro = 0;
$_fila = 0;
foreach ($_pedidos_facturados as $k => $_pedidoFact) {
$fecha = $_pedidoFact["pfechapedido"];
$_nropedido = $_pedidoFact["pidpedido"];
$_idemp = $_pedidoFact["pidemp"];
$_cliente = $_pedidoFact["pidcliente"];
$_nombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $_cliente, $_idemp);
if($_nro != $_nropedido) {
$_fila = $_fila + 1;
echo sprintf("<tr class=\"%s\" onclick=\"window.open('../detalle_pedido.php?nropedido=%s')\" style=\"cursor:pointer;\" target=\"_blank\" title=\"Detalle\">", ((($_fila % 2) == 0)? "par" : "impar"), $_nropedido);
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td>", $fecha, $_nropedido, $_nombre);
echo sprintf("</tr>");
}
$_nro = $_nropedido;
}
} else {
?>
<tr>
<td scope="colgroup" colspan="3" height="25" align="center">No hay pedidos Pre-Facturados</td>
</tr>
<?php
}
?>
</table>
</div> <!-- Fin lista -->
</div> <!-- Fin datos -->
<?php } ?>
<hr><file_sep>/droguerias/logica/eliminar.drogueriaRelacionada.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$drogTId = empty($_REQUEST['drogtid']) ? 0 : $_REQUEST['drogtid'];
if ($drogTId) {
//eliminar cuenta relacionada
$drogObject = DataManager::newObjectOfClass('TDrogueria', $drogTId);
$drogObject->__set('ID', $drogTId );
DataManagerHiper::deleteSimpleObject($drogObject, $drogTId);
DataManager::deleteSimpleObject($drogObject);
}
echo "1"; exit;
?>
<file_sep>/includes/class/class.abm.php
<?php
require_once('class.PropertyObject.php');
class TAbm extends PropertyObject {
protected $_tablename = 'abm';
protected $_fieldid = 'abmid';
protected $_fieldactivo = 'abmactivo';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'abmid';
$this->propertyTable['Drogueria'] = 'abmdrogid';
$this->propertyTable['Tipo'] = 'abmtipo';
$this->propertyTable['Mes'] = 'abmmes';
$this->propertyTable['Anio'] = 'abmanio';
$this->propertyTable['Articulo'] = 'abmartid';
$this->propertyTable['Descuento'] = 'abmdesc';
$this->propertyTable['Plazo'] = 'abmcondpago';
$this->propertyTable['Diferencia'] = 'abmdifcomp'; //Diferencia de compensación
$this->propertyTable['Activo'] = 'abmactivo';
$this->propertyTable['Empresa'] = 'abmidempresa';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
public function __getClassVars() {
$_classname = get_class($this);
foreach ($this->propertyTable as $k => $v) {
$array[] = $k;
}
return $array;
}
} ?><file_sep>/soporte/tickets/nuevo/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$tkidsector = empty($_REQUEST['tkidsector']) ? 0 : $_REQUEST['tkidsector'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/soporte/tickets/nuevo/': $_REQUEST['backURL'];
if($tkidsector){
$sectores = DataManager::getTicketSector();
foreach( $sectores as $k => $sec ) {
$idSec = $sec['tksid'];
if($tkidsector == $idSec){
$titulo = $sec['tksnombre'];
$motivos = DataManager::getTicketMotivos();
if (count($motivos)) {
foreach ($motivos as $j => $mot) {
$sector = $mot['tkmotidsector'];
if($tkidsector == $sector){
$idMotivo[] = $mot['tkmotid'];
$motivo[] = $mot['tkmotmotivo'];
}
}
}
}
}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "soporte";
$_subsection = "ticket";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<div class="box_body">
<form id="fmTicket" method="post" enctype="multipart/form-data">
<fieldset>
<legend><?php echo $titulo ?></legend>
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<input type="hidden" name="tkidsector" value="<?php echo $tkidsector;?>" />
<div class="bloque_5">
<label for="tkmotivo">Motivo del Servicio</label>
<select name="tkmotivo" >
<option id="0" value="0" selected></option> <?php
foreach ($motivo as $k => $mot) { ?>
<option id="<?php echo $idMotivo[$k]; ?>" value="<?php echo $idMotivo[$k]; ?>"><?php echo $mot; ?></option><?php
} ?>
</select>
</div>
<div class="bloque_6">
<input id="imagen" name="imagen" class="file" type="file"/>
</div>
<div class="bloque_8">
<?php $urlSend = '/pedidos/soporte/tickets/nuevo/logica/update.ticket.php';?>
<a id="btnSend" title="Enviar">
<img class="icon-send" onclick="javascript:dac_sendForm(fmTicket, '<?php echo $urlSend;?>');"/>
</a>
</div>
<div class="bloque_1">
<label for="tkmensaje">Mensaje</label>
<textarea name="tkmensaje" type="text"/></textarea>
</div>
</fieldset>
</form>
</div> <!-- FIN box_body -->
<hr>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/cuentas/logica/jquery/getListaPrecios.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php");
$empresa = $_GET['empresa'];
$idCatComerc = $_GET['idCatComerc'];
$datosJSON;
//Buscar las condiciones comerciales actuales para verificar que LISTAS existen asignadas
$condiciones = DataManager::getCondiciones(0, 0, 1, $empresa, NULL, date("Y-m-d"));
if (count($condiciones)) {
foreach ($condiciones as $k => $cond) {
if($cond['condlista']){
$condListas[]= $cond['condlista'];
}
}
unset($listas);
$listas = DataManager::getListas(1);
if (count($listas)) {
foreach ($listas as $k => $list) {
$listId = $list["IdLista"];
$listNombre = $list["NombreLT"];
$listCatComerc = $list["CategoriaComercial"];
$catComerc = explode(',',$listCatComerc);
if(in_array($listId, $condListas)){
if(in_array($idCatComerc, $catComerc)){
$datosJSON[] = $listId."|".$listNombre;
}
}
}
}
}
/*una vez tenemos un array con los datos los mandamos por json a la web*/
header('Content-type: application/json');
echo json_encode($datosJSON);
?><file_sep>/informes/logica/exportar.tablaabm.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
//*******************************************
$fechaDesde = (isset($_POST['fechaDesde'])) ? $_POST['fechaDesde'] : NULL;
$fechaHasta = (isset($_POST['fechaHasta'])) ? $_POST['fechaHasta'] : NULL;
//*******************************************
if(empty($fechaDesde) || empty($fechaHasta)){
echo "Debe completar las fechas de exportación"; exit;
}
$fechaInicio = new DateTime(dac_invertirFecha($fechaDesde));
$fechaFin = new DateTime(dac_invertirFecha($fechaHasta));
//$fechaFin->modify("+1 day");
if($fechaInicio->format("Y") != $fechaFin->format("Y") || $fechaInicio->format("m") != $fechaFin->format("m")){
echo "El mes y año a exportar debe ser el mismo"; exit;
}
//*************************************************
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=TablaAbm-".date('d-m-y').".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos .::</TITLE>
<head></head>
<body>
<table border="0">
<?php
$registros = DataManager::getAbms(0, $fechaInicio->format("Y-m-d"), $fechaFin->format("Y-m-d"));
if(count($registros)){
$names = array_keys($registros[0]); ?>
<thead>
<tr> <?php
foreach ($names as $j => $name) {
?><td scope="col" ><?php echo $name; ?></td><?php
} ?>
</tr>
</thead> <?php
foreach ($registros as $k => $registro) {
echo sprintf("<tr align=\"left\">");
foreach ($names as $j => $name) {
if($j != 9 && $j != 7){
echo sprintf("<td >%s</td>", $registro[$name]);
} else {
echo sprintf("<td style=\"mso-number-format:'\@';\">%s</td>", $registro[$name]);
}
}
echo sprintf("</tr>");
}
} ?>
</table>
</body>
</html>
<file_sep>/juegos/lista.php
<div class="cajajuegos" align="center">
<div style="max-width:1980px; height:100%; margin:5%;" align="center">
<div style="width:350px; height:320px;">
<img id="abrir-slotmachine" src="SlotMachine/images/cartel_slotmachine.png" height="320"/>
<?php include "SlotMachine/inicio.php"; ?>
</div>
</div>
</div> <!-- Fin marco --><file_sep>/reportes/jquery/selectCategoria.js
$( document ).ready(function() {
"use strict";
$("#rtecategoria").change(function(){
//var reportes;
var categoria = $('#rtecategoria option:selected').val();
/*$.getJSON('/pedidos/reportes/getReporte.php?categoria='+categoria, function(datos) {
reportes = datos; */
$('#rtereporte').find('option').remove();
switch(categoria){
case "0": break;
case "abm":
$('#rtereporte').append("<option value='0'>Datos de ABM</option>");
$('#rtereporte').append("<option value='1'>Opcion 2 </option>");
$('#rtereporte').append("<option value='2'>Opcion 3</option>");
break;
case "agenda":
$('#rtereporte').append("<option value='0'>Datos de Agenda</option>");
break;
case "articulo":
$('#rtereporte').append("<option value='0'>Datos de Artículo</option>");
break;
case "condicion":
$('#rtereporte').append("<option value='0'>Datos de Condición Comercial</option>");
break;
case "cuenta":
$('#rtereporte').append("<option value='0'>Datos de Cuenta</option>");
break;
case "llamada":
$('#rtereporte').append("<option value='0'>Datos de Llamada</option>");
break;
case "parte_diario":
$('#rtereporte').append("<option value='0'>Datos de Parte Diario</option>");
break;
case "pedido":
$('#rtereporte').append("<option value='0'>Datos de Pedido</option>");
break;
case "pedidos_transfer":
$('#rtereporte').append("<option value='0'>Datos de Pedido Transfer</option>");
break;
case "planificado":
$('#rtereporte').append("<option value='0'>Datos de Planificación</option>");
break;
case "propuesta":
$('#rtereporte').append("<option value='0'>Datos de Propuesta</option>");
break;
}
/*$.each( reportes, function( key, value ) {
var arr = value.split('-');
$('#rtereporte').append("<option value='" + arr[0] + "'>" + arr[1] + "</option>");
});
}); */
});
});
<file_sep>/condicion/logica/ajax/getCondiciones.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
//---------------------------
$empresa = (isset($_POST['empselect'])) ? $_POST['empselect'] : NULL;
$activos = (isset($_POST['actselect'])) ? $_POST['actselect'] : NULL;
$tipo = (isset($_POST['tiposelect'])) ? $_POST['tiposelect']: NULL;
$pag = (isset($_POST['pag'])) ? $_POST['pag'] : NULL;
$_LPP = (isset($_POST['rows'])) ? $_POST['rows'] : NULL;
//----------------------------
$tipo = ($tipo == '0') ? NULL : "'".$tipo."'";
$conds = DataManager::getCondiciones($pag, $_LPP, $activos, $empresa, NULL, NULL, $tipo);
$rows = count($conds);
echo "<table id='tblCondiciones' class='datatab' width='100%' border='0' cellpadding='0' cellspacing='0' >";
if ($rows) {
echo "<thead><tr><th scope='colgroup' height='18'>Tipo</th><th scope='colgroup' >Nombre</th><th scope='colgroup' >Inicio</th><th scope='colgroup' >Fin</th>";
if ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="M"){
echo "<th scope='colgroup' colspan='3' align='center'>Acciones</th>";
} else {
echo "<th scope='colgroup' colspan='2' align='center'>Acciones</th>";
}
echo "</tr></thead>";
echo "<tbody>";
for( $k=0; $k < $_LPP; $k++ ) {
if ($k < $rows) {
$cond = $conds[$k];
$condId = $cond['condid'];
$tipo = $cond['condtipo'];
$nombre = $cond['condnombre'];
$activa = $cond['condactiva'];
$inicio = dac_invertirFecha( $cond['condfechainicio'] );
$fin = dac_invertirFecha( $cond['condfechafin'] );
$checkBox = "<input type='checkbox' name='editSelected' value='".$condId."'/>";
$btnExport = "<a id='exporta' href='logica/export.condicion.php?condid=".$condId."' title='Exportar'><img class=\"icon-xls-export\"/></a> ";
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class='".$clase."'>";
if ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="M"){
$editar = sprintf( "onclick=\"window.open('editar.php?condid=%d')\" style=\"cursor:pointer;\"",$condId);
$_status = ($cond['condactiva']) ? "<a title='Desactivar' href='logica/changestatus.php?condid=".$condId."'><img class=\"icon-status-active\"/></a>" : "<a title='Activar' href='logica/changestatus.php?condid=".$condId."'><img class=\"icon-status-inactive\"/></a>";
echo "<td height='15'".$editar.">".$tipo."</td><td ".$editar.">".$nombre."</td><td ".$editar.">".$inicio."</td><td ".$editar.">".$fin."</td><td align='center'>".$checkBox."</td><td align='center'>".$btnExport."</td><td align='center'>".$_status."</td>";
} else {
$_status = ($cond['condactiva']) ? "<a title='Desactivar'><img class=\"icon-status-active\"/></a>" : "<a title='Activar'><img class=\"icon-status-inactive\"/></a>";
if(!$activa){ $btnExport = ''; }
echo "<td height='15'>".$tipo."</td><td>".$nombre."</td><td >".$inicio."</td><td>".$fin."</td><td align='center'>".$btnExport."</td><td align='center'>".$_status."</td>";
}
echo "</tr>";
}
}
echo "</table> </div>";
} else {
echo "<tbody>";
echo "<thead><tr><th colspan='7' align='center'>No hay registros relacionados</th></tr></thead>"; exit;
}
echo "</tbody></table>";
?><file_sep>/soporte/mensajes/logica/close.ticket.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo "SU SESIÓN HA EXPIRADO."; exit;
}
$tkid = empty($_POST['tkid']) ? 0 : $_POST['tkid'];
if (empty($tkid)) {
echo "Error al seleccionar el ticket."; exit;
}
$objectTicket = DataManager::newObjectOfClass('TTicket', $tkid);
$objectTicket->__set('UsrUpdate' , $_SESSION["_usrid"]);
$objectTicket->__set('DateUpdate' , date("Y-m-d H:m:s"));
$objectTicket->__set('Estado' , 0);
$objectTicket->__set('Activo' , 1);
$IDTicket = DataManager::updateSimpleObject($objectTicket);
echo "1"; exit;
?><file_sep>/README.md
# Neo-farma
Proyecto de Laboratorio G
Subido para uso de GitHub
<file_sep>/includes/class/class.pedidotransfer.php
<?php
require_once('class.PropertyObject.php');
class TPedidostransfer extends PropertyObject {
protected $_tablename = 'pedidos_transfer';
protected $_fieldid = 'ptid';
protected $_fieldactivo = 'ptactivo';
protected $_timestamp = 'ptfechapedido'; //0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'ptid';
$this->propertyTable['IDVendedor'] = 'ptidvendedor';
$this->propertyTable['ParaIdUsr'] = 'ptparaidusr';//Para quién se registra el pedido
$this->propertyTable['IDPedido'] = 'ptidpedido';
$this->propertyTable['IDDrogueria'] = 'ptiddrogueria';
$this->propertyTable['ClienteDrogueria'] = 'ptnroclidrog';
$this->propertyTable['ClienteNeo'] = 'ptidclineo';
$this->propertyTable['RS'] = 'ptclirs';
$this->propertyTable['Cuit'] = 'ptclicuit';
$this->propertyTable['Domicilio'] = 'ptdomicilio';
$this->propertyTable['Contacto'] = 'ptcontacto';
$this->propertyTable['Articulo'] = 'ptidart';
$this->propertyTable['Unidades'] = 'ptunidades';
$this->propertyTable['Precio'] = 'ptprecio';
$this->propertyTable['Descuento'] = 'ptdescuento';
$this->propertyTable['FechaPedido'] = 'ptfechapedido';
$this->propertyTable['CondicionPago'] = 'ptcondpago';
$this->propertyTable['IDAdmin'] = 'ptidadmin';
$this->propertyTable['IDNombreAdmin'] = 'ptnombreadmin';
$this->propertyTable['FechaExportado'] = 'ptfechaexp';
$this->propertyTable['Liquidado'] = 'ptliquidado';
$this->propertyTable['Activo'] = 'ptactivo';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
/*
public function Autenticado() {
return $this->_autenticado;
}*/
public function __newID() {
// Devuelve '#petid' para el alta de un nuevo registro
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/zonas/logica/update.zona.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A"){
echo "SU SESIÓN HA EXPIRADO"; exit;
}
$zId = (isset($_POST['zid'])) ? $_POST['zid'] : NULL;
$zona = (isset($_POST['zzona'])) ? $_POST['zzona'] : NULL;
$nombre = (isset($_POST['znombre'])) ? $_POST['znombre'] : NULL;
$assigned = (isset($_POST['asignado'])) ? $_POST['asignado'] : NULL;
if (empty($zona)) {
echo "Indique la zona."; exit;
}
if (empty($nombre)) {
echo "Indique el nombre."; exit;
}
if(empty($assigned)){
echo "Indique usuario asignado."; exit;
}
$zObject = ($zId) ? DataManager::newObjectOfClass('TZonas', $zId) : DataManager::newObjectOfClass('TZonas');
$zObject->__set('Zona' , $zona);
$zObject->__set('Nombre' , $nombre);
$zObject->__set('UsrAssigned' , $assigned);
if ($zId) {
$ID = DataManager::updateSimpleObject($zObject);
} else {
$zObject->__set('ID' , $zObject->__newID());
$zObject->__set('Activo', 1);
$ID = DataManager::insertSimpleObject($zObject);
}
echo "1"; exit;
?><file_sep>/rendicion/logica/jquery/jquery.add.cheque.js
$(document).ready(function() {
"use strict";
//ACA le asigno el evento click a cada boton de la clase btn_checque_plus y llamo a la funcion addField
$(".btn_checque_plus").each(function (){
$(this).bind("click",addField);
});
});
function addField(){
"use strict";
// ID del elemento div quitandole la palabra "bank_" de delante. Pasi asi poder aumentar el número. Esta parte no es necesaria pero yo la utilizaba ya que cada campo de mi formulario tenia un autosuggest , así que dejo como seria por si a alguien le hace falta.
var clickID = parseInt($(this).parent('div').parent('div').attr('id').replace('bank_',''));
// Genero el nuevo numero id
var newID = (clickID+1);
// Creo un clon del elemento div que contiene los campos de texto
var newClone = $('#bank_'+clickID).clone(true);
//Le asigno el nuevo numero id
newClone.attr("id",'bank_'+newID);
// Asigno nuevo id al primer campo input dentro del div y le borro cualquier valor que tenga asi no copia lo ultimo que hayas escrito.(igual que antes no es necesario tener un id)
newClone.children().eq(0).children("select").eq(0).attr("id", 'pagobco_nombre'+newID).val(''); //nombre
newClone.children().eq(1).children("input").eq(0).attr("id",'pagobco_nrocheque'+newID).val(''); //input nrocheque
newClone.children().eq(2).children("input").eq(0).attr("id",'bco_fecha'+newID).val(''); //input fecha
newClone.children().eq(3).children("input").eq(0).attr("id", 'pagobco_importe'+newID).val(''); // importe
//Asigno nuevo id al boton
newClone.children().eq(4).children("input").eq(0).attr("id", 'boton_'+newID);
//Inserto el div clonado y modificado despues del div original
newClone.insertAfter($('#bank_'+clickID));
//Cambio el signo "+" por el signo "-" y le quito el evento addfield
$("#boton_"+clickID).val('-').unbind("click", addField);
//Ahora le asigno el evento delRow para que borre la fial en caso de hacer click
$("#boton_"+clickID).bind("click", delRow);
}
function delRow() {// Funcion que destruye el elemento actual una vez echo el click
//Antes borra los datos
$(this).parent('div').parent('div').find('input:text').val('');
//Recalcula la diferencia porque si se borra el div ya no se podrá calcular
dac_Calcular_Diferencia();
$(this).parent('div').parent('div').remove();
}<file_sep>/index.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="P"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
} ?>
<!DOCTYPE html>
<html xml:lang='es'>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php"; ?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav> <!-- fin menu -->
<main class="cuerpo menu2">
<?php
// USUARIOS DE EMPRESA //
if ($_SESSION["_usrrol"]== "G" || $_SESSION["_usrrol"]== "V" || $_SESSION["_usrrol"]== "A" || $_SESSION["_usrrol"]== "M"){?>
<div class="box_down">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/inicio/contenido2.inc.php"); ?>
</div>
<?php } ?>
<?php
// USUARIOS PROVEEDORES //
if ($_SESSION["_usrrol"]=="P"){ ?>
<div class="box_down">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/banner.header.inc.php"); ?>
</div>
<?php } ?>
<hr>
</main> <!-- fin cuerpo -->
<offers>
<div class="section-title text-center center">
<h2>↓ Ofertas Del Mes ↓</h2>
</div>
<div class="offers"> <?php
$condiciones = DataManager::getCondiciones( 0, 0, 1, 1, 1, date("Y-m-d"), "'Bonificacion'");
if (count($condiciones)) {
$index = 0;
foreach ($condiciones as $j => $cond) {
$condId = $cond['condid'];
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
foreach ($articulosCond as $k => $artCond) {
$condArtOAM = $artCond["cartoferta"];
if($condArtOAM == "1"){
$condArtIdArt = $artCond['cartidart'];
$condArtNombre = DataManager::getArticulo('artnombre', $condArtIdArt, 1, 1);
$condArtImagen = DataManager::getArticulo('artimagen', $condArtIdArt, 1, 1);
$imagenObject = DataManager::newObjectOfClass('TImagen', $condArtImagen);
$imagen = $imagenObject->__get('Imagen');
$img = ($imagen) ? "/pedidos/images/imagenes/".$imagen : "/pedidos/images/sin_imagen.png";
$arrayArticulos['idart'][$index] = $condArtIdArt;
$arrayArticulos['nombre'][$index] = $condArtNombre;
$arrayArticulos['imagen'][$index] = $img;
$index ++;
}
}
}
}
}
if(isset($arrayArticulos)){
if(count($arrayArticulos['idart'])){
for($i = 0; $i < count($arrayArticulos['idart']); $i ++ ) {
$idArt = $arrayArticulos['idart'][$i];
$nombre = $arrayArticulos['nombre'][$i];
$imagen = $arrayArticulos['imagen'][$i];
$palabras = explode(" ", $nombre); ?>
<div class="col-sm-6">
<div class="portfolio-item">
<div class="hover-bg">
<div class="hover-text">
<i><?php echo $palabras[0]; ?></i>
<h4><?php echo "Art. ".$idArt; ?><h4>
<hr>
<small><?php echo $nombre; ?></small>
</div>
<img src="<?php echo $imagen; ?>" class="img-responsive" alt="Oferta">
</div>
</div>
</div> <?php
}
}
}?>
</div>
</offers>
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/pedidos/logica/ajax/getCuentas.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
$empresa = (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
$condidcuentas = (isset($_POST['condidcuentas'])) ? $_POST['condidcuentas'] : NULL;
$listaCondicion = (isset($_POST['listaCondicion'])) ? $_POST['listaCondicion'] : NULL;
$arrayCondIdCtas = array();
if($condidcuentas){ $arrayCondIdCtas = explode(",", $condidcuentas); }
if (!empty($_SESSION["_usrzonas"])) {
$cuentas = DataManager::getCuentas( 0, 0, $empresa, 1, '"C","CT"', $_SESSION["_usrzonas"]);
if (count($cuentas)) {
echo '<table id="tblTablaCta" style="table-layout:fixed;">';
echo '<thead><tr align="left"><th>Id</th><th>Nombre</th><th>Localidad</th></tr></thead>';
echo '<tbody>';
foreach ($cuentas as $k => $cta) {
$ctaId = $cta["ctaid"];
$idCuenta = $cta["ctaidcuenta"];
$condPago = $cta["ctacondpago"];
$nombre = $cta["ctanombre"];
$idLoc = $cta["ctaidloc"];
$listaCuenta= $cta["ctalista"];
$listaNombre= DataManager::getLista('NombreLT', 'IdLista', $listaCuenta);
$localidad = 0;
$localidad = (empty($idLoc)) ? DataManager::getCuenta('ctalocalidad', 'ctaid', $ctaId, $empresa) : DataManager::getLocalidad('locnombre', $idLoc);
$direccion = $cta["ctadireccion"].' '.$cta["ctadirnro"];
$observacion= $cta["ctaobservacion"];
((($k % 2) == 0)? $clase="par" : $clase="impar");
if( $idCuenta != 0 ) {
if(count($arrayCondIdCtas) > 0) {
if(in_array($ctaId, $arrayCondIdCtas)){
echo "<tr class=".$clase." onclick=\"javascript:dac_cargarDatosCuenta('$idCuenta', '$nombre', '$direccion', '$observacion', '$condPago', '$listaCuenta', '$listaNombre', '$listaCondicion')\" title='".$direccion."' style=\"cursor:pointer\"><td>".$idCuenta."</td><td>".$nombre."</td><td>".$localidad."</td></tr>";
}
} else {
echo "<tr class=".$clase." onclick=\"javascript:dac_cargarDatosCuenta('$idCuenta', '$nombre', '$direccion', '$observacion', '$condPago', '$listaCuenta', '$listaNombre', '$listaCondicion')\" title='".$direccion."' style=\"cursor:pointer\"><td>".$idCuenta."</td><td>".$nombre."</td><td>".$localidad."</td></tr>";
}
}
}
echo '</tbody></table>';
}else {
echo '<table><tr><td align="center">No hay registros activos.</td></tr></table>';
}
} else {
echo '<table><tr><td align="center">Usuario sin zonas registradas.</td></tr></table>';
}
?><file_sep>/includes/class/class.pedido.php
<?php
require_once('class.PropertyObject.php');
class TPedido extends PropertyObject {
protected $_tablename = 'pedido';
protected $_fieldid = 'pid';
protected $_fieldactivo = 'pactivo';
protected $_timestamp = 'pfechapedido';
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'pid';
$this->propertyTable['Usuario'] = 'pidusr'; //id de usuario o vendedor
//$this->propertyTable['Zona'] = 'pzona'; //Zona del cliente??
$this->propertyTable['Cliente'] = 'pidcliente';
$this->propertyTable['Pedido'] = 'pidpedido';
$this->propertyTable['Pack'] = 'pidpack';
$this->propertyTable['Lista'] = 'pidlista';
$this->propertyTable['Empresa'] = 'pidemp';
$this->propertyTable['Laboratorio'] = 'pidlab';
$this->propertyTable['IDArt'] = 'pidart';
$this->propertyTable['Articulo'] = 'pnombreart';
$this->propertyTable['Cantidad'] = 'pcantidad';
$this->propertyTable['Precio'] = 'pprecio';
$this->propertyTable['Bonificacion1'] = 'pbonif1';
$this->propertyTable['Bonificacion2'] = 'pbonif2';
$this->propertyTable['Descuento1'] = 'pdesc1';
$this->propertyTable['Descuento2'] = 'pdesc2';
$this->propertyTable['Descuento3'] = 'pdesc3';
$this->propertyTable['CondicionPago'] = 'pidcondpago';
$this->propertyTable['OrdenCompra'] = 'pordencompra';
$this->propertyTable['Observacion'] = 'pobservacion';
$this->propertyTable['FechaPedido'] = 'pfechapedido';
$this->propertyTable['IDAdmin'] = 'pidadmin';
$this->propertyTable['Administrador'] = 'pnombreadmin';
$this->propertyTable['FechaExportado'] = 'pfechaexport';
$this->propertyTable['Propuesta'] = 'pidpropuesta';
$this->propertyTable['CondicionComercial'] = 'pidcondcomercial';
$this->propertyTable['Negociacion'] = 'pnegociacion';
$this->propertyTable['IDResp'] = 'pidresp';
$this->propertyTable['Responsable'] = 'presponsable';
$this->propertyTable['FechaAprobado'] = 'pfechaaprob';
$this->propertyTable['Aprobado'] = 'paprobado';
$this->propertyTable['Propuesta'] = 'pidpropuesta';
$this->propertyTable['Activo'] = 'pactivo';
//Para pedidos SP, VALE, ClienteParticular, etc
$this->propertyTable['Tipo'] = 'ptipo';
$this->propertyTable['Nombre'] = 'pnombre';
$this->propertyTable['Provincia'] = 'pprovincia';
$this->propertyTable['Localidad'] = 'plocalidad';
$this->propertyTable['Direccion'] = 'pdireccion';
$this->propertyTable['CP'] = 'pcp';
$this->propertyTable['Telefono'] = 'ptelefono';
//----------
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
/*
public function Autenticado() {
return $this->_autenticado;
}*/
public function __newID() {
// Devuelve '#petid' para el alta de un nuevo registro
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/contactos/logica/ajax/cargar.contacto.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//*************************************************
$_ctoid = (isset($_POST['ctoid'])) ? $_POST['ctoid'] : NULL;
//*************************************************
$_contacto = DataManager::newObjectOfClass('TContacto', $_ctoid);
$_apellido = $_contacto->__get('Apellido');
$_nombre = $_contacto->__get('Nombre');
$_telefono = $_contacto->__get('Telefono');
$_interno = $_contacto->__get('Interno');
$_sector = $_contacto->__get('Sector');
$_correo = $_contacto->__get('Email');
$_sectores = DataManager::getSectores(1);
if($_sectores){
foreach ($_sectores as $k => $_sect) {
$_sectid = $_sect['sectid'];
if($_sectid == $_sector){
$_sectnombre = $_sect['sectnombre'];
}
}
}
//*************************************************
$_datos[] = array(
"apellido" => $_apellido,
"nombre" => $_nombre,
"telefono" => $_telefono,
"interno" => $_interno,
"sector" => $_sectnombre,
"correo" => $_correo
);
$objJason = json_encode($_datos);
echo $objJason;
?><file_sep>/planificacion/detalle_parte.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_fecha_planif = empty($_REQUEST['fecha_planif']) ? date("d-m-Y") : $_REQUEST['fecha_planif'];
$_button_print = sprintf( "<a id=\"imprime\" title=\"Imprimir Parte Diario\" onclick=\"javascript:dac_imprMuestra('muestra_parte')\">%s</a>", "<img class=\"icon-print\"/>");
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
?>
<!DOCTYPE html>
<html>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
<script type="text/javascript">
function dac_imprMuestra(muestra){
var ficha=document.getElementById(muestra);
var ventimp=window.open(' ','popimpr');
ventimp.document.write(ficha.innerHTML);
ventimp.document.close();
ventimp.print();
ventimp.close();
}
</script>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "pedidos";
$_subsection = "mis_pedidos";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav> <!-- fin menu -->
<main class="cuerpo">
<div class="cbte">
<div id="muestra_parte">
<div class="cbte_header">
<div class="cbte_boxheader" style="text-align: left;
float: left; max-width: 400px; min-width: 300px;">
<?php echo $cabeceraPedido; ?>
</div>
<div class="cbte_boxheader" style="text-align: left;
float: left; max-width: 400px; min-width: 300px;">
<h2 style="font-size: 18px;">PARTE DIARIO (<?php echo $_fecha_planif; ?>)</br>
<?php echo $_SESSION["_usrname"]; ?></h2>
</div>
</div>
<?php
$_partediario = DataManager::getDetalleParteDiario($_fecha_planif, $_SESSION["_usrid"]);
if (count($_partediario)){ ?>
<div class="cbte_boxcontent2">
<table class="datatab_detalle" width="100%" style="border:2px solid #999;">
<thead>
<tr align="left">
<th scope="col" width="10%" height="20" style="border-left: 1px solid #999; text-align: center;" >Cliente</th>
<th scope="col" width="12%" style="border-left: 1px solid #999; text-align: center;">Nombre</th>
<th scope="col" width="12%" style="border-left: 1px solid #999; text-align: center;">Domicilio</th>
<th scope="col" width="11%" style="border-left: 1px solid #999; text-align: center;">Acción</th>
<th scope="col" width="15%" style="border-left: 1px solid #999; text-align: center;">Trabaja con...</th>
<th scope="col" width="40%" style="border-left: 1px solid #999; text-align: center;">Observación</th>
</tr>
</thead>
<?php
foreach ($_partediario as $k => $_parte){
$_parte = $_partediario[$k];
if($_parte["parteidcliente"]==0){ $_partecliente = "NUEVO";
}else{ $_partecliente = $_parte["parteidcliente"];};
$_partenombre = $_parte["parteclinombre"];
$_partedir = $_parte["parteclidireccion"];
$_parteacciones = explode(',', $_parte["parteaccion"]);
$_acc = '';
for ($i=0; $i < count($_parteacciones); $i++){
if($_parteacciones[$i]){
$_acciones = DataManager::getAccion($_parteacciones[$i]);
$_accion = $_acciones[0];
if($i==0){ $_acc = $_accion["acnombre"];
}else{ $_acc = $_acc."</br>".$_accion["acnombre"];}
}
}
$_partetrabaja = $_parte["partetrabajocon"];
$_parteobserv = $_parte["parteobservacion"];
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"100\" align=\"center\" style=\"border:1px solid #999; border-right: none;\">%s</td><td style=\"border:1px solid #999; border-right: none;\">%s</td><td style=\"border:1px solid #999; border-right: none;\">%s</td><td align=\"center\" style=\"border:1px solid #999; border-right: none;\">%s</td><td style=\"border:1px solid #999; border-right: none;\">%s</td><td style=\"border:1px solid #999; border-right: none;\">%s</td>", $_partecliente, $_partenombre, $_partedir, $_acc,$_partetrabaja,$_parteobserv);
echo sprintf("</tr>");
} ?>
</table>
</div> <!-- cbte_boxcontent2 --> <?php
} ?>
<div class="cbte_boxcontent2" align="center">
<?php echo $piePedido; ?>
</div> <!-- cbte_boxcontent2 -->
</div> <!-- muestra -->
<div class="cbte_boxcontent2" align="center">
<?php echo $_button_print; ?>
</div> <!-- cbte_boxcontent2 -->
</div> <!-- cbte_box -->
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/includes/class/class.relevamiento.php
<?php
require_once('class.PropertyObject.php');
class TRelevamiento extends PropertyObject {
protected $_tablename = 'relevamiento';
protected $_fieldid = 'relid';
protected $_fieldactivo = 'relactivo';
protected $_timestamp = 0;
protected $_id = 0;
protected $_autenticado = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'relid';
$this->propertyTable['Relevamiento'] = 'relidrel'; //númeración de los relevamientos.
$this->propertyTable['Orden'] = 'relpregorden';
$this->propertyTable['Pregunta'] = 'relpregunta';
$this->propertyTable['Tipo'] = 'reltiporesp';
$this->propertyTable['Nulo'] = 'reladmitenulo';
$this->propertyTable['UsrUpdate'] = 'relusrupdate';
$this->propertyTable['LastUpdate'] = 'rellastupdate';
$this->propertyTable['Activo'] = 'relactivo';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/includes/class.Database.php
<?php
class Database { //extends PropertyDB {
private $conn;
protected static $instance;
protected static $instanceHiper;
public function __construct($dsn = '') {
try {
$this->conn = $this->connect($dsn);
} catch(PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
}
public static function instance() {
if ( !isset( self::$instance ) ) {
try {
self::$instance = new Database();
} catch(PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
}
return self::$instance;
}
public static function instanceHiper() {
if ( !isset( self::$instanceHiper ) ) {
try {
self::$instanceHiper = new Database('Database');
} catch(PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
}
return self::$instanceHiper;
}
public function connect($dsn='') {
$config = (require 'config.php');
$dbConnectionName = ($dsn==="Database") ? "Database" : "dbname";
$dbconn = $config[$dbConnectionName]['connection'].";".$dbConnectionName."=".$config[$dbConnectionName]['name'].";".$config[$dbConnectionName]['charset'];
$dbusr = $config[$dbConnectionName]['username'];
$dbpass = $config[$dbConnectionName]['password'];
$dbconf = $config[$dbConnectionName]['options'];
try {
$this->conn = new PDO($dbconn, $dbusr, $dbpass, $dbconf);
//Si option no funciona, debo usar: para el control de excepciones funcione
//$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $this->conn;
} catch (PDOException $e){
echo "ERROR de conexión a DDBB ".$config[$dbConnectionName]['name'].". Consulte con el administrador web."; exit;// . $e->getMessage(); //die ($e->getMessage());
//Redirigir a una página de error de conexión a DDBB
//include($_SERVER['DOCUMENT_ROOT']."/pedidos/errorConnectionDDBB.php"); die();
}
catch(Exception $e) {
//TODO: flag to disable errors?
throw $e;
}
}
//returns 2D assoc array
function getAll($sql) {
//$result = $this->ejecutar($sql);
try{
# Prepare query
$sth = $this->conn->prepare($sql);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e ){
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
return $result;
}
//returns single scalar value from the first column, first record
function getOne($sql) {
$result = "";
try{
//$result = $this->ejecutar($sql);
# Prepare query
$sth = $this->conn->prepare($sql);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_NUM)[0];
//$result = $result->fetch_row()[0];
} catch(PDOException $e ) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
return $result;
}
//ERROR
public static function isError($result){
if (!$result) {
return true;
} else {
return false;
}
}
public function __destruct() {
$this->disconnect();
}
public function disconnect(){
$this->conn = null;
}
//returns a DB_result object
function select($sql) {
try {
$result = $this->conn->query($sql);
} catch (PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
return $result;
}
//returns numerically indexed 1D array of values from the first column
function getColumn($sql) {
try {
$result = $this->conn->getCol($sql);
} catch (PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
return $result;
}
function update($tableName, $arUpdates, $sWhere = null) {
$arSet = array();
foreach($arUpdates as $name => $value) {
if(empty($value) && $value != 0){$value = "";}
$arSet[] = $name . ' = ' . $this->conn->quote($value) ; //PERL->quoteSmart($value) //php 7 real_escape_string($value)
}
$sSet = implode(', ', $arSet);
//make sure the table name is properly escaped
//$tableName = $this->conn->quote($tableName); //quoteIdentifier($tableName)
$sql = "UPDATE $tableName SET $sSet";
if($sWhere) {
$sql .= " WHERE $sWhere";
}
try {
$sth = $this->conn->prepare($sql);
$result = $sth->execute();
//$result = $this->conn->query($sql);
} catch (PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
return $sth->rowCount();
}
function nextId($seqname) { //$seqname, $ondemand = true
$tableName = $seqname."_seq";
//consulto si existe la tabla de sequencia
$sql = "SHOW TABLES LIKE '$tableName'";
$result = $this->getOne($sql);
//NO HAY RESULTADO DE LA CONSULTA
if($result){
//consulto nextID
$sql2 = "SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = '$tableName'
"; //AND table_schema = DATABASE( )
$_ID = $this->getOne($sql2);
//Modifica el autoincremental
try {
$sql3 = "ALTER TABLE $tableName AUTO_INCREMENT=$_ID";
$sth = $this->conn->prepare($sql3);
$sth->execute();
} catch (PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
//modifico la tabla del autoincremental
try {
$arUpdates = array();
$arUpdates['id'] = $_ID;
$data = $this->update($tableName, $arUpdates);
} catch (PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
return $_ID;
} else {
//crear la tabla
try {
$sql = "CREATE TABLE $tableName (id int NOT NULL AUTO_INCREMENT, PRIMARY KEY (id))";
$sth = $this->conn->prepare($sql);
$sth->execute();
} catch (PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
//insertar primer registro
try {
$sql = "INSERT INTO $tableName (id) VALUES (1)";
$sth = $this->conn->prepare($sql);
$sth->execute();
return 1;
} catch (PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
}
}
function insert($tableName, $arValues) {
$id = null;
$sFieldList = join(', ', array_keys($arValues));
$arValueList = array();
foreach ($arValues as $value){
if(!empty($value)){
if($value[0] == '#') { //if($value{0} == '#') {
//we need to get the next value from this table's sequence
$value = $id = $this->nextID($tableName . '_' . strtolower(substr($value,1)));
}
}
$arValueList[] = $this->conn->quote($value);
}
$sValueList = implode(', ', $arValueList);
//make sure the table name is properly escaped
$sql = "INSERT INTO $tableName ( $sFieldList ) VALUES ( $sValueList )";
try {
$sth = $this->conn->prepare($sql);
$sth->execute();
} catch (PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage(); exit;
}
//return the ID, if there was one, or the number of rows affected
//return $id ? $id : $this->conn->affected_rows;
return $id ? $id : $sth->rowCount();
}
function startTransaction() {
// PDO beginTransaction, deshabilita el modo de confirmación automática
$this->conn->beginTransaction();
}
function commit() {
try {
$result = $this->conn->commit();
} catch (PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
$this-> abort();
}
return true;
}
function abort() {
try {
$result = $this->conn->rollback();
} catch (PDOException $e) {
echo "Error: ".$e." Mensage: ".$e->getMessage();
}
return true;
}
}
?>
<file_sep>/acciones/lista.php
<?php
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/acciones/': $_REQUEST['backURL'];
$_LPP = 10;
$_total = DataManager::getNumeroFilasTotales('TAccion', 0);
$_paginas = ceil($_total/$_LPP);
$_pag = isset($_REQUEST['pag']) ? min(max(1,$_REQUEST['pag']),$_paginas) : 1;
$_GOFirst = sprintf("<a class=\"icon-go-first\" href=\"%s?pag=%d\"></a>", $backURL, 1);
$_GOPrev = sprintf("<a class=\"icon-go-previous\" href=\"%s?pag=%d\"></a>", $backURL, $_pag-1);
$_GONext = sprintf("<a class=\"icon-go-next\" href=\"%s?pag=%d\"></a>", $backURL, $_pag+1);
$_GOLast = sprintf("<a class=\"icon-go-last\" href=\"%s?pag=%d\"></a>", $backURL, $_paginas);
$btnNuevo = sprintf( "<a href=\"editar.php\" title=\"Nuevo\"><img class=\"icon-new\"/></a>");
?>
<div class="box_body">
<div class="barra">
<div class="bloque_5">
<h1>Acciones</h1>
</div>
<div class="bloque_5">
<?php echo $btnNuevo ?>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblAcciones">
<thead>
<tr>
<td scope="col" >id Acción</td>
<td scope="col" >Nombre</td>
<td scope="col" >Siglas</td>
<td scope="colgroup" colspan="3" align="center">Acciones</td>
</tr>
</thead>
<?php
$_acciones = DataManager::getAcciones($_pag, $_LPP, FALSE);
$_max = count($_acciones);
for( $k=0; $k < $_LPP; $k++ ){
if ($k < $_max){
$_accion = $_acciones[$k];
$_id = $_accion['acid'];
$_nombre = $_accion['acnombre'];
$_sigla = $_accion['acsigla'];
$_status = ($_accion['acactiva']) ? "<img class=\"icon-status-active\"/>" : "<img class=\"icon-status-inactive\"/>";
$_editar = sprintf( "<a href=\"editar.php?acid=%d&backURL=%s\" title=\"editar acción\">%s</a>", $_accion['acid'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit\"/>");
$_borrar = sprintf( "<a href=\"logica/changestatus.php?acid=%d&backURL=%s&pag=%s\" title=\"Cambiar Estado\">%s</a>", $_accion['acid'], $_SERVER['PHP_SELF'], $_pag, $_status);
$_eliminar = sprintf ("<a href=\"logica/eliminar.accion.php?acid=%d&backURL=%s&pag=%s\" title=\"eliminar acción\" onclick=\"return confirm('¿Está Seguro que desea ELIMINAR LA ACCIÓN?')\"> <img class=\"icon-delete\"/></a>", $_accion['acid'], $_SERVER['PHP_SELF'], $_pag, "eliminar");
} else {
$_id = " ";
$_nombre = " ";
$_sigla = " ";
$_editar = " ";
$_borrar = " ";
$_eliminar = " ";
}
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_id, $_nombre, $_sigla, $_editar, $_borrar, $_eliminar);
echo sprintf("</tr>");
}
?>
</table>
</div> <!-- Fin lista -->
<?php
if ( $_paginas > 1 ) {
$_First = ($_pag > 1) ? $_GOFirst : " ";
$_Prev = ($_pag > 1) ? $_GOPrev : " ";
$_Last = ($_pag < $_paginas) ? $_GOLast : " ";
$_Next = ($_pag < $_paginas) ? $_GONext : " ";
echo("<table class=\"paginador\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
echo sprintf("<td height=\"16\">Mostrando página %d de %d</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td>", $_pag, $_paginas, $_First, $_Prev, $_Next, $_Last);
echo("</tr></table>");
} ?>
</div> <!-- Fin body -->
<file_sep>/usuarios/logica/recupera.usuario.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
/*if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="P" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}*/
function dac_generar_password($longitud) {
$caracteres = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$password = '';
for ($i=0; $i<$longitud; ++$i) $password .= substr($caracteres, (mt_rand() % strlen($caracteres)), 1);
return $password;
}
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/login/': $_REQUEST['backURL'];
$_usuario = $_POST['rec_usuario'];
$_email = $_POST['rec_mail'];
$_SESSION['s_usuario'] = $_usuario;
$_SESSION['s_email'] = $_email;
//Consulta si existe el usuario en cualquiera de las tablas con posibilidad de usuario
$_ID = DataManager::getIDByField('TUsuario', 'ulogin', $_usuario);
if ($_ID > 0) {
$_usrobject = DataManager::newObjectOfClass('TUsuario', $_ID);
} else {
$_ID = DataManager::getIDByField('TProveedor', 'provlogin', $_usuario);
if ($_ID > 0) {
$_usrobject = DataManager::newObjectOfClass('TProveedor', $_ID);
}
}
if ($_ID > 0) {
//$_usrobject = DataManager::newObjectOfClass('TUsuario', $_ID);
$_uemail = $_usrobject->__get('Email');
//if ($_usrobject->login(md5($_password))) {
if (!preg_match( "/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,4})$/", $_email )) {
$_goURL = sprintf("/pedidos/login/index.php?sms=%d", 2);
header('Location:' . $_goURL);
exit;
} else {
if (strcmp ($_email , $_uemail ) != 0) {
$_goURL = sprintf("/pedidos/login/index.php?sms=%d", 3);
header('Location:' . $_goURL);
exit;
}
}
$_uusuario = $_usrobject->__get('Login');
/*********************************/
/*Genero una clave aleatorioa para que el usuario luego la modifique si lo desea*/
$_clave = dac_generar_password(7);
$_usrobject->__set('Clave', md5($_clave));
$ID = DataManager::updateSimpleObject($_usrobject);
/*********************************/
// ENVIAR CLAVE POR MAIL */
//********************************/
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = "<EMAIL>";
$mail->Subject = 'Clave Recuperada';
/*$_total= "
Alguien ha solicitado la recuperación de contraseña de la siguiente cuenta:<br /><br />
http://www.neo-farma.com.ar/<br /><br />
Nombre de Usuario: ".$_uusuario."<br />
Nueva Clave: ".$_clave."<br /><br />
". /*Si ha sido un error, ignora este correo y no pasará nada.<br /><br />
Para restaurar la contraseña, visita la siguiente dirección:<br /><br />
<http://www.neo-farma.com.ar/wp-login.php?action=rp&key=<KEY>&login=".$_nombre.">*//*"<br />
No responda a éste mail.<br /><br />
Saludos.";*/
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
$_total = '
<html>
<head>
<title>Clave Recuperada</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 90%;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 0px;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>
<body>
<div align="center">
<table width="600" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Notificación de <strong>NUEVA CLAVE DE ACCESO</strong><br />
Alguien ha solicitado la recuperación de contraseña de la siguiente cuenta:<br />
<div />
</td >
</tr>
<tr bgcolor="#597D92">
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight: bold;">
<strong>Estos son sus datos de solicitud</strong>
</div>
</td>
</tr>
<tr>
<td height="95" valign="top">
<div class="texto">
<table width="600px" style="border:1px solid #597D92">
<tr>
<th rowspan="2" align="left" width="250">
Usuario:<br />
Clave:
</th>
<th rowspan="2" align="left" width="450">
'.$_usuario.'<br />
'.$_clave.'
</th>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con la empresa al 4555-3366 de Lunes a Viernes de 10 a 17 horas.
</font>
<div style="color:#000000; font-size:12px;">
<strong>No responda a éste mail.</br></br>
</div>
</div>
</td>
</tr>
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo" align="left">
Gracias por confiar en nosotros.<br/>
Le Saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
';
$mail->msgHTML($_total);
$mail->AddAddress($_uemail, "Clave Recuperada");
$mail->AddAddress("<EMAIL>", "[neo-farma.com.ar] Clave Recuperada.");
/************************************/
unset($_SESSION['s_usuario']);
unset($_SESSION['s_email']);
/**********************************/
if(!$mail->Send()) {
echo 'Fallo en el envío del correo.';
} else {
$_goURL = sprintf("/pedidos/login/index.php?sms=%d", 4);
header('Location:'.$_goURL);
}
exit;
} else {
$_goURL = sprintf("/pedidos/login/index.php?sms=%d", 1);
header('Location:' . $_goURL);
exit;
}
header('Location: '.$backURL);
?><file_sep>/includes/class/class.pack.php
<?php
require_once('class.PropertyObject.php');
class TPack extends PropertyObject {
protected $_tablename = 'pack';
protected $_fieldid = 'packid';
protected $_fieldactivo = 'packactiva';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'packid';
$this->propertyTable['Empresa'] = 'packidemp';
$this->propertyTable['Nombre'] = 'packnombre';
$this->propertyTable['CantidadMin'] = 'packcantmin';
$this->propertyTable['ReferenciaMin'] = 'packcantminref';
$this->propertyTable['MinPorReferencia'] = 'packcantminporref';
$this->propertyTable['MontoMin'] = 'packmontomin';
$this->propertyTable['CondicionPago'] = 'packcondpago';
$this->propertyTable['FechaInicio'] = 'packfechainicio';
$this->propertyTable['FechaFin'] = 'packfechafin';
$this->propertyTable['Observacion'] = 'packobservacion';
$this->propertyTable['Activa'] = 'packactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
/*public function __getFieldActivo() {
return $this->_fieldactivo;
}*/
public function __newID() {
// Devuelve '#petid' para el alta de un nuevo registro
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/acciones/logica/eliminar.accion.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$_acid = empty($_REQUEST['acid']) ? 0 : $_REQUEST['acid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/articulos/' : $_REQUEST['backURL'];
if ($_acid) {
$_acobject = DataManager::newObjectOfClass('TAccion', $_acid);
$_acobject->__set('ID', $_acid );
$ID = DataManager::deleteSimpleObject($_acobject);
}
header('Location: '.$backURL.'?pag='.$_pag);
?><file_sep>/transfer/gestion/liquidacion/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_drogid = empty($_REQUEST['drogid']) ? 0 : $_REQUEST['drogid'];
if(empty($_REQUEST['fecha_liquidacion'])){
$_mes = date("m"); $_anio = date("Y");
} else {
list($_mes, $_anio) = explode('-', str_replace('/', '-', $_REQUEST['fecha_liquidacion']));
}
if($_drogid){
$_importarXLS = sprintf( "<img id=\"importar\" src=\"/pedidos/images/icons/icono-importxls.png\" border=\"0\" align=\"absmiddle\" title=\"Importar Liquidacion\"/>");
$_exportarXLS = sprintf( "<a href=\"logica/exportar.liquidacion.php?mes=%d&anio=%d&drogid=%d&backURL=%s\" title=\"Exportar Liquidacion\">%s</a>", $_mes, $_anio, $_drogid, $_SERVER['PHP_SELF'], "<img class=\"icon-xls-export\"/>");
$_emitirNC = sprintf( "<img id=\"emitirnc\" title=\"Emitir NC\" src=\"/pedidos/images/icons/icono-emitirnc.png\" border=\"0\" align=\"absmiddle\" />");
} ?>
<div class="box_down">
<table id="tabla_liquidacion" name="tabla_liquidacion" class="tabla_liquidacion" border="0">
<thead>
<tr>
<th colspan="8" align="left">
<form id="fm_droguerias" action="#" method="post" enctype="multipart/form-data">
<label for="drogid">Droguería: </label> <?php
$_droguerias = DataManager::getDrogueria('');
if (count($_droguerias)) { ?>
<select name='drogid' id='drogid' style='width:500px; font-weight:bold; background-color:transparent; border:none;' onChange="javascript:document.getElementById('fm_droguerias').submit();">
<option value="0" selected>Seleccione Droguería...</option><?php
foreach ($_droguerias as $k => $_drogueria) {
$_drogueria = $_droguerias[$k];
$_Did = $_drogueria["drogtid"];
$_DidEmp = $_drogueria["drogtidemp"];
$_Didcliente = $_drogueria["drogtcliid"];
$_Dnombre = $_drogueria["drogtnombre"];
$_Dlocalidad = $_drogueria["drogtlocalidad"];
if($_drogid == $_Didcliente){
$_drogidemp = $_DidEmp;
?><option value="<?php echo $_Didcliente; ?>" selected><?php echo $_Didcliente." | ".$_Dnombre." | ".$_Dlocalidad; ?></option> <?php
} else { ?>
<option value="<?php echo $_Didcliente; ?>"><?php echo $_Didcliente." | ".$_Dnombre." | ".$_Dlocalidad; ?></option> <?php
}
} ?>
</select> <?php
} ?>
</th>
<th colspan="6" align="right">
<?php echo infoFecha(); ?>
</th>
</tr>
<tr>
<th colspan="3" align="left">
<label for="fecha_liquidacion" >Fecha liquidacion: </label>
<?php echo listar_mes_anio('fecha_liquidacion', $_anio, $_mes, 'javascript:dac_VerMesAnioDrog()', 'width:80px; font-weight:bold; background-color:transparent; border:none;'); ?>
<input hidden id="vermesanio" name="vermesanio" type="text" value="<?php echo $_mes." - ".$_anio; ?>" />
<input hidden id="vermesaniodrog" name="vermesaniodrog" type="submit"/>
</th>
<th colspan="8" align="left">
<input type="file" name="file" id="file">
<?php echo $_importarXLS; ?><?php //echo $_guardar; ?><?php echo $_emitirNC; ?>
<?php //echo $_boton_print; ?><?php echo $_exportarXLS; ?>
</form>
</th>
<th colspan="3"></th>
</tr>
<tr height="60px;"> <!-- Títulos de las Columnas -->
<th align="center">Transfer</th>
<th align="center">Fecha Factura</th>
<th align="center">Nro. Factura</th>
<th align="center">EAN</th>
<th align="center">Artículo</th>
<th align="center">Cantidad</th>
<th align="center">PSL Unit.</th>
<th align="center">Desc. PSL</th>
<th align="center">Importe NC</th>
<th align="center">Cantidad</th>
<th align="center">PSL Unit.</th>
<th align="center">Desc. PSL</th>
<th align="center">Importe NC</th>
<th align="center">Estado</th>
</tr>
</thead>
<tbody id="lista_liquidacion">
<form id="fm_liquidacion_edit" name="fm_liquidacion_edit" method="POST" enctype="multipart/form-data">
<input id="mes_liquidacion" name="mes_liquidacion" type="text" value="<?php echo $_mes; ?>" hidden/>
<input id="anio_liquidacion" name="anio_liquidacion" type="text" value="<?php echo $_anio; ?>" hidden/>
<input id="drogid_liquidacion" name="drogid_liquidacion" type="text" value="<?php echo $_drogid; ?>" hidden/>
<?php
//******************************************//
//Consulta liquidacion del mes actual y su drogueria//
//******************************************//
$_liquidaciones = DataManager::getDetalleLiquidacion($_mes, $_anio, $_drogid, 'TL');
if ($_liquidaciones) {
foreach ($_liquidaciones as $k => $_liq){
$_liq = $_liquidaciones[$k];
$_liqID = $_liq['liqid'];
$_liqFecha = $_liq['liqfecha'];
$_liqTransfer = $_liq['liqnrotransfer'];
$_liqFechaFact = dac_invertirFecha( $_liq['liqfechafact'] );
$_liqNroFact = $_liq['liqnrofact'];
$_liqean = str_replace(" ", "", $_liq['liqean']);
if(!empty($_liqean)){
$_articulo = DataManager::getFieldArticulo("artcodbarra", $_liqean) ;
$_nombreart = $_articulo['0']['artnombre'];
$_idart = $_articulo['0']['artidart'];
}
$_liqcant = $_liq['liqcant'];
$_liqunit = $_liq['liqunitario'];
$_liqdesc = $_liq['liqdescuento'];
$_liqimportenc = $_liq['liqimportenc'];
$_liqactiva = $_liq['liqactiva'];
$_TotalNC += $_liqimportenc;
((($k % 2) != 0)? $clase="par" : $clase="impar");
// CONTROLA las Condiciones de las Liquidaciones y Notas de Crédito//
include($_SERVER['DOCUMENT_ROOT']."/pedidos/transfer/gestion/liquidacion/logica/controles.liquidacion.php");
/*****************/
?>
<tr id="lista_liquidacion<?php echo $k;?>" class="<?php echo $clase;?>">
<input id="idliquid" name="idliquid[]" type="text" value="<?php echo $_liqID;?>" hidden/>
<input id="activa" name="activa[]" type="text" value="<?php echo $_liqactiva;?>" hidden/>
<input id="fecha" name="fecha[]" type="text" value="<?php echo $_liqFecha;?>" hidden/>
<td><input id="transfer" name="transfer[]" type="text" size="7px" value="<?php echo $_liqTransfer;?>" style="border:none; text-align:center;" readonly/></td>
<td><input id="fechafact" name="fechafact[]" type="text" size="8px" value="<?php echo $_liqFechaFact;?>" style="border:none; text-align:center;" readonly/></td>
<td><input id="nrofact" name="nrofact[]" type="text" size="8px" value="<?php echo $_liqNroFact;?>" style="border:none; text-align:center;" readonly/></td>
<td><input id="ean" name="ean[]" type="text" size="12px" value="<?php echo $_liqean;?>" style="border:none; text-align:center;" readonly/></td>
<td><?php echo $_idart." - ".$_nombreart; ?>
<input id="idart" name="idart[]" type="text" value="<?php echo $_idart;?>" readonly hidden/>
</td>
<td><input id="cant" name="cant[]" type="text" size="5px" value="<?php echo $_liqcant;?>" style="border:none; text-align:center;" readonly/></td>
<td><input id="unitario" name="unitario[]" type="text" size="8px" value="<?php echo $_liqunit;?>" style="border:none; text-align:center;" readonly/></td>
<td><input id="desc" name="desc[]" type="text" size="8px" value="<?php echo $_liqdesc;?>" style="border:none; text-align:center;" readonly/></td>
<td><input id="importe" name="importe[]" type="text" size="8px" value="<?php echo $_liqimportenc;?>" style="border:none; text-align:center;" readonly/></td>
<td width="150px" align="center" style="border-bottom:1px #CCCCCC solid; color:#ba140c; font-weight:bold;"><?php echo $_CtrlCant;?></td>
<td width="150px" align="center" style="border-bottom:1px #CCCCCC solid; color:#ba140c; font-weight:bold;"><?php echo $_CtrlPSLUnit;?></td>
<td width="150px" align="center" style="border-bottom:1px #CCCCCC solid; color:#ba140c; font-weight:bold;"><?php echo $_CtrlDescPSL;?></td>
<td width="150px" align="center" style="border-bottom:1px #CCCCCC solid; color:#ba140c; font-weight:bold;"><?php echo $_CtrlImpNT;?></td>
<td align="center"><input id="estado" name="estado[]" type="text" size="8px" value="<?php echo $_Estado; ?>" style="border:none; text-align:center;" readonly/></td>
</tr> <?php
} //FIN del FOR
} else { ?>
<tr class="impar"><td colspan="14" align="center">No hay liquidaciones cargadas</td></tr><?php
}?>
</form>
</tbody>
<tfoot>
<tr>
<th colspan="7" height="30px" style="border:none; font-weight:bold;"></th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;">Total</th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;"><?php echo $_TotalNC; ?></th>
<th colspan="3" height="30px" style="border:none; font-weight:bold;"></th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;"><?php echo $_CtrlTotalNC; ?></th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;"></th>
</tr>
</tfoot>
</table>
<div hidden="hidden"><button id="btnExport" hidden="hidden"></button></div>
</div>
<hr>
<div class="box_body2"> <!-- datos -->
<div class="barra">
<div class="bloque_5">
<h1>Tienen ARTÍCULOS PENDIENTES</h1>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblliquidaciones">
<thead>
<tr>
<td scope="col" width="20%" height="18">Fecha</td>
<td scope="col" width="20%">Transfer</td>
<td scope="col" width="50%">Cliente</td>
<td scope="colgroup" colspan="2" width="10%" align="center">Acciones</td>
</tr>
</thead> <?php
$_fila = 0;
$_liqTransfer_ant = 0;
$_no_existe = 0;
//Recorro cada número de transfer de la liquidación
$_liquidaciones = DataManager::getDetalleLiquidacion($_mes, $_anio, $_drogid, 'TL');
if ($_liquidaciones) {
foreach ($_liquidaciones as $k => $_liq){
$_liq = $_liquidaciones[$k];
$_liqTransfer = $_liq['liqnrotransfer'];
//Si el transfer se repite más de una vez, no hago el control
if ($_liqTransfer != $_liqTransfer_ant){
unset($_idartArray);
//Recorro cualquier liquidación de la droguería que pueda tener con el número transter
$_detalles_trans_liq = DataManager::getDetalleLiquidacionTransfer(NULL, $_drogid, $_liqTransfer, NULL);
if ($_detalles_trans_liq) {
foreach ($_detalles_trans_liq as $i => $_det_tl){
$_det_tl = $_detalles_trans_liq[$i];
$_liqean = str_replace("", "", $_det_tl['liqean']);
$_articulo = DataManager::getFieldArticulo("artcodbarra", $_liqean) ;
$_idart = $_articulo['0']['artidart'];
//Cargo el array de artículos liquidados
$_idartArray[] = $_idart;
}
}
//Recorro los artículos del transfer
$_detalles = DataManager::getTransfersPedido(NULL, NULL, NULL, NULL, NULL, NULL, $_liqTransfer); //DataManager::getDetallePedidoTransfer($_liqTransfer);
if ($_detalles) {
foreach ($_detalles as $j => $_detalle){
$_detalle = $_detalles[$j];
$_drogtransf= $_detalle["ptiddrogueria"];
$_fecha = $_detalle["ptfechapedido"];
$_nombre = $_detalle["ptclirs"];
$_det_idart = $_detalle['ptidart'];
//si la droguería del transfer no coincide con la de la liquidación, no la agrega.
if($_drogid == $_drogtransf) {
//Si algún artículo del transfer no está liquidado, lo agrega a la tabla
if (!in_array($_det_idart, $_idartArray) && $_no_existe == 0) {
$_no_existe = 1;
$_fila = $_fila + 1;
//el artículono NO existe en el array SEGURO SALGA TANTAS VECES COMO ARTÍCULOS DE TRANSFER NO SALGAN EN EL ARRAY
$_conciliar_liq = sprintf( "<a id=\"conciliar\" href=\"/pedidos/transfer/gestion/liquidacion/detalle_liq.php?idpedido=%s\" target=\"_blank\" title=\"Conciliar Liquidación\" >%s</a>", $_liqTransfer, "<img src=\"/pedidos/images/icons/icono-conciliar.png\" border=\"0\" />");
$_detalle = sprintf( "<a href=\"../../detalle_transfer.php?idpedido=%d&backURL=%s\" target=\"_blank\" title=\"detalle pedido\">%s</a>", $_liqTransfer, $_SERVER['PHP_SELF'], "<img src=\"/pedidos/images/icons/icono-lista.png\" border=\"0\" align=\"absmiddle\" />");
echo sprintf("<tr class=\"%s\">", ((($_fila % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_fecha, $_liqTransfer, $_nombre, $_conciliar_liq, $_detalle);
echo sprintf("</tr>");
}
}
}
}
}
$_no_existe = 0;
$_liqTransfer_ant = $_liqTransfer;
}
} else { ?>
<tr>
<td scope="colgroup" colspan="5" height="25" align="center">No hay pedidos Transfer SIN entregar</td>
</tr> <?php
} ?>
</table>
</div> <!-- Fin listar -->
<div class="barra">
<div class="bloque_5">
<h1>Tienen ARTÍCULOS NO PEDIDOS</h1>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblliquidaciones" width="90%" border="0">
<thead>
<tr>
<td scope="col" width="20%" height="18">Fecha</td>
<td scope="col" width="20%">Transfer</td>
<td scope="col" width="50%">Cliente</td>
<td scope="colgroup" width="10%" colspan="2" align="center">Acciones</td>
</tr>
</thead> <?php
//Busco transfers que tengan artículos liquidaros y NO PEDIDOS ¿solo en éste mes?
$_liquidaciones = DataManager::getDetalleLiquidacion($_mes, $_anio, $_drogid, 'TL');
if ($_liquidaciones) {
//recorro todos los artículos que haya en la liquidación
$_nropedido_ant = 0;
foreach ($_liquidaciones as $k => $_liq){
$_liq = $_liquidaciones[$k];
$_liqTransfer = $_liq['liqnrotransfer'];
$_liqean = str_replace("", "", $_liq['liqean']);
$_articulo = DataManager::getFieldArticulo("artcodbarra", $_liqean) ;
$_idart = $_articulo['0']['artidart'];
//pregunto si el artículo de ésta liquidación, existe en el transfer original
//Busco el artículo del nrotransfer en las liquidaciones
$_detalles = DataManager::getTransfersPedido(NULL, NULL, NULL, NULL, NULL, NULL, $_liqTransfer); //DataManager::getDetallePedidoTransfer($_liqTransfer);
if ($_detalles) {
unset($_idartArray);
foreach ($_detalles as $j => $_detalle){
$_detalle = $_detalles[$j];
$_drogtransf = $_detalle["ptiddrogueria"];
$_fecha = $_detalle["ptfechapedido"];
$_nropedido = $_detalle["ptidpedido"];
$_nombre = $_detalle["ptclirs"];
$_det_idart = $_detalle['ptidart'];
$_idartArray[] = $_det_idart;
}
//si el transfer que liquidan no corresponde a la droguería del transfer original, no lo cuenta
if($_drogtransf == $_drogid){
if (!in_array($_idart, $_idartArray) && ($_nropedido_ant != $_nropedido)) {
$_nropedido_ant = $_nropedido;
$_fila = $_fila + 1;
//El Art sale en una liquidacio, pero NO EXISTE PEDIDO en el transfer original
$_conciliar_liq = sprintf( "<a id=\"conciliar\" href=\"/pedidos/transfer/gestion/liquidacion/detalle_liq.php?idpedido=%s\" target=\"_blank\" title=\"Conciliar Liquidación\" >%s</a>", $_nropedido, "<img src=\"/pedidos/images/icons/icono-conciliar.png\" border=\"0\" />");
$_detalle = sprintf( "<a href=\"../../detalle_transfer.php?idpedido=%d&backURL=%s\" target=\"_blank\" title=\"detalle pedido\">%s</a>", $_nropedido, $_SERVER['PHP_SELF'], "<img src=\"/pedidos/images/icons/icono-lista.png\" border=\"0\" align=\"absmiddle\" />");
echo sprintf("<tr class=\"%s\">", ((($_fila % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_fecha, $_nropedido, $_nombre, $_conciliar_liq, $_detalle);
echo sprintf("</tr>");
}
}
}
}
} else { ?>
<tr>
<td scope="colgroup" colspan="4" height="25" align="center">No hay pedidos Transfer con artículos NO PEDIDOS</td>
</tr> <?php
} ?>
</table>
</div> <!-- Fin listar -->
</div> <!-- Fin datos -->
<div class="box_body2">
<div class="barra">
<div class="bloque_5">
<h1>Tienen UNIDADES PENDIENTES</h1>
</div>
<div class="bloque_5">
<?php $exportXLSUnidsPend = sprintf( "<a href=\"logica/exportar.unidades_pendientes.php?drogid=%d&backURL=%s\" title=\"Exportar PENDIENTES\">%s</a>", $_drogid, $_SERVER['PHP_SELF'], "<img class=\"icon-xls-export\"/>");
echo $exportXLSUnidsPend;?>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblliquidaciones">
<thead>
<tr>
<td scope="col" width="20%" height="18">Fecha</td>
<td scope="col" width="20%">Transfer</td>
<td scope="col" width="50%">Cliente</td>
<td scope="colgroup" width="10%" colspan="2" align="center">Acciones</td>
</tr>
</thead> <?php
$_transfers_liquidados = DataManager::getTransfersLiquidados(NULL, 'LP', $_drogid);
if ($_transfers_liquidados) {
for( $k=0; $k < count($_transfers_liquidados); $k++ ){
$_detalle = $_transfers_liquidados[$k];
$_fecha = $_detalle["ptfechapedido"];
$_nropedido = $_detalle["ptidpedido"];
$_nombre = $_detalle["ptclirs"];
$_conciliar_liq = sprintf( "<a id=\"conciliar\" href=\"/pedidos/transfer/gestion/liquidacion/detalle_liq.php?idpedido=%s\" target=\"_blank\" title=\"Conciliar Liquidación\" >%s</a>", $_nropedido, "<img src=\"/pedidos/images/icons/icono-conciliar.png\" border=\"0\" />");
$_detalle = sprintf( "<a href=\"../../detalle_transfer.php?idpedido=%d&backURL=%s\" target=\"_blank\" title=\"detalle pedido\">%s</a>", $_nropedido, $_SERVER['PHP_SELF'], "<img src=\"/pedidos/images/icons/icono-lista.png\" border=\"0\" align=\"absmiddle\" />");
$_status = "<img src=\"/pedidos/images/icons/icono-LP-LT.png\" border=\"0\" align=\"absmiddle\" title=\"Pasar LP a LT\"/>";
$_borrar = sprintf( "<a href=\"logica/changestatus.php?nropedido=%d&status='LP'&backURL=%s\" title=\"Pasar a LT\">%s</a>", $_nropedido, $_SERVER['PHP_SELF'], $_status);
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_fecha, $_nropedido, $_nombre, $_borrar, $_conciliar_liq, $_detalle);
echo sprintf("</tr>");
}
} else { ?>
<tr>
<td scope="colgroup" colspan="4" height="25" align="center">No hay Transfer con UNIDADES PENDIENTES</td>
</tr> <?php
} ?>
</table>
</div> <!-- Fin listar -->
<div class="barra">
<div class="bloque_5">
<h1>Tienen UNIDADES EXCEDENTES</h1>
</div>
<div class="bloque_5">
<?php $exportXLSUnidsExced = sprintf( "<a href=\"logica/exportar.unidades_excedentes.php?drogid=%d&backURL=%s\" title=\"Exportar EXCEDENTES\">%s</a>", $_drogid, $_SERVER['PHP_SELF'], "<img class=\"icon-xls-export\"/>");
echo $exportXLSUnidsExced;?>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblliquidaciones" width="90%" border="0">
<thead>
<tr>
<td scope="col" width="20%" height="18">Fecha</td>
<td scope="col" width="20%">Transfer</td>
<td scope="col" width="50%">Cliente</td>
<td scope="colgroup" width="10%" colspan="3" align="center">Acciones</td>
</tr>
</thead> <?php
$_transfers_liquidados = DataManager::getTransfersLiquidados(NULL, 'LE', $_drogid);
if ($_transfers_liquidados) {
for( $k=0; $k < count($_transfers_liquidados); $k++ ){
$_detalle = $_transfers_liquidados[$k];
$_fecha = $_detalle["ptfechapedido"];
$_nropedido = $_detalle["ptidpedido"];
$_nombre = $_detalle["ptclirs"];
$_conciliar_liq = sprintf( "<a id=\"conciliar\" href=\"/pedidos/transfer/gestion/liquidacion/detalle_liq.php?idpedido=%s\" target=\"_blank\" title=\"Conciliar Liquidación\" >%s</a>", $_nropedido, "<img src=\"/pedidos/images/icons/icono-conciliar.png\" border=\"0\" />");
$_detalle = sprintf( "<a href=\"../../detalle_transfer.php?idpedido=%d&backURL=%s\" target=\"_blank\" title=\"detalle pedido\">%s</a>", $_nropedido, $_SERVER['PHP_SELF'], "<img src=\"/pedidos/images/icons/icono-lista.png\" border=\"0\" align=\"absmiddle\" />");
$_status = "<img src=\"/pedidos/images/icons/icono-LE-LT.png\" border=\"0\" align=\"absmiddle\" title=\"Pasar LE a LT\"/>";
$_borrar = sprintf( "<a href=\"logica/changestatus.php?nropedido=%d&status='LE'&backURL=%s\" title=\"Pasar a LT\">%s</a>", $_nropedido, $_SERVER['PHP_SELF'], $_status);
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_fecha, $_nropedido, $_nombre, $_borrar, $_conciliar_liq, $_detalle);
echo sprintf("</tr>");
}
} else { ?>
<tr>
<td scope="colgroup" colspan="5" height="25" align="center">No hay Transfer CON UNIDADES EXCEDENTES</td>
</tr> <?php
} ?>
</table>
</div> <!-- Fin listar -->
</div> <!-- Fin boxdatosuper -->
<!-- Scripts para IMPORTAR ARCHIVO -->
<script type="text/javascript" src="/pedidos/transfer/gestion/liquidacion/logica/jquery/jquery.script.file.js"></script>
<!--script type="text/javascript" src="logica/jquery/jquery.process.liquidacion.js"></script-->
<script type="text/javascript" src="logica/jquery/jquery.process.emitirnc.js"></script>
<script type="text/javascript">
function dac_VerMesAnioDrog(){ document.getElementById("vermesaniodrog").click();}
</script><file_sep>/transfer/logica/jquery/jqueryHeader.js
//-----------------------------------/
// Limpia Artículos del Pedido
function dac_limpiarArticulos(){
"use strict";
$('#pwsubtotal').html('');
$("#lista_articulos2").empty();
}
function dac_mostrarCuentasRelacionada(id){
"use strict";
var nro = document.getElementById('tblTransfer').value; //la primera será cero
document.getElementById('tblTransfer').value = id;
if(nro !== id){
dac_limpiarArticulos();
document.getElementById(id).style.display = 'block';
document.getElementById(nro).style.display = 'none';
$("#detalle_cuenta").empty();//limpia contenido de cuentas
}
}
//**************//
// Carga %ABM //
function dac_CargarDescAbm(id) {
"use strict";
var elem = document.getElementsByName("cuentaId[]");
var drogid = '';
for (var i = 0; i < elem.length; ++ i) {
drogid = elem[i].value;
}
var artid = document.getElementById("ptidart"+id).value;
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/transfer/logica/ajax/cargar.abm.php',
data:{ drogid : drogid,
artid : artid
},
beforeSend: function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (result) {
if (result){
$('#box_cargando').css({'display':'none'});
if (result.replace("\n","") === '1'){
$('#box_error').css({'display':'block'});
$("#msg_error").html("Hubo un error en la carga autom\u00e1tica de descuento del AMB del art\u00edculo agregado, o no existe en el ABM del mes actual.");
} else {
document.getElementById("ptdesc"+id).value = result;
}
}
},
error: function () {
$('#box_cargando2').css({'display':'none'});
$('#box_error2').css({'display':'block'});
$("#msg_error2").html("Error en el proceso de control de ABM");
}
});
}
//**************//
// SUBTOTAL //
function dac_CalcularSubtotalTransfer(){
"use strict";
var cantArts = document.getElementsByName('ptidart[]').length;
var subtotal = 0;
for(var i = 0; i < cantArts; i++){
var ptprecio= document.getElementsByName("ptprecioart[]").item(i).value;
var ptcant = document.getElementsByName("ptcant[]").item(i).value;
var ptdesc = document.getElementsByName("ptdesc[]").item(i).value;
var total = ptcant * ptprecio;
var desc = total * ptdesc/100;
subtotal += total - desc;
}
document.getElementById("ptsubtotal").style.display = 'block';
$('#ptsubtotal').html('<strong>Subtotal: $ '+subtotal.toFixed(2)+ '</strong> (No refleja IVA)');
}
//*****************************************//
// Crea Div de Cuenta Transfer relacionada //
var nextCuentaTransfer = 0;
function dac_cargarCuentaTransferRelacionada(id, idCta, idCuenta, nombre, nroClienteTransfer, ctaRelEmpresa){
"use strict";
//limpia el contenido de detalle_cuenta
dac_limpiarArticulos();
$("#detalle_cuenta").empty();
nextCuentaTransfer++;
var campo = '<div id="rutcuenta'+nextCuentaTransfer+'">';
campo +='<div class="bloque_7"><input id="cuentaIdTransfer'+nextCuentaTransfer+'" name="cuentaIdTransfer[]" type="text" placeholder="Cliente Transfer" value="'+nroClienteTransfer+'" readonly/></div>';
campo +='<div class="bloque_4"><input id="cuentaId'+nextCuentaTransfer+'" name="cuentaId[]" type="text" value='+idCta+' hidden/> '+idCuenta+" - "+nombre.substring(0,25)+'</div>';
campo +='<div class="bloque_8"><input id="btmenos" class="btmenos" type="button" value=" - " onClick="dac_deleteCuentaTransferRelacionada('+id+', '+nextCuentaTransfer+')"></div>';
campo +='</div>';
$("#detalle_cuenta").append(campo);
dac_CargarArticulos(ctaRelEmpresa, 1);
}
/********************/
/* Carga Artículos */
function dac_CargarArticulos(idEmpresa, idlab, condicion){
"use strict";
$.ajax({
type : 'POST',
cache: false,
url : 'logica/ajax/getArticulos.php',
data: { laboratorio : idlab,
empresa : idEmpresa,
condicion : condicion,
},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
$('#box_cargando3').css({'display':'block'});
$("#msg_cargando3").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
$('#box_cargando').css({'display':'none'});
if (resultado){
document.getElementById('tablaarticulos').innerHTML = resultado;
$('#box_cargando3').css({'display':'none'});
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_cargando3').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los artículos.");
},
});
}<file_sep>/agenda/ajax/deleteEvents.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$id = (isset($_POST['id']))? $_POST['id'] : NULL;
if ($id) {
$eventObject = DataManager::newObjectOfClass('TAgenda', $id);
$eventObject->__set('ID', $id );
$ID = DataManager::deleteSimpleObject($eventObject);
}
echo $ID; exit;
?><file_sep>/usuarios/lista.php
<?php
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/usuarios/': $_REQUEST['backURL'];
$btnNuevo = sprintf( "<a href=\"editar.php\" title=\"Nuevo\"><img class=\"icon-new\"/></a>");
?>
<div class="box_body">
<div class="barra">
<div class="bloque_5">
<h1>Vendedores</h1>
</div>
<div class="bloque_7">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn" type="text" value="tblUsuarios" hidden/>
</div>
<div class="bloque_7">
<?php echo $btnNuevo; ?>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblUsuarios">
<thead>
<tr>
<th scope="col" width="20%" height="18">Usuario</th>
<th scope="colgroup" width="50%">Nombre</th>
<th scope="colgroup" width="10%">Dni</th>
<th scope="colgroup" colspan="4" align="center" width="20%">Acciones</th>
</tr>
</thead>
<?php
$_LPP = 50;
$_total = count(DataManager::getUsuarios( 0, 0, NULL, NULL, '"V"'));
$_paginas = ceil($_total/$_LPP);
$_pag = isset($_REQUEST['pag']) ? min(max(1,$_REQUEST['pag']),$_paginas) : 1;
$_GOFirst = sprintf("<a class=\"icon-go-first\" href=\"%s?pag=%d\"></a>", $backURL, 1);
$_GOPrev = sprintf("<a class=\"icon-go-previous\" href=\"%s?pag=%d\"></a>", $backURL, $_pag-1);
$_GONext = sprintf("<a class=\"icon-go-next\" href=\"%s?pag=%d\"></a>", $backURL, $_pag+1);
$_GOLast = sprintf("<a class=\"icon-go-last\" href=\"%s?pag=%d\"></a>", $backURL, $_paginas);
$usuarios = DataManager::getUsuarios( $_pag, $_LPP, NULL, NULL, '"V"');
$_max = count($usuarios);
for( $k=0; $k < $_max; $k++ ) {
if ($k < $_LPP) {
$usuario = $usuarios[$k];
$nombre = $usuario['unombre'];
$usr = $usuario['ulogin'];
$dni = $usuario['udni'];
$_status = ($usuario['uactivo']) ? "<img class=\"icon-status-active\"/>" : "<img class=\"icon-status-inactive\"/>";
$_editar = sprintf( "<a href=\"editar.php?uid=%d&backURL=%s\" title=\"editar usuario\">%s</a>", $usuario['uid'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit\"/>");
$_zona = sprintf( "<a href=\"editar.zona.php?uid=%d&backURL=%s\" title=\"Editar Zona\">%s</a>", $usuario['uid'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit-zone\"/>");
$_borrar = sprintf( "<a href=\"logica/changestatus.php?uid=%d&backURL=%s&pag=%s\" title=\"Cambiar Estado\">%s</a>", $usuario['uid'], $_SERVER['PHP_SELF'], $_pag, $_status);
$_eliminar = sprintf ("<a href=\"logica/eliminar.usuario.php?uid=%d&backURL=%s\" title=\"eliminar cliente\" onclick=\"return confirm('¿Está Seguro que desea ELIMINAR EL USUARIO?')\"> <img class=\"icon-delete\" /> </a>", $usuario['uid'], $_SERVER['PHP_SELF'], "eliminar");
} else {
$nombre = " ";
$usr = " ";
$dni = " ";
$_editar = " ";
$_zona = " ";
$_borrar = " ";
$_eliminar = " ";
}
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $usr, $nombre, $dni, $_editar, $_zona, $_borrar, $_eliminar);
echo sprintf("</tr>");
}?>
</table>
</div> <!-- Fin listar -->
<?php
if ( $_paginas > 1 ) {
$_First = ($_pag > 1) ? $_GOFirst : " ";
$_Prev = ($_pag > 1) ? $_GOPrev : " ";
$_Last = ($_pag < $_paginas) ? $_GOLast : " ";
$_Next = ($_pag < $_paginas) ? $_GONext : " ";
echo("<table class=\"paginador\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
echo sprintf("<td height=\"16\">Mostrando página %d de %d</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td>", $_pag, $_paginas, $_First, $_Prev, $_Next, $_Last);
echo("</tr></table>");
}
?>
</div> <!-- Fin datos -->
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Administrador Web</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar2" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn2" type="text" value="tblAdmWeb" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<table id="tblAdmWeb">
<thead>
<tr>
<th scope="col" width="20%" height="18">Usuario</th>
<th scope="colgroup" width="50%">Nombre</th>
<th scope="colgroup" colspan="4" align="center" width="30%">Acciones</th>
</tr>
</thead>
<?php
$usuarios = DataManager::getUsuarios( 0, 0, NULL, NULL, '"A"');
foreach ($usuarios as $k => $usuario) {
$nombre = $usuario['unombre'];
$usr = $usuario['ulogin'];
$_status= ($usuario['uactivo']) ? "<img class=\"icon-status-active\"/>" : "<img class=\"icon-status-inactive\"/>";
$_editar= sprintf( "<a href=\"editar.php?uid=%d&backURL=%s\" title=\"editar usuario\">%s</a>", $usuario['uid'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit\" />");
$_zona = sprintf( "<a href=\"editar.zona.php?uid=%d&backURL=%s\" title=\"Editar Zona\">%s</a>", $usuario['uid'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit-zone\" />");
$_borrar= sprintf( "<a href=\"logica/changestatus.php?uid=%d&backURL=%s&pag=%s\" title=\"Cambiar Estado\">%s</a>", $usuario['uid'], $_SERVER['PHP_SELF'], $_pag, $_status);
$_eliminar = sprintf ("<a href=\"logica/eliminar.usuario.php?uid=%d&backURL=%s\" title=\"eliminar cliente\" onclick=\"return confirm('¿Está Seguro que desea ELIMINAR EL USUARIO?')\"> <img class=\"icon-delete\" /> </a>", $usuario['uid'], $_SERVER['PHP_SELF'], "eliminar");
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $usr, $nombre, $_editar, $_zona, $_borrar, $_eliminar);
echo sprintf("</tr>");
}?>
</table>
</div> <!-- Fin listar -->
<div class="barra">
<div class="bloque_5">
<h1>Gerencias</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar3" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn3" type="text" value="tblGerencias" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<table id="tblGerencias">
<thead>
<tr>
<th scope="col" width="20%" height="18">Usuario</th>
<th scope="colgroup" width="50%">Nombre</th>
<th scope="colgroup" colspan="4" align="center" width="30%">Acciones</th>
</tr>
</thead>
<?php
$usuarios = DataManager::getUsuarios( 0, 0, NULL, NULL, '"G"');
foreach ($usuarios as $k => $usuario) {
$nombre = $usuario['unombre'];
$usr = $usuario['ulogin'];
$_status= ($usuario['uactivo']) ? "<img class=\"icon-status-active\"/>" : "<img class=\"icon-status-inactive\"/>";
$_editar= sprintf( "<a href=\"editar.php?uid=%d&backURL=%s\" title=\"editar usuario\">%s</a>", $usuario['uid'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit\"/>");
$_zona = sprintf( "<a href=\"editar.zona.php?uid=%d&backURL=%s\" title=\"Editar Zona\">%s</a>", $usuario['uid'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit-zone\" />");
$_borrar= sprintf( "<a href=\"logica/changestatus.php?uid=%d&backURL=%s&pag=%s\" title=\"Cambiar Estado\">%s</a>", $usuario['uid'], $_SERVER['PHP_SELF'], $_pag, $_status);
$_eliminar = sprintf ("<a href=\"logica/eliminar.usuario.php?uid=%d&backURL=%s\" title=\"eliminar cliente\" onclick=\"return confirm('¿Está Seguro que desea ELIMINAR EL USUARIO?')\"> <img class=\"icon-delete\"/> </a>", $usuario['uid'], $_SERVER['PHP_SELF'], "eliminar");
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $usr, $nombre, $_editar, $_zona, $_borrar, $_eliminar);
echo sprintf("</tr>");
}?>
</table>
</div> <!-- Fin listar -->
<div class="barra">
<div class="bloque_5">
<h1>Administracion</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar4" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn4" type="text" value="tblAdministracion" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<table id="tblAdministracion">
<thead>
<tr>
<th scope="col" width="20%" height="18">Usuario</th>
<th scope="colgroup" width="50%">Nombre</th>
<th scope="colgroup" colspan="4" align="center" width="30%">Acciones</th>
</tr>
</thead>
<?php
$usuarios = DataManager::getUsuarios( 0, 0, NULL, NULL, '"M"');
foreach ($usuarios as $k => $usuario) {
$nombre = $usuario['unombre'];
$usr = $usuario['ulogin'];
$_status= ($usuario['uactivo']) ? "<img class=\"icon-status-active\"/>" : "<img class=\"icon-status-inactive\"/>";
$_editar= sprintf( "<a href=\"editar.php?uid=%d&backURL=%s\" title=\"editar usuario\">%s</a>", $usuario['uid'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit\"/>");
$_borrar= sprintf( "<a href=\"logica/changestatus.php?uid=%d&backURL=%s&pag=%s\" title=\"Cambiar estado\">%s</a>", $usuario['uid'], $_SERVER['PHP_SELF'], $_pag, $_status);
$_zona = sprintf( "<a href=\"editar.zona.php?uid=%d&backURL=%s\" title=\"Editar Zona\">%s</a>", $usuario['uid'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit-zone\" />");
$_eliminar = sprintf ("<a href=\"logica/eliminar.usuario.php?uid=%d&backURL=%s\" title=\"eliminar cliente\" onclick=\"return confirm('¿Está Seguro que desea ELIMINAR EL USUARIO?')\"> <img class=\"icon-delete\"/> </a>", $usuario['uid'], $_SERVER['PHP_SELF'], "eliminar");
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $usr, $nombre, $_editar, $_zona, $_borrar, $_eliminar);
echo sprintf("</tr>");
}?>
</table>
</div> <!-- Fin listar -->
</div> <!-- Fin datos -->
<file_sep>/includes/classHiper/class.articulo.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/pedidos/includes/class/class.PropertyObject.php');
class THiperArticulo extends PropertyObject {
protected $_tablename = 'Articulos';
protected $_fieldid = 'artid';
protected $_fieldactivo = 'artactivo';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManagerHiper::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'artid';
$this->propertyTable['Empresa'] = 'IdEmpresa';
$this->propertyTable['Laboratorio'] = 'IdLab';
$this->propertyTable['Articulo'] = 'IdArt';
$this->propertyTable['Nombre'] = 'NombreART';
$this->propertyTable['Precio'] = 'PrecioART';
$this->propertyTable['PrecioLista'] = 'PrecioListaART';
$this->propertyTable['PrecioCompra']= 'PrecioComART';
$this->propertyTable['PrecioReposicion']= 'PrecioRepART';
$this->propertyTable['FechaCompra'] = 'FechaComART';
$this->propertyTable['IVA'] = 'Cod_IvaART';
$this->propertyTable['Rubro'] = 'IdRubro';
$this->propertyTable['Lista'] = 'IdLista';
$this->propertyTable['Medicinal'] = 'Medicinal';
$this->propertyTable['CodigoBarra'] = 'CodigoBarras';
$this->propertyTable['UsrUpdate'] = 'artusrupdate';
$this->propertyTable['LastUpdate'] = 'artlastupdate';
$this->propertyTable['Stock'] = 'artstock';
$this->propertyTable['Imagen'] = 'artimagen';
$this->propertyTable['Activo'] = 'artactivo';
$this->propertyTable['Descripcion'] = 'artdescripcion';
$this->propertyTable['Dispone'] = 'artiddispone';
$this->propertyTable['Familia'] = 'artidfamilia';
$this->propertyTable['Ganancia'] = 'artganancia';
$this->propertyTable['Oferta'] = 'Cond_OfertaART';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/includes/menu.admin.php
<?php if ($_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="M" ){?>
<header>
<div id="navegador" align="center">
<nav2>
<ul>
<?php if ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="M"){ ?>
<li class="<?php echo ($_section=="movimientos") ? "current_menu" : "boton_menu";?>">
<a href="/pedidos/movimientos/">Movimientos</a>
</li>
<?php } ?>
<?php if ($_SESSION["_usrrol"]=="A" ){ ?>
<li class="<?php echo ($_section=="contactos") ? "current_menu" : "boton_menu";?>">
<a href="#">Contactos</a>
<ul id="uno">
<li class="<?php echo ($_subsection=="nuevo_contacto") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/contactos/editar.php">Nuevo Contacto</a>
</li>
</ul>
</li>
<li class="<?php echo ($_section=="newsletter") ? "current_menu" : "boton_menu";?>">
<a href="#">Enviar Newsletter</a> <!-- /pedidos/newsletter/logica/newsletter.php -->
</li>
<li class="<?php echo ($_section=="noticias") ? "current_menu" : "boton_menu";?>">
<a href="/pedidos/noticias">Noticias</a>
</li>
<li class="<?php echo ($_section=="reportes") ? "current_menu" : "boton_menu";?>">
<a href="/pedidos/reportes/">Reportes</a>
</li>
<li class="<?php echo ($_section=="soporte") ? "current_menu" : "boton_menu";?>">
<a href="#">Soporte</a>
<ul id="dos">
<li class="<?php echo ($_subsection=="soporte_resolver") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/soporte/tickets/resolver/">Resolver Tickets</a>
</li>
<li class="<?php echo ($_subsection=="soporte_motivos") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/soporte/motivos/">Motivos</a>
</li>
</ul>
</li>
<li class="<?php echo ($_section=="usuarios") ? "current_menu" : "boton_menu";?>">
<a href="/pedidos/usuarios">Usuarios</a>
</li>
<li class="<?php echo ($_section=="localidades") ? "current_menu" : "boton_menu";?>">
<a href="/pedidos/localidades/">Localidades</a>
</li>
<?php } ?>
</ul>
</nav>
</div>
</header>
<?php } ?><file_sep>/cuentas/logica/jquery/cargar.cuentasTransferRelacionada.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
echo '<table id="tblCuentasTransfer" border="0" align="center">';
echo '<thead><tr align="left"><th>Id</th><th>Nombre</th><th>Localidad</th></tr></thead>';
echo '<tbody>';
$drogueriasTransfer = DataManager::getDrogueria(1);
if (count($drogueriasTransfer)) {
foreach ($drogueriasTransfer as $k => $drogTrans) {
$id = $drogTrans['drogtid'];
$idEmpCtaDrog= $drogTrans['drogtidemp'];
$idCtaDrog = $drogTrans['drogtcliid'];
$ctaId = DataManager::getCuenta('ctaid', 'ctaidcuenta', $idCtaDrog, $idEmpCtaDrog);
$idCuenta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $ctaId);
$nombre = DataManager::getCuenta('ctanombre', 'ctaid', $ctaId);
$idLoc = DataManager::getCuenta('ctaidloc', 'ctaid', $ctaId);
$localidad = DataManager::getLocalidad('locnombre', $idLoc);
$clienteTransfer = "";
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr id=cuenta".$id." class=".$clase." onclick=\"javascript:dac_cargarCuentaTransferRelacionada2('$id', '$ctaId', '$idCuenta', '$nombre', '$clienteTransfer' )\" style=\"cursor:pointer;\"><td>".$idCuenta."</td><td>".$nombre."</td><td>".$localidad."</td></tr>";
}
} else {
echo "<tr><td colspan=\"3\"></br>No hay cuentas activas en la empresa seleccionada</td></tr>";
}
echo '</tbody></table>';
exit;
?><file_sep>/condicion/logica/ajax/change.status.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$arrayIdCond = empty($_POST['condid']) ? 0 : $_POST['condid'];
if(!$arrayIdCond){
echo "Seleccione condición para modificar."; exit;
}
if(count($arrayIdCond)){
foreach ($arrayIdCond as $j => $condId) {
if ($condId) {
$condObject = DataManager::newObjectOfClass('TCondicionComercial', $condId);
$status = ($condObject->__get('Activa')) ? 0 : 1;
$condObject->__set('Activa', $status);
DataManagerHiper::updateSimpleObject($condObject, $condId);
DataManager::updateSimpleObject($condObject);
// Registro MOVIMIENTO
$movimiento = 'ChangeStatus_a_'.$status;
dac_registrarMovimiento($movimiento, 'UPDATE', 'TCondicionComercial', $condId);
} else {
echo "Error al consultar los registros."; exit;
}
}
echo "1"; exit;
} else {
echo "Seleccione una condición."; exit;
}
echo "Error de proceso."; exit;
?><file_sep>/proveedores/fechaspago/logica/importar_facturas.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/PHPExcel/PHPDacExcel.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$mensage = '';//Declaramos una variable mensaje que almacenara el resultado de las operaciones.
if ($_FILES){
foreach ($_FILES as $key){ //Iteramos el arreglo de archivos
if($key['error'] == UPLOAD_ERR_OK ){//Si el archivo se paso correctamente Continuamos
//antes de importar el EXCEL debería eliminar en esa fecha y droguería, cualquier dato existente de facturas inactivas
$_factobject = DataManager::deletefromtabla('facturas_proveedor', 'factactiva', 0);
//Convierto el excel en un array de arrays
$archivo_temp = $key['tmp_name']; //Obtenemos la ruta Original del archivo
$arrayxls = PHPDacExcel::xls2array($archivo_temp);
for($j=1; $j < count($arrayxls); $j++){
if(count($arrayxls[$j]) != 10){
echo 'Está intentando importar un archivo con diferente cantidad de campos (deben ser 10)'; exit;
} else {
//procedo a cargar los datos
$_factobject = DataManager::newObjectOfClass('TFacturaProv');
$_factobject->__set('ID' , $_factobject->__newID());
$_factobject->__set('Empresa' , $arrayxls[$j][0]);
$_factobject->__set('Proveedor' , $arrayxls[$j][1]);
$_factobject->__set('Plazo' , $arrayxls[$j][3]);
$_factobject->__set('Tipo' , $arrayxls[$j][4]);
$_factobject->__set('Sucursal' , $arrayxls[$j][5]);
$_factobject->__set('Numero' , $arrayxls[$j][6]);
$_factobject->__set('Comprobante' , dac_fecha_xlsToDate($arrayxls[$j][7]));
$_factobject->__set('Vencimiento' , dac_fecha_xlsToDate($arrayxls[$j][8]));
$_factobject->__set('Saldo' , $arrayxls[$j][9]);
$_factobject->__set('Pago' , '2001-01-01');
$_factobject->__set('Observacion' , '');
$_factobject->__set('Activa' , 0);
$ID = DataManager::insertSimpleObject($_factobject);
}
}
}
if ($key['error']==''){ //Si no existio ningun error, retornamos un mensaje por cada archivo subido
$mensage .= count($arrayxls)-1;
//$mensage .= 'Archivo Subido correctamente con '.(count($arrayxls)-1).' registros';
} else {
//if ($key['error']!=''){//Si existio algún error retornamos un el error por cada archivo.
$mensage .= '-> No se pudo subir el archivo debido al siguiente Error: \n'.$key['error'];
}
}
} else { $mensage .= 'Debe seleccionar algún archivo para enviar.'; }
echo $mensage;// Regresamos los mensajes generados al cliente
?><file_sep>/droguerias/logica/ajax/getCuentasDrogueria.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
//------------------
$empresa = (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
$drogidCAD = (isset($_POST['drogidCAD'])) ? $_POST['drogidCAD'] : NULL;
//-------------------
$datosJSON;
$droguerias = DataManager::getDrogueria(NULL, $empresa, $drogidCAD);
if (count($droguerias)) {
foreach ($droguerias as $k => $drog) {
$id = $drog['drogtid'];
$cuenta = $drog['drogtcliid'];
$nombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $cuenta, $empresa);
$idLoc = DataManager::getCuenta('ctaidloc', 'ctaidcuenta', $cuenta, $empresa);
$localidad = DataManager::getLocalidad('locnombre', $idLoc);
$rentTl = $drog['drogtrentabilidadtl'];
$rentTD = $drog['drogtrentabilidadtd'];
$datosJSON[]= array(
"id" => $id,
"cuenta" => $cuenta,
"nombre" => $nombre,
"localidad" => $localidad,
"rentTl" => $rentTl,
"rentTd" => $rentTD
);
}
}
/*una vez tenemos un array con los datos los mandamos por json a la web*/
header('Content-type: application/json');
echo json_encode($datosJSON);
?><file_sep>/droguerias/logica/eliminar.drogueria.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/droguerias/': $_REQUEST['backURL'];
$drogIdCAD = empty($_REQUEST['drogid']) ? 0 : $_REQUEST['drogid']; //ID de la droguería
if ($drogIdCAD) {
//eliminar cuentas relacionadas
$cuentasDroguerias = DataManager::getDrogueria(NULL, NULL, $drogIdCAD);
if (count($cuentasDroguerias)) {
foreach($cuentasDroguerias as $k => $drog) {
$id = $drog['drogtid'];
$drogObject = DataManager::newObjectOfClass('TDrogueria', $id);
$drogObject->__set('ID', $id);
DataManagerHiper::deleteSimpleObject($drogObject, $id);
DataManager::deleteSimpleObject($drogObject);
}
}
//eliminar drogueria
$drogCadObject = DataManager::newObjectOfClass('TDrogueriaCAD', $drogIdCAD);
$drogCadObject->__set('ID', $drogIdCAD );
DataManagerHiper::deleteSimpleObject($drogCadObject, $drogIdCAD);
DataManager::deleteSimpleObject($drogCadObject);
} else {
echo "Error al intentar eliminar registros."; exit;
}
header('Location: '.$backURL);
?><file_sep>/relevamiento/logica/eliminar.relevamiento.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$_relid = empty($_REQUEST['relid']) ? 0 : $_REQUEST['relid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/clientes/': $_REQUEST['backURL'];
if ($_relid) {
$_relobject = DataManager::newObjectOfClass('TRelevamiento', $_relid);
$_relobject->__set('ID', $_relid );
$ID = DataManager::deleteSimpleObject($_relobject);
}
header('Location: '.$backURL.'?pag='.$_pag);
?><file_sep>/proveedores/logica/upload.file.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
$_provid = (isset($_POST['provid'])) ? $_POST['provid'] : NULL;
$ruta = $_SERVER['DOCUMENT_ROOT'].'/pedidos/login/registrarme/archivos/proveedor/'.$_provid.'/';
if(empty($_provid)){
echo "Ocurrió un error en el código del proveedor"; exit;
}
$mensage = '';//Declaramos una variable mensaje quue almacenara el resultado de las operaciones.
if ($_FILES){
foreach ($_FILES as $key){ //Iteramos el arreglo de archivos
$temporal = '';
if($key['error'] == UPLOAD_ERR_OK ){//Si el archivo se paso correctamente Ccontinuamos
$nombreOriginal = dac_sanearString($key['name']); //Obtenemos el nombre original del archivo
$temporal = $key['tmp_name'];//$key['tmp_name']; //Obtenemos la ruta Original del archivo
//$Destino = $ruta.$nombreOriginal; //Creamos una ruta de destino con la variable ruta y el nombre original del archivo
$destino = $ruta;
if(file_exists($destino) || @mkdir($destino, 0777, true)) {
$info = new SplFileInfo($nombreOriginal);
$destino = $destino.'documentoF'.date("dmYHms").".".$info->getExtension();
move_uploaded_file($temporal, $destino);
} else {echo "Error al intentar crear el archivo."; exit;}
//move_uploaded_file($temporal, $Destino); //Movemos el archivo temporal a la ruta especificada
}
if ($key['error']==''){ //Si no existio ningun error, retornamos un mensaje por cada archivo subido
$mensage .= '<b>'.$nombreOriginal.'</b> Subido correctamente. <br>';
}
if ($key['error']!=''){//Si existio algún error retornamos un el error por cada archivo.
echo 'No se pudo subir el archivo <b>'.$nombreOriginal.'</b> debido al siguiente Error: \n'.$key['error']; exit;
//$mensage .= '-> No se pudo subir el archivo <b>'.$nombreOriginal.'</b> debido al siguiente Error: \n'.$key['error'];
}
}
} else {
echo '<b> Debe seleccionar algún archivo para enviar</b> <br>'; exit;
//$mensage .= '</b> Debe seleccionar algún archivo para enviar. <br>';
}
echo $mensage;// Regresamos los mensajes generados al cliente
?><file_sep>/includes/menu.televenta.php
<!--
Ojo con las siguientes variables!
var origen = document.getElementById('origen').value;
var idorigen = document.getElementById('idorigen').value;
var nroRel = <?php //echo $_nroRel;?>;
var telefono = document.getElementById('telefono').value;
-->
<script>
$(function() {
$("#llamada").accordion({
//active: 0 inicia con el número de barra desplegado que elija desde el 0 (primero por defecto) en adelante
//event: "mouseover" se activan con mouseover en vez del clic
collapsible: true,
icons: { "header": "ui-icon-plus", "activeHeader": "ui-icon-minus" },
heightStyle: "content" //"auto" //"fill" / "content"
});
});
$(window).resize(function(e) {
$("#dialogo").dialog("close");
$("#dialogo").dialog("open");
$("#reprogramar").dialog("close");
$("#reprogramar").dialog("open");
});
</script>
<div id="dialogo" style="display:none;"></div>
<div id="reprogramar" style="display:none;"></div>
<div id="llamada" align="left">
<!-- Button -->
<h3>Llamada</h3>
<div>
<div class="bloque_5">
<select id="contesta" name="contesta" style="height:45px;">
<option value="1" selected>No Contesta</option>
<option value="2">Ocupado</option>
<option value="3">Si Contesta</option>
</select>
</div>
<div class="bloque_5">
<button id="button" style="width:140px;">
<img class="icon-phone"/>
</button>
</div>
</div>
<h3>Resumen marcaciones</h3>
<div> <?php
$arrayLlamadas = array();
$_si_contesta = 0;
$_no_contesta = 0;
$_ocupado = 0;
$_incidencia = 0;
//--------------//
$_si_contesta_hoy = 0;
$_no_contesta_hoy = 0;
$_ocupado_hoy = 0;
$_incidencia_hoy = 0;
$_llamadas = DataManager::getLlamadas(NULL, NULL, $_idorigen, $_origen, 0);
if (count($_llamadas)) {
foreach ($_llamadas as $k => $_llam) {
$_tiporesultado = $_llam["llamtiporesultado"];
$_ultima_fecha = $_llam["llamfecha"];
$_fechasllamadas= explode(" ", $_ultima_fecha);
$_llamfecha = explode("-", $_fechasllamadas[0]);
$_resultado = $_llam["llamtiporesultado"]." - ".$_llam["llamresultado"];
$_telefono = $_llam["llamtelefono"];
$_usrUpdate = $_llam["llamusrupdate"];
$_usrName = DataManager::getUsuario('unombre', $_usrUpdate);
$_observacion = $_llam["llamobservacion"];
switch($_tiporesultado){
case 'contesta':
$_si_contesta++;
break;
case 'ocupado':
$_ocupado++;
break;
case 'no contesta':
$_no_contesta++;
break;
case 'incidencia':
$_incidencia++;
break;
}
if($_llamfecha[0] == date("Y") && $_llamfecha[1] == date("m") && trim($_llamfecha[2]) == date("d")){
switch($_tiporesultado){
case 'contesta':
$_si_contesta_hoy++;
break;
case 'ocupado':
$_ocupado_hoy++;
break;
case 'no contesta':
$_no_contesta_hoy++;
break;
case 'incidencia':
$_incidencia_hoy++;
break;
}
}
$arrayLlamadas[$k]['usuario'] = $_usrName;
$arrayLlamadas[$k]['fecha'] = trim($_llamfecha[2])."-".$_llamfecha[1]."-".$_llamfecha[0];
$arrayLlamadas[$k]['resultado'] = $_resultado;
$arrayLlamadas[$k]['observacion'] = $_observacion;
}
} ?>
<table width="100%">
<thead>
<tr>
<th colspan="2">Contesta</th><th colspan="2"></th>
</tr>
<tr>
<th>SI</th><th>NO</th><th>Ocupado</th><th>Incidencia</th>
</tr>
</thead>
<tbody>
<tr class="par" align="center">
<td><?php echo $_si_contesta; ?></td><td><?php echo $_no_contesta; ?></td><td><?php echo $_ocupado; ?></td><td><?php echo $_incidencia; ?></td>
</tr>
</tbody>
<thead>
<tr>
<th colspan="4">Hoy</th>
</tr>
</thead>
<tbody>
<tr class="par" align="center">
<td><?php echo $_si_contesta_hoy; ?></td><td><?php echo $_no_contesta_hoy; ?></td><td><?php echo $_ocupado_hoy; ?></td><td><?php echo $_incidencia_hoy; ?></td>
</tr>
</tbody>
<thead>
<tr>
<th colspan="4">Último registro</th>
</tr>
</thead>
<tbody>
<tr class="par" align="center">
<td><?php echo $_si_contesta_hoy; ?></td><td><?php echo $_no_contesta_hoy; ?></td><td><?php echo $_ocupado_hoy; ?></td><td><?php echo $_incidencia_hoy; ?></td>
</tr>
</tbody>
</table>
</div>
<h3>Historial</h3>
<div> <?php
if(count($arrayLlamadas) > 0){ ?>
<table width="100%">
<thead>
<tr>
<th>Usuario</th><th>Fecha</th><th>Resultado</th><th>Observación</th>
</tr>
</thead>
<tbody> <?php
foreach ($arrayLlamadas as $j => $arrayllam) {
((($j % 2) == 0)? $clase="par" : $clase="impar"); ?>
<tr class="<?php echo $clase; ?>">
<td><?php echo $arrayLlamadas[$j]['usuario']; ?></td><td><?php echo $arrayLlamadas[$j]['fecha']; ?></td><td><?php echo $arrayLlamadas[$j]['resultado']; ?></td><td><?php echo $arrayLlamadas[$j]['observacion']; ?></td>
</tr> <?php
} ?>
</tbody>
</table> <?php
} ?>
</div>
</div>
<script>
$( "#button" ).button();
$( "#button" ).click(function(){
$("#dialogo").empty();
$("#dialogo").dialog({
modal: true, title: 'Mensaje', zIndex: 100, autoOpen: true,
resizable: false,
width: 380,
});
$( "#dialogo" ).dialog( "option", "title", 'Registro de llamadas');
var origen = document.getElementById('origen').value;
var idorigen = document.getElementById('idorigen').value;
var nroRel = <?php echo $_nroRel;?>;
var telefono = document.getElementById('telefono').value;
var empresa = document.getElementById('empselect').value;
var contesta = $( "#contesta" ).val();
switch(contesta){
case '1':
//NO CONTESTA//
$("#dialogo").dialog("close");
dac_reprogramar(origen, idorigen, nroRel, 'no contesta', telefono);
break;
case '2':
//OCUPADO//
$("#dialogo").dialog("close");
dac_reprogramar(origen, idorigen, nroRel, 'ocupado', telefono);
break;
case '3':
//SI CONTESTAS //
$( "#dialogo" ).dialog({
height: 300,
buttons: {
Aceptar : function () {
var radio = $("input[name='radio']:checked").val();
switch(radio){
case '1':
/* ARGUMENTAR --> LLAMADA OK */
$("#btsend").click();
dac_registrarLlamada(origen, idorigen, nroRel, telefono, 'contesta', 'argumentado', '');
href ='/pedidos/relevamiento/relevar/index.php?origenid='+idorigen+'&origen='+origen+'&nroRel='+nroRel+'&empresa='+empresa;
//redirige al relevamiento
window.open(href,'_blank');
//Cierra el formulario
$(this).dialog("close");
break;
case '2':
/* REPROGRAMAR LLAMADA */
dac_reprogramar(origen, idorigen, nroRel, 'contesta', telefono);
break;
/*case '3':
RELLAMAR INMEDIATAMENTE
//Cierra el formulario
$(this).dialog("close");
break;*/
case '4':
/* INDIDENCIA */
var tipo_incidencia = $( "#tipo_incidencia" ).val();
var observacion = $( "#descripcion" ).val();
dac_registrarLlamada(origen, idorigen, nroRel, telefono, 'incidencia', tipo_incidencia, observacion);
break;
default:
$(this).dialog("close");
break;
}
},
Cerrar : function () {
$(this).dialog("close");
}
},
});
var contenido =
'<form>'+
'<div class="bloque_1"><h1>Resultado del contacto</h1></div>'+
'<div class="bloque_1"><input type="radio" id="radio1" name="radio" value="1" checked="checked" onclick="dac_incidencia(0)"><label for="radio1" value="1">Argumentado (iniciar preguntas)</label></div><hr>'+
'<div class="bloque_1"><input type="radio" id="radio2" name="radio" value="2" onclick="dac_incidencia(0)"><label for="radio2">Volver a llamar</label></div><hr>'+
'<div class="bloque_1"><input type="radio" id="radio4" name="radio" value="4" onclick="dac_incidencia(1)"><label for="radio4">Incidencia</label></div><hr>'+
'<div id="incidencia" style="display:none">'+
'<div class="bloque_1">'+
'<label>Tipo de incidencia</label>'+
'<select id="tipo_incidencia" name="tipo_incidencia">'+
'<option value="0" selected></option>'+
'<option value="ilocalizable">Ilocalizable</option>'+
'<option value="no_colabora">No Colabora</option>'+
'<option value="duplicado">Duplicado</option>'+
'<option value="tel_equivocado">Tel. equivocado</option>'+
'<option value="otras">Otras</option>'+
'</select> '+
'</div>'+
'<div class="bloque_1"><label>Descripción</label> <input id="descripcion" name="descripcion" type="text"></div>'+
'</div>'+
'</form>'
;
$(contenido).appendTo('#dialogo');
break;
default: break;
}
});
</script><file_sep>/pedidos/imprimir_pedido.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$nroPedido = empty($_REQUEST['nropedido']) ? 0 : $_REQUEST['nropedido'];
?>
<!DOCTYPE html>
<html>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<main class="cuerpo">
<div id="factura" align="center">
<div class="cbte" style="overflow:auto; background-color: #FFF; width: 800px;">
<?php
if ($nroPedido) {
$usr = ($_SESSION["_usrrol"] != "V") ? NULL : $_SESSION["_usrid"];
$totalFinal = 0;
$detalles = DataManager::getPedidos($usr, NULL, $nroPedido);
if ($detalles) {
foreach ($detalles as $k => $detalle) {
if ($k==0){
$empresa = $detalle["pidemp"];
$empresas = DataManager::getEmpresas();
if ($empresas) {
foreach ($empresas as $i => $emp) {
$idEmpresa = $emp['empid'];
if ($empresa == $idEmpresa){
$nombreEmp = $emp['empnombre'];
$dirEmp = $emp['empdomicilio'];
$localidadEmp = " - ".$emp['emplocalidad'];
$cpEmp = " - CP".$emp['empcp'];
$telEmp = " - Tel: ".$emp['empcp'];
$correoEmp = $emp['empcorreo']." / ";
}
}
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
}?>
<div class="cbte_header" style="border-bottom: solid 1px #CCCCCC; color:#373435; padding:15px; height:110px;">
<div class="cbte_boxheader" style="float: left; width: 350px;">
<?php echo $cabeceraPedido; ?>
</div> <!-- cbte_boxheader -->
<div class="cbte_boxheader_der" align="left" style="float:left; width:365px; border-left:1px solid #CCC; padding-left:30px; font-family: Verdana, Geneva, sans-serif; font-size:11px; line-height:20px; font-weight:bold;">
<h1 style="color:#2D567F;">PEDIDO WEB</h1>
<?php echo $dirEmp; ?> <?php echo $cpEmp; ?> <?php echo $localidadEmp; ?> <?php echo $telEmp; ?></br>
<?php echo $correoEmp; ?> www.neo-farma.com.ar</br>
IVA RESPONSABLE INSCRIPTO
</div> <!-- cbte_boxheader -->
</div> <!-- boxtitulo -->
<?php
$fechaPedido = $detalle['pfechapedido'];
$idUsuario = $detalle['pidusr'];
$nombreUsr = DataManager::getUsuario('unombre', $idUsuario);
$empresa = $detalle["pidemp"];
$idCliente = $detalle["pidcliente"];
$nombreCli = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $idCliente, $empresa);
$domicilioCli = DataManager::getCuenta('ctadireccion', 'ctaidcuenta', $idCliente, $empresa)." ".DataManager::getCuenta('ctadirnro', 'ctaidcuenta', $idCliente, $empresa)." ".DataManager::getCuenta('ctadirpiso', 'ctaidcuenta', $idCliente, $empresa)." ".DataManager::getCuenta('ctadirdpto', 'ctaidcuenta', $idCliente, $empresa);
$localidadCli = DataManager::getCuenta('ctalocalidad', 'ctaidcuenta', $idCliente, $empresa);
$codpostalCli = DataManager::getCuenta('ctacp', 'ctaidcuenta', $idCliente, $empresa);
$condpago = $detalle["pidcondpago"];
$condicionesDePago = DataManager::getCondicionesDePago(0, 0, NULL, $condpago);
if (count($condicionesDePago)) {
foreach ($condicionesDePago as $k => $condPago) {
$condPagoCodigo = $condPago["IdCondPago"];
$condnombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condPago['condtipo']);
$conddias = "(";
$conddias .= empty($condPago['Dias1CP']) ? '0' : $condPago['Dias1CP'];
$conddias .= empty($condPago['Dias2CP']) ? '' : ', '.$condPago['Dias2CP'];
$conddias .= empty($condPago['Dias3CP']) ? '' : ', '.$condPago['Dias3CP'];
$conddias .= empty($condPago['Dias4CP']) ? '' : ', '.$condPago['Dias4CP'];
$conddias .= empty($condPago['Dias5CP']) ? '' : ', '.$condPago['Dias5CP'];
$conddias .= " Días)";
$conddias .= ($condPago['Porcentaje1CP'] == '0.00') ? '' : ' '.$condPago['Porcentaje1CP'].' %';
}
}
$ordenCompra = ($detalle["pordencompra"] == 0) ? '' : "<span style=\" color: #2D567F; font-weight:bold;\">Orden Compra: </span><span style=\"font-size: 12px; font-weight:bold;\">".$detalle["pordencompra"]."</span>";
$observacion = $detalle["pobservacion"];
?>
<div class="cbte_boxcontent" align="left" style="font-size: 14px; background-color:#cfcfcf; padding: 5px; padding-left: 15px; padding-right: 15px; min-height: 20px; overflow: hidden;">
<div class="cbte_box" style="height: auto; line-height: 20px; float:left; width: 33%; font-weight:bold;"><?php echo $fechaPedido;?></span></div>
<div class="cbte_box" align="center" style="height: auto; line-height: 20px; float:left; width: 33%; font-weight:bold;"><span style=" color: #2D567F;">Nro. Pedido:</span> <?php echo str_pad($nroPedido, 9, "0", STR_PAD_LEFT); ?></div>
<div class="cbte_box" align="right" style="height: auto; line-height: 20px; float:left; width: 33%;"><span style=" color: #2D567F; font-weight:bold;"><?php echo $nombreUsr;?></div>
</div> <!-- cbte_box_nro -->
<div class="cbte_boxcontent" align="left" style="font-size: 14px; background-color:#cfcfcf; padding: 5px; padding-left: 15px; padding-right: 15px; min-height: 20px; overflow: hidden;"> <!-- background-color:#A0DFFC; -->
<div class="cbte_box" style="height: auto; line-height: 20px; float:left; width: 16%;">
<span style=" color:#2D567F; font-weight:bold;">
Cliente: </br>
Dirección: </br>
</span>
</div> <!-- cbte_box_col -->
<div class="cbte_box2" style="height: auto; line-height: 20px; float:left; width: 66%;">
<span style="font-size: 14px; font-weight:bold;">
<?php echo $idCliente." - ".$nombreCli;?></br>
<?php echo $domicilioCli." - ".$localidadCli." - ".$codpostalCli; ?></br>
</span>
</div> <!-- cbte_box_col -->
</div> <!-- cbte_box_nro -->
<div class="cbte_boxcontent" align="left" style="font-size: 14px; background-color: #cfcfcf; padding: 5px; padding-left: 15px; padding-right: 15px; min-height: 20px; overflow: hidden;">
<div class="cbte_box2" style="height: auto; line-height: 20px; float:left; width: 66%;"><span style=" color: #2D567F; font-weight:bold;">Condición de Pago: </span><span style="font-size: 14px; font-weight:bold;"><?php echo $condpago." | ".$condnombre." ".$conddias;?></span></div>
<div class="cbte_box" align="right" style="height: auto; line-height: 20px; float:left; width: 33%;"><?php echo $ordenCompra;?></div>
</div> <!-- cbte_box_nro -->
<div class="cbte_boxcontent2" style="padding: 15px; overflow:auto; height:auto;">
<table width="95%" border="0">
<thead>
<tr align="left">
<th scope="col" width="10%" height="18" align="center">Código</th>
<th scope="col" width="10%" align="center">Cant</th>
<th scope="col" width="30%" align="center">Descripción</th>
<th scope="col" width="10%" align="center">Precio</th>
<th scope="col" width="10%" align="center">Bonif</th>
<th scope="col" width="10%" align="center">Dto1</th>
<th scope="col" width="10%" align="center">Dto2</th>
<th scope="col" width="10%" align="center">Total</th>
</tr>
</thead> <?php
}
$total = 0;
$idArt = $detalle['pidart'];
$unidades = $detalle['pcantidad'];
$descripcion= DataManager::getArticulo('artnombre', $idArt, 1, 1);
$precio = $detalle['pprecio'];
$b1 = ($detalle['pbonif1'] == 0)? '' : $detalle['pbonif1'];
$b2 = ($detalle['pbonif2'] == 0)? '' : $detalle['pbonif2'];
$bonif = ($detalle['pbonif1'] == 0)? '' : $b1." X ".$b2;
$desc1 = ($detalle['pdesc1'] == 0) ? '' : $detalle['pdesc1'];
$desc2 = ($detalle['pdesc2'] == 0) ? '' : $detalle['pdesc2'];
//**************************************//
// Calculo precio final por artículo //
$precioF = $precio * $unidades;
if ($desc1 != ''){ $precioF = $precioF - ($precioF * ($desc1/100)); }
if ($desc2 != ''){ $precioF = $precioF - ($precioF * ($desc2/100)); }
$total = round($precioF, 3);
$totalFinal += $total;
//**************************************//
echo sprintf("<tr style=\"%s\">", ((($k % 2) == 0)? "background-color:#fff; height:40px;" : "background-color:#C3C3C3; height:40px; font-weight:bold;"));
echo sprintf("<td height=\"15\" align=\"center\">%s</td><td align=\"center\" style=\"border-left:1px solid #999;\">%s</td><td style=\"border-left:1px solid #999; padding-left:15px;\">%s</td><td align=\"right\" style=\"border-left:1px solid #999; padding-right:15px;\">%s</td><td align=\"center\" style=\"border-left:1px solid #999;\">%s</td><td align=\"center\" style=\"border-left:1px solid #999;\">%s</td><td align=\"center\" style=\"border-left:1px solid #999;\">%s</td><td align=\"right\" style=\"border-left:1px solid #999; padding-right:5px;\">%s</td>", $idArt, number_format($unidades,0), $descripcion, number_format(round($precio,2),2), $bonif, number_format(round($desc1,2),2), number_format(round($desc2,2),2), number_format(round($total,2),2));
echo sprintf("</tr>");
} ?>
</table>
</div> <!-- cbte_boxcontent2 -->
<div class="cbte_boxcontent2" align="left" style="font-size: 14px; background-color: #cfcfcf; padding: 5px; padding-left: 15px; padding-right: 15px; min-height: 20px; overflow: hidden;">
<div class="cbte_box2" style="height: auto; line-height: 20px; float:left; width: 66%; border:1px solid #cfcfcf;"><span style=" font-weight:bold;"><span style="font-size:16px; font-weight:bold;"><?php echo $observacion;?></span>
</div>
<div class="cbte_box" align="right" style="height: auto; line-height: 20px; float:left; width: 33%; font-size:26px;"><span style=" color: #2D567F; font-weight:bold;">TOTAL: </span>
<span style="font-weight:bold;"><?php echo number_format(round($totalFinal,2),2); ?></span></div>
</div> <!-- cbte_boxcontent2 -->
<?php
}
} ?>
<div class="cbte_boxcontent2" align="center">
<?php echo $piePedido; ?>
</div>
</div> <!-- cbte_box -->
</div> <!-- factura -->
</main> <!-- fin cuerpo -->
</body>
</html>
<?php
echo "<script>";
echo "javascript:dac_imprimirMuestra('factura');";
echo "</script>";
?>
<file_sep>/rendicion/logica/ajax/anular.recibo.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$_rendid = (isset($_REQUEST['rendid'])) ? $_REQUEST['rendid'] : NULL;
$_nro_rendicion = (isset($_REQUEST['nro_rend'])) ? $_REQUEST['nro_rend'] : NULL;
$_nro_tal = (isset($_REQUEST['nro_tal'])) ? $_REQUEST['nro_tal'] : NULL;
$_nro_rec = (isset($_REQUEST['nro_rec'])) ? $_REQUEST['nro_rec'] : NULL;
$_nva_rendicion = 0;
if((empty($_nro_rendicion) or !is_numeric($_nro_rendicion))){
echo "No existe una rendición. No se pueden cargar recibos anulados."; exit;
}
//Controla que EXISTA (para saber si insertar o modificar) la rendición Y QUE NO esté ENVIADA.
$_rendicion = DataManager::getRendicion($_SESSION["_usrid"], $_nro_rendicion);
if (count($_rendicion) > 0) {
foreach ($_rendicion as $k => $_rend){
$_rend = $_rendicion[$k];
$_rendActiva= $_rend['rendactiva'];
}
if($_rendActiva != 1){
echo "No se pueden enviar los datos con el Nro. de Rendición ".$_nro_rendicion." ya que fue enviado anteriormente."; exit;
}
} else {
//Si no existen datos, es que el nro de rendición no existe, por lo tanto es nueva
$_nva_rendicion = 1;
}
if((empty($_nro_tal) or !is_numeric($_nro_tal)) ){
echo "Debe completar el número de talonario correctamente.\n"; exit;
}
if((empty($_nro_rec) or !is_numeric($_nro_rec)) ){
echo "Debe completar el número de recibo correctamente.\n"; exit;
}
//BUSCA el talonario en talonario_idusr
$_talonario = DataManager::getBuscarTalonario($_nro_tal);
if (count($_talonario) > 0) {
foreach ($_talonario as $k => $_tal) {
$_talnro = $_tal["nrotalonario"];
$_talidusr = $_tal["idusr"];
if ($_talidusr != $_SESSION["_usrid"]){
echo "El número de talonario corresponde a otro Vendedor"; exit;
} else {
//Busca el número MAX de recibo
$max_rec = DataManager::getMaxRecibo($_nro_tal);
$nro_siguiente = $max_rec + 1;
if (($_nro_rec <= $max_rec || $_nro_rec > $nro_siguiente) && $max_rec != 0){
echo "El número de recibo [ $_nro_rec ] no es válido. Debe ser $nro_siguiente.";
} else { //ES VALIDO.
if($_nva_rendicion == 1){ //Se cre la Rendición
//Inserto datos en tabla rendicion
$_rendicionobject = DataManager::newObjectOfClass('TRendicion');
$_rendicionobject->__set('Numero' , $_nro_rendicion);
$_rendicionobject->__set('Fecha' , date('Y-m-d'));
$_rendicionobject->__set('IdUsr' , $_SESSION["_usrid"]);
$_rendicionobject->__set('NombreUsr' , $_SESSION["_usrname"]);
$_rendicionobject->__set('Activa' , '1');
$_rendicionobject->__set('Retencion' , '0.00');
$_rendicionobject->__set('Deposito' , '0.00');
$_rendicionobject->__set('Envio' , date('2001-01-01'));
$_rendicionobject->__set('ID', $_rendicionobject->__newID());
$IDRendicion = DataManager::insertSimpleObject($_rendicionobject);
} else {
$IDRendicion = $_rendid;
}
//Inserto datos recibos.
$_recobject = DataManager::newObjectOfClass('TRecibos');
$_recobject->__set('ID', $_recobject->__newID());
$_recobject->__set('Numero', $_nro_rec);
$_recobject->__set('Talonario', $_nro_tal);
$_recobject->__set('Observacion', 'ANULADO');
$_recobject->__set('Diferencia', '0.00');
$IDRecibo = DataManager::insertSimpleObject($_recobject);
//Inserto datos en tabla rend_rec.
$_IDRend_Rec = DataManager::insertToTable('rend_rec', 'rendid, recid', "'".$IDRendicion."','".$IDRecibo."'");
//Finalizo OK
echo "1"; exit;
}
}
}
} else {
echo "No existe el número de talonario, antes debe crearlo."; exit;
}
?>
<file_sep>/proveedores/fechaspago/logica/ajax/notificar.fechapago.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$empresa = empty($_REQUEST['idempresa']) ? 0 : $_REQUEST['idempresa'];
$_idprov = empty($_REQUEST['idprov']) ? 0 : $_REQUEST['idprov'];
$_fechapago = empty($_REQUEST['fechapago']) ? 0 : $_REQUEST['fechapago'];
$_nrofact = empty($_REQUEST['factnro']) ? 0 : $_REQUEST['factnro'];
if(empty($empresa) || empty($_idprov) || empty($_fechapago) || empty($_nrofact)){
echo "Ocurrió un ERROR al verificar el proveedor."; exit;
}
$empresaNombre = DataManager::getEmpresa('empnombre', $empresa);
if(!$empresaNombre){
echo "No existen empresas activas en GEZZI."; exit;
}
//$_empresas = DataManager::getEmpresas(1);
/*
if (count($_empresas)) {
foreach ($_empresas as $k => $_emp) {
if ($empresa == $_emp['empid']){
$_nombreemp = $_emp["empnombre"];
}
}
} else {
echo "No existen empresas activas en GEZZI."; exit;
}*/
//Busco registros ya guardados en ésta fecha y pongo en cero si no están en el array (si fueron eliminados)
$_proveedor = DataManager::getProveedor('providprov', $_idprov, $empresa);
if($_proveedor){
$_idorigen = $_proveedor['0']['provid'];
$_activo = $_proveedor['0']['provactivo'];
$_nombre = $_proveedor['0']['provnombre'];
$_emailprov = $_proveedor['0']['provcorreo']; //email de razón social
$_telefono = $_proveedor['0']['provtelefono'];
if(!$_activo){
echo "El proveedor '".$_idprov." - ".$_nombre."' no se encuentra activo."; exit;
}
//$_idorigen = $_provid;
$_origen = 'TProveedor';
$_ctocorreo = "";
$_emails = array();
//Esto registrará SOLO el último correo de los que esté como sector COBRANZAS..
$_contactos = DataManager::getContactosPorCuenta( $_idorigen, $_origen, 1);
if($_contactos){
$_email = '';
foreach ($_contactos as $k => $_cont){
$_ctoid = $_cont["ctoid"];
$_sector = $_cont["ctosector"];
if($_sector == 2){ //2 = Cobranza
$_email = $_cont["ctocorreo"];
array_push($_emails, $_email);
}
}
if (empty($_email)){
echo "No se encuentra un correo de Cobranzas para notificar al Proveedor"; exit;
}
} else {
if(empty($_emailprov)){
echo "El Proveedor no tiene correos para notificar.";
exit;
} else {
$_email = $_emailprov;
}
}
//**************************//
// NOTIFICA FECHA DE PAGO //
//**************************//
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = "<EMAIL>";
$mail->FromName = "InfoWeb GEZZI";
$mail->Subject = "Notificacion de Fecha de Pago para ".$_nombre.", guarde este email.";
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
$headMail = '
<html>
<head>
<title>Notificación de Solicitud</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 580px;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>';
$cuerpoMail_1 = '
<body>
<div align="center">
<table width="580" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Notificación de <strong>FECHA DE PAGO</strong><br />
<div />
</td >
</tr>
<tr bgcolor="#597D92">
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight: bold;">
<strong>Estos son sus datos de solicitud</strong>
</div>
</td>
</tr>
';
$cuerpoMail_2 = '
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200">FECHA DE PAGO:</th>
<td align="left" width="400">'.$_fechapago.'</td>
</tr>
<tr>
<th align="left" width="200">Horario:</th>
<td align="left" width="400">de 15:00 a 16:30 hs</td>
</tr>
<tr>
<th align="left" width="200">Proveedor: </th>
<td align="left" width="400">'.$_nombre.'</td>
</tr>
<tr>
<th align="left" width="200">Nro. de Factura:</th>
<td align="left" width="400">'.$_nrofact.'</td>
</tr>
<tr>
<th align="left" width="200">Correo:</th>
<td align="left" width="400">'.$_emailprov.'</td>
</tr>
<tr>
<th align="left" width="200">Teléfono:</th>
<td align="left" width="400">'.$_telefono.'</td>
</tr>
</table>
</div>
</td>
</tr>
';
$cuerpoMail_3 = '
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con la empresa al 4555-3366 de Lunes a Viernes de 10 a 17 horas.
</font>
<div style="color:#000000; font-size:12px;">
<strong>Le enviaremos un email notificando la fecha de pago, al contacto de su cuenta de usuario.</br></br>
</div>
</div>
</td>
</tr>
';
$pieMail = ' <tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Gracias por confiar en '.$empresaNombre.'<br/>
Le saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
</body>
</html>
';
$_total = $headMail.$cuerpoMail_1.$cuerpoMail_2.$cuerpoMail_3.$pieMail;
$mail->msgHTML($_total);
//$mail->AddAddress($_email, 'InfoWeb GEZZI');
if(count($_emails)){
foreach ($_emails as $k => $_email){
$mail->AddAddress($_email, 'InfoWeb GEZZI');
}
}
$mail->AddBCC("<EMAIL>", 'InfoWeb GEZZI');
$mail->AddBCC("<EMAIL>", 'InfoWeb GEZZI');
//*********************************//
if(!$mail->Send()) {
echo "Hubo un error al intentar enviar la notificación."; exit;
}
//**************************//
} else {
echo "El proveedor no existe cargado"; exit;
}
echo "1"; exit;
?><file_sep>/condicion/logica/changestatus.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$condId = empty($_REQUEST['condid']) ? 0 : $_REQUEST['condid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/condicion/' : $_REQUEST['backURL'];
if ($condId) {
$condicionObject= DataManager::newObjectOfClass('TCondicionComercial', $condId);
$status = ($condicionObject->__get('Activa')) ? 0 : 1;
$condicionObject->__set('Activa', $status);
DataManagerHiper::updateSimpleObject($condicionObject, $condId);
DataManager::updateSimpleObject($condicionObject);
// Registro movimiento
$movimiento = 'ChangeStatus_a_'.$status;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, 'TCondicionComercial', $condId);
}
header('Location: '.$backURL);
?><file_sep>/acciones/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_acid = empty($_REQUEST['acid']) ? 0 : $_REQUEST['acid'];
$_sms = empty($_GET['sms']) ? 0 : $_GET['sms'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/acciones/': $_REQUEST['backURL'];
if ($_sms) {
$_acnombre = $_SESSION['s_nombre'];
$_acsigla = $_SESSION['s_sigla'];
switch ($_sms) {
case 1: $_info = "El nombre de la acción es obligatorio."; break;
case 2: $_info = "La sigla de la acción es obligatoria."; break;
} // mensaje de error
}
if ($_acid) {
if (!$_sms) {
$_accion = DataManager::newObjectOfClass('TAccion', $_acid);
$_acnombre = $_accion->__get('Nombre');
$_acsigla = $_accion->__get('Sigla');
$_acactiva = $_accion->__get('Activa');
}
$_button = sprintf("<input type=\"submit\" id=\"btsend\" name=\"_accion\" value=\"Enviar\"/>");
$_action = "logica/update.accion.php?backURL=".$backURL;
} else {
if (!$_sms) {
$_acnombre = "";
$_acsigla = "";
}
$_button = sprintf("<input type=\"submit\" id=\"btsend\" name=\"_accion\" value=\"Enviar\"/>");
$_action = sprintf("logica/update.accion.php?uid=%d&backURL=", $_acid, $backURL);
}?>
<!DOCTYPE html>
<html lang="es">
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = 'acciones';
$_subsection = 'nueva_accion';
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav> <!-- fin menu -->
<main class="cuerpo">
<div class="box_body">
<?php
if ($_sms) { ?>
<div class="bloque_1" align="center">
<fieldset id='box_error' class="msg_error" style="display: block">
<div id="msg_error"><?php echo $_info;?></div>
</fieldset>
</div> <?php
} ?>
<form method="post" action="<?php echo $_action;?>">
<fieldset>
<legend>Acción</legend>
<div class="bloque_5">
<label for="acnombre">Nombre Acción</label>
<input name="acnombre" id="acnombre" type="text" maxlength="50" value="<?php echo @$_acnombre;?>"/>
</div>
<div class="bloque_7">
<label for="acsigla">Sigla</label>
<input name="acsigla" id="acsigla" type="text" maxlength="20" value="<?php echo @$_acsigla;?>"/>
</div>
<input type="hidden" name="acid" value="<?php echo @$_acid;?>" />
<div class="bloque_7">
<br>
<?php echo $_button; ?>
</div>
</fieldset>
</form>
</div> <!-- boxbody -->
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/contactos/logica/ajax/update.contacto.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//*******************************************/
$_ctoid = (isset($_POST['ctoid'])) ? $_POST['ctoid'] : NULL;
$_origenid = (isset($_POST['origenid'])) ? $_POST['origenid'] : NULL; //id de la tabla de origen
$_origen = (isset($_POST['origen'])) ? $_POST['origen'] : NULL; //es el nombre de la tabla de donde se origina el contacto (ejemplo Proveedor) el Destino, sería la tabla CONTACTOS
$_nombre = (isset($_POST['nombre'])) ? $_POST['nombre'] : NULL;
$_apellido = (isset($_POST['apellido'])) ? $_POST['apellido'] : NULL;
$_telefono = (isset($_POST['telefono'])) ? $_POST['telefono'] : NULL;
$_interno = (isset($_POST['interno'])) ? $_POST['interno'] : NULL;
$_correo = (isset($_POST['correo'])) ? $_POST['correo'] : NULL;
$_activo = (isset($_POST['activo'])) ? $_POST['activo'] : NULL;
$_sector = (isset($_POST['sector'])) ? $_POST['sector'] : NULL;
$_puesto = (isset($_POST['puesto'])) ? $_POST['puesto'] : NULL;
$_genero = (isset($_POST['genero'])) ? $_POST['genero'] : NULL;
//*******************************************/
//******************//
// Controlo Datos //
//******************//
if(empty($_origen)){
echo "Indique un origen"; exit;
}
if(empty($_sector)){
echo "Indique un sector"; exit;
}
if(empty($_puesto)){
echo "Indique un puesto"; exit;
}
if(empty($_nombre)){
echo "Indique el nombre"; exit;
}
if(empty($_apellido)){
echo "Indique el apellido"; exit;
}
if(empty($_genero)){
echo "Indique un genero"; exit;
}
if(empty($_telefono) || !is_numeric($_telefono)){
echo "Indique un telefono"; exit;
}
if (!preg_match( "/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,4})$/", $_correo)) {
echo "El correo es incorrecto"; exit;
}
$_ctoobject = ($_ctoid) ? DataManager::newObjectOfClass('TContacto', $_ctoid) : DataManager::newObjectOfClass('TContacto');
$_ctoobject->__set('Origen', $_origen);
$_ctoobject->__set('IDOrigen', $_origenid);
$_ctoobject->__set('Domicilio', 0);
$_ctoobject->__set('Sector', $_sector);
$_ctoobject->__set('Puesto', $_puesto);
$_ctoobject->__set('Nombre', $_nombre);
$_ctoobject->__set('Apellido', $_apellido);
$_ctoobject->__set('Genero', $_genero);
$_ctoobject->__set('Telefono', $_telefono);
$_ctoobject->__set('Interno', $_interno);
$_ctoobject->__set('Email', $_correo);
$_ctoobject->__set('Activo', 1);
if ($_ctoid) {
$ID = DataManager::updateSimpleObject($_ctoobject);
} else {
$_ctoobject->__set('ID', $_ctoobject->__newID());
$ID = DataManager::insertSimpleObject($_ctoobject);
}
echo '1'; exit;
?><file_sep>/noticias/logica/update.noticia.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_idnt = empty($_REQUEST['idnt']) ? 0 : $_REQUEST['idnt'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/noticias/': $_REQUEST['backURL'];
$_titulo = $_POST['ntitulo'];
$_fecha = $_POST['nfecha'];
$_noticia = $_POST['nnoticia'];
$_link = $_POST['nlink'];
$_SESSION['s_titulo'] = $_titulo;
$_SESSION['s_fecha'] = $_fecha;
$_SESSION['s_noticia'] = $_noticia;
$_SESSION['s_link'] = $_link;
if (empty($_titulo)) {
$_goURL = sprintf("/pedidos/noticias/editar.php?idnt=%d&sms=%d", $_idnt, 1);
header('Location:' . $_goURL);
exit;
}
if (empty($_fecha)) {
$_goURL = sprintf("/pedidos/noticias/editar.php?idnt=%d&sms=%d", $_idnt, 2);
header('Location:' . $_goURL);
exit;
}
if (empty($_noticia)) {
$_goURL = sprintf("/pedidos/noticias/editar.php?idnt=%d&sms=%d", $_idnt, 3);
header('Location:' . $_goURL);
exit;
}
$date = $_fecha;
list($día, $mes, $año) = explode('[/.-]', $date);
$_fecha = $año."-".$mes."-".$día;
$_noticiaobject = ($_idnt) ? DataManager::newObjectOfClass('TNoticia', $_idnt) : DataManager::newObjectOfClass('TNoticia');
$_noticiaobject->__set('Titulo', $_titulo);
$_noticiaobject->__set('Fecha', $_fecha);
$_noticiaobject->__set('Descripcion', $_noticia);
$_noticiaobject->__set('Link', $_link);
if ($_idnt) {
$ID = DataManager::updateSimpleObject($_noticiaobject);
} else {
$_noticiaobject->__set('ID', $_noticiaobject->__newID());
$_noticiaobject->__set('Activa', 1);
$ID = DataManager::insertSimpleObject($_noticiaobject);
}
unset($_SESSION['s_titulo']);
unset($_SESSION['s_fecha']);
unset($_SESSION['s_noticia']);
unset($_SESSION['s_link']);
header('Location:' . $backURL);
?><file_sep>/login/registrarme/registrarme.php
<?php
$_nextURL = (isset($_REQUEST["_go"])) ? sprintf("%s?_go=%s", $_SERVER["PHP_SELF"], $_REQUEST["_go"]) : "/pedidos/index.php";
$_goURL = (isset($_REQUEST["_go"])) ? $_REQUEST["_go"] : "/pedidos/index.php"; // url destino
$btAccion = sprintf("<input type=\"submit\" id=\"btsend\" name=\"_accion\" value=\"Enviar\" style=\"background-color:#DF6900;\"/>");
$_action = sprintf("logica/update.registrarme.php");
$_sms = (empty($_GET['sms'])) ? 0 : $_GET['sms'];
if ($_sms) {
$_razonsocial = isset($_SESSION['razonsocial']) ? $_SESSION['razonsocial'] : '';
$_usuario = isset($_SESSION['usuario']) ? $_SESSION['usuario'] : '';
$_telefono = isset($_SESSION['telefono']) ? $_SESSION['telefono'] : '';
$_provincia = isset($_SESSION['provincia']) ? $_SESSION['provincia'] : '';
$_localidad = isset($_SESSION['localidad']) ? $_SESSION['localidad'] : '';
$_direccion = isset($_SESSION['direccion']) ? $_SESSION['direccion'] : '';
$_codpostal = isset($_SESSION['codpostal']) ? $_SESSION['codpostal'] : '';
$_email = isset($_SESSION['email']) ? $_SESSION['email'] : '';
$_emailconfirm = isset($_SESSION['emailconfirm']) ? $_SESSION['emailconfirm'] : '';
$_clave = isset($_SESSION['clave']) ? $_SESSION['clave'] : '';
$_web = isset($_SESSION['web']) ? $_SESSION['web'] : '';
$_cuit = isset($_SESSION['cuit']) ? $_SESSION['cuit'] : '';
$_nroIBB = isset($_SESSION['nroIBB']) ? $_SESSION['nroIBB'] : '';
$_comentario = isset($_SESSION['comentario']) ? $_SESSION['comentario'] : '';
switch ($_sms) {
case 1: $_info = "Indique Razón Social.";
break;
case 2: $_info = "CUIT incorrecto.";
break;
case 3: $_info = "Indique número de teléfono.";
break;
case 4: $_info = "El usuario ya existe registrado.";
break;
case 5: $_info = "El correo ya existe registrado.";
break;
case 6: $_info = "La dirección de correo es incorrecta.";
break;
case 7: $_info = "Los correos no coinciden.";
break;
case 8:$_info = "Indique una clave de usuario.";
break;
case 9:$_info = "La dirección Web es incorrecta.";
break;
case 10:$_info = "Debe adjuntar Constancia de inscripción y Formulario CM01.";
break;
case 11:$_info = "Controle que los archivos adjuntos no superen los 4 MB.";
break;
case 12:$_info = "El usuario es incorrecto.";
break;
case 13:$_info = "Indique la provincia.";
break;
case 14:$_info = "Indique la localidad.";
break;
case 15:$_info = "El código postal debe ser numérico.";
break;
case 16:$_info = "Indique una dirección.";
break;
case 18:$_info = "El usuario debe contener solo caracteres alfanuméricos.";
break;
case 19:$_info = "Debe activar el control de reCAPTCHA para indicar que no es un robot.";
break;
case 20:$_info = "No se pudo enviar la solicitud.";
break;
case 21:$_info = "Falló el envío por correo. Si no recibe respuesta, póngase en contacto con la empresa.";
break;
case 22:$_info = "Uno de los archivos no es imagen o pdf.";
break;
case 23:$_info = "Error al archivar la documentación adjunta";
break;
case 24:$_info = "Debe completar Ingresos Brutos";
break;
case 30:$_info = "Su solicitud fue enviada correctamente";
break;
} // mensaje de error
} else {
$_razonsocial = $_usuario = $_telefono =
$_localidad = $_direccion =
$_codpostal = $_email = $_emailconfirm =
$_clave = $_web = $_cuit =
$_nroIBB = $_comentario = "";
$_provincia = 0;
} // $_sms > 0 ==> ERROR DETECTADO EN EL SCRIPT DE PROCESO DEL FORMULARIO (NO JAVASCRIPT)
?>
<script type="text/javascript">
$(document).ready(function() {
$("#email").bind('paste', function(e) {
e.preventDefault();
});
$("#emailconfirm").bind('paste', function(e) {
e.preventDefault();
});
});
</script>
<script type="text/javascript">
function dac_MostrarSms(sms){
document.getElementById('box_error').style.display = 'none';
if(sms){
if(sms > 0 && sms < 30){
document.getElementById('box_error').style.display = 'block';
document.getElementById('box_confirmacion').style.display = 'none';
} else {
document.getElementById('box_confirmacion').style.display = 'block';
document.getElementById('box_error').style.display = 'none';
}
}
}
</script>
<div id="box_down" align="center">
<?php
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
echo $cabeceraPedido;
?>
<div class="registro" align="center">
<div class="barra" align="left">
<tit_1>Registrarme como Proveedor</tit_1>
<hr>
</div>
<form method="post" enctype="multipart/form-data" action="<?php echo $_action; ?>">
<input type="hidden" name="sms" id="sms" value="<?php echo $_sms;?>"/>
<div class="bloque_1">
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_error' class="msg_error">
<div id="msg_error"> <?php echo $_info; ?> </div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"><?php echo $_info;?></div>
</fieldset>
<?php
echo "<script>";
echo "javascript:dac_MostrarSms(".$_sms.")";
echo "</script>";
?>
</div>
<div class="bloque_1">
<select id="empselect" name="empselect" ><?php
$_empresas = DataManager::getEmpresas(1);
if (count($_empresas)) {
foreach ($_empresas as $k => $_emp) {
$_idemp = $_emp["empid"];
$_nombreemp = $_emp["empnombre"];
if ($_idemp == 3){ ?>
<option id="<?php echo $_idemp; ?>" value="<?php echo $_idemp; ?>" selected><?php echo $_nombreemp; ?></option><?php
} else { ?>
<option id="<?php echo $_idemp; ?>" value="<?php echo $_idemp; ?>"><?php echo $_nombreemp; ?></option><?php
}
}
} ?>
</select>
</div>
<div class="bloque_3">
<input id="razonsocial" name="razonsocial" type="text" placeholder="Razón Social" value="<?php echo @$_razonsocial;?>" maxlength="50"/>
</div>
<div class="bloque_7">
<input id="cuit" name="cuit" type="text" placeholder="Cuit" value="<?php echo @$_cuit;?>" maxlength="13" />
</div>
<hr>
<div class="bloque_7">
<input id="usuario" name="usuario" type="text" placeholder="Usuario" value="<?php echo @$_usuario;?>" maxlength="15"/>
</div>
<div class="bloque_7">
<input id="clave" name="clave" type="password" placeholder="Clave" value="<?php echo $_clave;?>" maxlength="15" />
</div>
<div class="bloque_7">
<input id="nroIBB" name="nroIBB" type="text" placeholder="Ingresos Brutos" value="<?php echo @$_nroIBB;?>" maxlength="15" />
</div>
<div class="bloque_7">
<input id="telefono" name="telefono" type="text" placeholder="Teléfono" value="<?php echo @$_telefono;?>" maxlength="15"/>
</div>
<hr>
<div class="bloque_5">
<!--El id lo usaremos para seleccionar este elemento con el jQuery-->
<select id="provincia" name="provincia" />
<option> Seleccione Provincia... </option> <?php
$_provincias = DataManager::getProvincias();
if (count($_provincias)) {
foreach ($_provincias as $k => $_prov) {
if ($_provincia == $_prov["provid"]){ ?>
<option id="<?php echo $_prov["provnombre"]; ?>" value="<?php echo $_prov["provid"]; ?>" selected><?php echo $_prov["provnombre"]; ?></option> <?php
} else { ?>
<option id="<?php echo $_prov["provnombre"]; ?>" value="<?php echo $_prov["provid"]; ?>"><?php echo $_prov["provnombre"]; ?></option><?php
}
}
} ?>
</select>
</div>
<div class="bloque_5">
<select id="f_localidad" name="localidad"> <?php
if (!empty($_localidad)){ ?>
<option value="<?php echo $_localidad; ?>" selected><?php echo $_localidad; ?></option> <?php
} ?>
</select>
</div>
<div class="bloque_3">
<input id="direccion" name="direccion" type="text" placeholder="Dirección" value="<?php echo $_direccion;?>" maxlength="50"/>
</div>
<div class="bloque_7">
<input id="codpostal" name="codpostal" type="text" placeholder="Cod Postal" value="<?php echo $_codpostal;?>" maxlength="6" />
</div>
<div class="bloque_5">
<input id="email" name="email" type="text" placeholder="Correo electrónico" value="<?php echo @$_email;?>" maxlength="50"/>
</div>
<div class="bloque_5">
<input id="emailconfirm" name="emailconfirm" type="text" placeholder="Confirmar correo electrónico" value="<?php echo $_emailconfirm;?>" maxlength="50" />
</div>
<div class="bloque_1">
<input id="web" name="web" type="text" placeholder="Página web" value="<?php echo @$_web;?>" maxlength="50" />
</div>
<hr>
<div class="bloque_1">
<label><strong>Documentación (máximo por archivo de 4 MB, pdf o jpg) </strong></label>
</div>
<div class="bloque_5" >
<label style="color:#666;">Constancia de Inscripción</label> </br> <input type="file" name="archivo1"/>
</div>
<div class="bloque_5" >
<label style="color:#666;">Formulario CM01</label> </br>
<input type="file" name="archivo2" />
</div>
<div class="bloque_5">
<label style="color:#666;">Formulario CM05</label></br>
<input type="file" name="archivo3" />
</div>
<div class="bloque_5">
<label style="color:#666;">Excención de ganancias</label> </br>
<input type="file" name="archivo4" />
</div>
<div class="bloque_1">
<textarea id="comentario" name="comentario" placeholder="Comentarios" rez value="<?php echo $_comentario;?>" style="resize:none;" onKeyUp="javascript:dac_LimitaCaracteres(event, 'comentario', 200);" onKeyDown="javascript:dac_LimitaCaracteres(event, 'comentario', 200);"/><?php echo $_comentario;?></textarea>
<fieldset id='box_informacion' class="msg_informacion">
<div id="msg_informacion" align="center"></div>
</fieldset>
</div>
<div class="bloque_7" style="color:#666;">
Al hacer clic en "Enviar" aceptas los <a href="/pedidos/legal/terminos/" target="_blank">Términos y Condiciones</a>, confirmando así fueron leídas.
</div>
<div class="bloque_3" align="center">
<div class="g-recaptcha" data-theme="dark light" data-size="compact normal" data-sitekey="<KEY>"></div>
</div>
<div class="bloque_7" style="float: right;"> <?php echo $btAccion;?> </div>
<hr>
</form>
</div> <!-- fin registro -->
</div> <!-- fin cuerpo --> <file_sep>/transfer/enviados/lista.php
<div class="box_down"> <!-- datos -->
<?php if ($_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]== "A" || $_SESSION["_usrrol"]== "M"){ ?>
<div class="barra">
<div class="bloque_5" align="left">
<h1>Enviados Recientes</h1>
</div>
<div class="bloque_6" align="right">
<input id="txtBuscar3" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn3" type="text" value="tblPTEnviados" hidden/>
</div>
<div class="bloque_8" align="right">
<a href="../logica/exportar.historial.total.php" title="Exportar Historial"><img class="icon-xls-export"/></a>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblPTEnviados" >
<thead>
<tr>
<td scope="col" width="20%" height="18">Fecha</td>
<td scope="col" width="20%">Transfer</td>
<td scope="col" width="50%">Cliente</td>
<td scope="colgroup" width="10%" align="center">Acciones</td>
</tr>
</thead>
<tbody>
<?php
$dateFrom = new DateTime('now');
$dateFrom ->modify('-3 month');
$_transfers_recientes = DataManager::getTransfers(0, NULL, $dateFrom->format('Y-m-d'));
$_max = count($_transfers_recientes);
if ($_max != 0) {
for( $k=0; $k < $_max; $k++ ){
if ($k < $_max){
$_transfer_r = $_transfers_recientes[$k];
$_fecha = $_transfer_r["ptfechapedido"];
$_nropedido = $_transfer_r["ptidpedido"];
$_nombre = $_transfer_r["ptclirs"];
$_detalle = sprintf( "<a href=\"../detalle_transfer.php?idpedido=%d&backURL=%s\" target=\"_blank\" title=\"detalle pedido\">%s</a>", $_nropedido, $_SERVER['PHP_SELF'], "<img class=\"icon-detail\"/>");
}
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td>", $_fecha, $_nropedido, $_nombre, $_detalle);
echo sprintf("</tr>");
}
} else {
?>
<tr>
<td scope="colgroup" colspan="3" height="25" align="center">No hay pedidos Transfer enviados</td>
</tr>
<?php
} ?>
</tbody>
</table>
</div> <!-- Fin listar -->
<?php }?>
<?php if ($_SESSION["_usrrol"]=="V" || $_SESSION["_usrrol"]== "A"){ ?>
<div class="barra">
<div class="bloque_5" align="left">
<h1>Mi Transfers Enviado</h1>
</div>
<div class="bloque_6" align="right">
<input id="txtBuscar4" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn4" type="text" value="tblMisPTEnviados" hidden/>
</div>
<div class="bloque_8" align="right">
<a href="../logica/exportar.historial.php" title="Exportar Mi Historial">
<img class="icon-xls-export"/>
</a>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblMisPTEnviados">
<thead>
<tr>
<td scope="col" width="20%" height="18">Fecha</td>
<td scope="col" width="20%">Transfer</td>
<td scope="col" width="50%">Cliente</td>
<td scope="colgroup" width="10%" align="center">Acciones</td>
</tr>
</thead>
<?php
$_transfers_recientes = DataManager::getTransfers(0, $_SESSION["_usrid"]);
$_max = count($_transfers_recientes);
if ($_max != 0) {
for( $k=0; $k < $_max; $k++ ){
if ($k < $_max){
$_transfer_r = $_transfers_recientes[$k];
$fecha = explode(" ", $_transfer_r["ptfechapedido"]);
list($ano, $mes, $dia) = explode("-", $fecha[0]);
$_fecha = $dia."-".$mes."-".$ano;
$_nropedido = $_transfer_r["ptidpedido"];
$_nombre = $_transfer_r["ptclirs"];
$_detalle = sprintf( "<a href=\"../detalle_transfer.php?idpedido=%d&backURL=%s\" target=\"_blank\" title=\"detalle pedido\">%s</a>", $_nropedido, $_SERVER['PHP_SELF'], "<img class=\"icon-detail\"/>");
} else {
$_fecha = " ";
$_nropedido = " ";
$_nombre = " ";
$_detalle = " ";
}
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td>", $_fecha, $_nropedido, $_nombre, $_detalle);
echo sprintf("</tr>");
}
} else { ?>
<tr>
<td scope="colgroup" colspan="5" height="25" align="center">No hay pedidos Transfer enviados</td>
</tr>
<?php
} ?>
</table>
</div> <!-- Fin listar -->
<?php }?>
</div> <!-- Fin datos --><file_sep>/listas/lista.php
<?php
$btnNuevo = sprintf( "<a href=\"\" title=\"Nuevo\"><img class=\"icon-new\"/></a>");
?>
<div class="box_body">
<div class="bloque_1" align="center">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<form id="fmLista" method="post">
<input type="text" id="idLista" name="idLista" hidden="hidden">
<fieldset>
<legend>Lista de Precio</legend>
<div class="bloque_8">
<label for="id">Lista</label>
<input type="text" id="id" name="id" readonly>
</div>
<div class="bloque_6">
<label for="nombre">Nombre</label>
<input type="text" id="nombre" name="nombre" maxlength="50" class="text-uppercase">
</div>
<div class="bloque_9">
<br>
<?php $urlSend = '/pedidos/listas/logica/update.php';?>
<a title="Enviar">
<img class="icon-send" onclick="javascript:dac_sendForm(fmLista, '<?php echo $urlSend;?>');"/>
</a>
</div>
<div class="bloque_1">
<div id="desplegable" class="desplegable"> <?php
$categoriasComerc = DataManager::getCategoriasComerciales(1);
if (count($categoriasComerc)) {
foreach ($categoriasComerc as $k => $catComerc) {
$catComIdcat= $catComerc["catidcat"];
$catNombre = $catComerc["catnombre"]; ?>
<input id="categoriaComer<?php echo $catComIdcat; ?>" type="checkbox" name="categoriaComer[]" value="<?php echo $catComIdcat; ?>" style="float:left;"><label><?php echo $catComIdcat." - ".$catNombre; ?></label><hr>
<?php
}
} ?>
</div>
</div>
</fieldset>
</form>
</div>
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Listas de Precios</h1>
</div>
<div class="bloque_5" align="right">
<?php echo $btnNuevo ?>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table>
<thead>
<tr>
<th scope="colgroup" width="10%">Lista</th>
<th scope="colgroup" width="60%">Descripción</th>
<th scope="colgroup" width="10%">Categorís</th>
<th scope="colgroup" align="center" width="20%">Acciones</th>
</tr>
</thead>
<?php
$listas = DataManager::getListas();
if($listas){
foreach ($listas as $k => $lista) {
$id = $lista['IdLista'];
$nombre = $lista['NombreLT'];
$catComercial = $lista['CategoriaComercial'];
$categorias = str_replace(",", ", ", $catComercial);
$activa = $lista['Activa'];
$_onClick = sprintf( "onClick='dac_newList(\"%s\", \"%s\", \"%s\")'", $id, $nombre, $catComercial);
$_status = ($activa) ? "<img class=\"icon-status-active\"/>" : "<img class=\"icon-status-inactive\"/>";
$_borrar = sprintf( "<a href=\"logica/changestatus.php?id=%d&backURL=%s\" title=\"Cambiar Estado\">%s</a>", $id, $_SERVER['PHP_SELF'], $_status);
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\" class=\"cursor-pointer\" %s >%s</td><td class=\"cursor-pointer\" %s>%s</td><td class=\"cursor-pointer\" %s>%s</td><td>%s</td>", $_onClick, $id, $_onClick, $nombre, $_onClick, $categorias, $_borrar);
echo sprintf("</tr>");
}
}?>
</table>
</div>
</div>
<script>
function dac_newList(id, nombre, catComercial){
$('#id').val(id);
$('#nombre').val(nombre);
// Categorías
if(catComercial){
var categorias = catComercial.split(",");
}
//$('input:checkbox').removeAttr('checked');
$("input[name='categoriaComer[]']").prop('checked', false);
for (var i=0; i<categorias.length; i++){
$('#categoriaComer'+categorias[i]).prop('checked', true);
}
}
</script>
<file_sep>/planificacion/logica/ajax/update.parte.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//*******************************************
$_enviar = (isset($_POST['enviar'])) ? $_POST['enviar'] : NULL;
$_cantparte = (isset($_POST['cantparte'])) ? $_POST['cantparte'] : NULL;
$_fecha_plan = (isset($_POST['fecha_plan'])) ? $_POST['fecha_plan'] : NULL;
$_partecliente = json_decode(str_replace ('\"','"', $_POST['partecliente_Obj']), true);
$_partenombre = json_decode(str_replace ('\"','"', $_POST['partenombre_Obj']), true);
$_partedir = json_decode(str_replace ('\"','"', $_POST['partedir_Obj']), true);
$_partetrabaja = json_decode(str_replace ('\"','"', $_POST['partetrabaja_Obj']), true);
$_parteobservacion = json_decode(str_replace ('\"','"', $_POST['parteobservacion_Obj']),true);
$_parteacciones = json_decode(str_replace ('\"','"', $_POST['parteacciones_Obj']), true);
$_partenro = json_decode(str_replace ('\"','"', $_POST['nroparte_Obj']), true);
//*************************************************
//Controlo campos
//*************************************************
//controla si el envío del parte ya fue realizado
$_parte_diario = DataManager::getDetalleParteDiario($_fecha_plan, $_SESSION["_usrid"]);
if (count($_parte_diario)){
foreach ($_parte_diario as $k => $_partecontrol){
$_partecontrol = $_parte_diario[$k];
$_partecontrolactiva = $_partecontrol["parteactiva"];
if($_partecontrolactiva == 0){
echo "El Parte Diario Ya fue enviado. No puede ser modificado."; exit;
}
}
}
//*************************************************
//Controlo campos
//*************************************************
//controla que no se hayan repetido idclientes.
for($i = 0; $i < $_cantparte; $i++){
if($_partecliente[$i] != 0){ //discrimina el cero que serían clientes nuevos
for($j = 0; $j < $_cantparte; $j++){
if (($_partecliente[$i] == $_partecliente[$j]) && ($i!=$j)){
echo "No puede cargarse el mismo cliente más de una vez. Verifique el cliente ".$_partecliente[$i]; exit;
}
}
}
}
//*************************************************
//*************************************************
//Control de campos si quiere enviar el parte
//*************************************************
if ($_enviar == 1){
if(empty($_cantparte)){echo "No hay partes diarios cargados o no se envió aún la planificación."; exit;}
for($i = 0; $i < $_cantparte; $i++){
if(empty($_partenombre[$i])){ echo "Debe completar el nómbre de cliente del parte ".$_partenro[$i]; exit;} //($i + 1)
if(empty($_partedir[$i])){ echo "Debe completar dirección de cliente del parte ".$_partenro[$i]; exit;}
if(empty($_parteacciones) || empty($_parteacciones[$i])){ echo "Debe completar alguna acción del parte ".$_partenro[$i]; exit;
} else{
$acciones = explode(',', $_parteacciones[$i]);
for($j = 0; $j < count($acciones); $j++){
if($acciones[$j] == 10){ //Si accion No Realizada, aclarar por qué y que solo esté esa acción
if(count($acciones)>1){
echo "Verifique el parte ".$_partenro[$i].". Si No realizó acciones, no puede elegir otra acción."; exit;
}
if (empty($_parteobservacion[$i])){echo "Indique el motivo de la acción No realizada del parte ".$_partenro[$i]; exit;}
}
}
}
}
}
//*************************************************
$date = $_fecha_plan;
list($dia, $mes, $ano) = explode('-', str_replace('/', '-', $date));
$_fecha_plan = $ano."-".$mes."-".$dia;
//*******************************************
//BORRO EL REGISTRO EN ESA FECHA Y ESE VENDEDOR
//*******************************************
$ID = DataManager::deleteFromParte($_SESSION["_usrid"], $_fecha_plan);
//*******************************************
// GRABO EL PARTE
//*******************************************
for($i = 0; $i < $_cantparte; $i++){
if(empty($_partenombre[$i]) || empty($_partedir[$i])){
echo "Hubo un error al cargar los datos. Revise y vuelva a intentarlo"; exit;
}
$_parteobject = DataManager::newObjectOfClass('TPartediario');
$_parteobject->__set('ID', $_parteobject->__newID());
$_parteobject->__set('IDVendedor', $_SESSION["_usrid"]);
$_parteobject->__set('Fecha', $_fecha_plan);
if (empty($_partecliente[$i])){ $_parteobject->__set('Cliente', 0);
} else { $_parteobject->__set('Cliente', $_partecliente[$i]);}
$_parteobject->__set('Nombre', $_partenombre[$i]); //htmlentities($_partenombre[$i], ENT_QUOTES,'UTF-8'));
$_parteobject->__set('Direccion', $_partedir[$i]); //htmlentities($_partedir[$i], ENT_QUOTES,'UTF-8'));
$_parteobject->__set('Trabajocon', $_partetrabaja[$i]);
$_parteobject->__set('Observacion', $_parteobservacion[$i]); //htmlentities($_parteobservacion[$i], ENT_QUOTES,'UTF-8'));
$acciones = (empty($_parteacciones) || empty($_parteacciones[$i])) ? '0' : $_parteacciones[$i];
$_parteobject->__set('Acciones', $acciones);
//$_parteobject->__set('EnvioPlanif', $_parteacciones[$i]);
//Al realizar el envío, se crea el objeto para cargarlo como parte ENVIADO (y se graba la fecha de envío) o sin enviar si se hace clic en botón guardar
if ($_enviar == 1){
$time = time();
$_parte_fecha_envio = date("Y-m-d H:i:s");
$_parteobject->__set('Envio' , $_parte_fecha_envio);
$_parteobject->__set('Activa' , '0');
} else {
$_parteobject->__set('Envio' , date("2001-01-01 00:00:00"));
$_parteobject->__set('Activa' , '1'); }
$ID_parte = DataManager::insertSimpleObject($_parteobject);
if (empty($ID_parte)) { echo "Error Parte. $ID."; exit; }
}
echo $_enviar;
?><file_sep>/includes/class/class.llamada.php
<?php
require_once('class.PropertyObject.php');
class TLlamada extends PropertyObject {
protected $_tablename = 'llamada';
protected $_fieldid = 'llamid';
protected $_fieldactivo = 'llamactiva';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'llamid';
$this->propertyTable['Origen'] = 'llamorigen';
$this->propertyTable['IDOrigen'] = 'llamorigenid';
$this->propertyTable['Telefono'] = 'llamtelefono';
$this->propertyTable['Fecha'] = 'llamfecha';
$this->propertyTable['TipoResultado'] = 'llamtiporesultado';
$this->propertyTable['Resultado'] = 'llamresultado';
$this->propertyTable['Observacion'] = 'llamobservacion';
$this->propertyTable['UsrUpdate'] = 'llamusrupdate';
$this->propertyTable['LastUpdate'] = 'llamlastupdate';
$this->propertyTable['Activa'] = 'llamactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/droguerias/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$drogtId = empty($_REQUEST['drogtid']) ? 0 : $_REQUEST['drogtid']; //ID de la droguería
$drogueriaCAD = empty($_REQUEST['drogid']) ? 0 : $_REQUEST['drogid']; //ID de la droguería CAD
$empresa = empty($_REQUEST['empresa']) ? 0 : $_REQUEST['empresa'];
if ($drogtId) {
$objectDrog = DataManager::newObjectOfClass('TDrogueria', $drogtId);
$id = $objectDrog->__get('ID');
$empresa = $objectDrog->__get('IDEmpresa');
$cuenta = $objectDrog->__get('Cliente');
$correotransfer = $objectDrog->__get('CorreoTransfer');
$tipotransfer = $objectDrog->__get('TipoTransfer');
$rentTl = $objectDrog->__get('RentabilidadTL');
$rentTd = $objectDrog->__get('RentabilidadTD');
$cadId = $objectDrog->__get('CadId');
$drogueriasCAD = DataManager::getDrogueriaCAD('', $empresa, $cadId);
if (count($drogueriasCAD)) {
foreach ($drogueriasCAD as $k => $drogCAD) {
$nombreCAD = $drogCAD['dcadNombre'];
}
}
} else {
$id = "";
$cuenta = "";
$correotransfer = "";
$tipotransfer = "";
$rentTl = "";
$rentTd = "";
if($drogueriaCAD){
$drogueriasCAD = DataManager::getDrogueriaCAD('', $empresa, $drogueriaCAD);
if (count($drogueriasCAD)) {
foreach ($drogueriasCAD as $k => $drogCAD) {
$cadId = $drogCAD['dcadId'];
$nombreCAD = $drogCAD['dcadNombre'];
}
}
} else {
$cadId = "";
$empresa = "";
$nombreCAD = "";
}
} ?>
<!DOCTYPE html>
<html>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = 'droguerias';
$_subsection = 'nueva_drogueria';
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<div class="box_body">
<form id="fmDrogueria" name="fmDrogueria" method="post">
<fieldset>
<legend>Droguería</legend>
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<div class="bloque_1">
<?php $urlSend = '/pedidos/droguerias/logica/update.drogueria.php';?>
<a id="btnSend" title="Enviar">
<img class="icon-send" onclick="javascript:dac_sendForm(fmDrogueria, '<?php echo $urlSend;?>');"/>
</a>
</div>
<div class="bloque_1">
<label for="empresa">Empresa</label>
<select id="empresa" name="empresa"> <?php
$empresas = DataManager::getEmpresas(1);
if (count($empresas)) {
foreach ($empresas as $k => $emp) {
$idEmp = $emp["empid"];
$nombreEmp = $emp["empnombre"];
if ($idEmp == $empresa){ ?>
<option id="<?php echo $idEmp; ?>" value="<?php echo $idEmp; ?>" selected><?php echo $nombreEmp; ?></option><?php
} else { ?>
<option id="<?php echo $idEmp; ?>" value="<?php echo $idEmp; ?>"><?php echo $nombreEmp; ?></option><?php
}
}
} ?>
</select>
</div>
<div class="bloque_7">
<label for="drogid">Drogueria</label>
<input type="text" id="drogid" name="drogid" readonly value="<?php echo $cadId; ?>">
</div>
<div class="bloque_5">
<label for="nombre">Nombre</label>
<input type="text" id="nombre" name="nombre" class="text-uppercase" value="<?php echo $nombreCAD; ?>" >
</div>
<div class="bloque_7">
<label for="drogtcliid">Cuenta Asociada</label>
<input name="drogtcliid" id="drogtcliid" type="text" maxlength="10" value="<?php echo @$cuenta;?>">
</div>
<div class="bloque_1">
Los pedidos transfers se enviarán filtrando por iguales destinos de correo. Controle el correcto ingreso de éste campo.
</div>
<div class="bloque_5">
<label for="drogtcorreotrans">Correo Transfer</label>
<input name="drogtcorreotrans" id="drogtcorreotrans" type="text" maxlength="50" value="<?php echo @$correotransfer;?>">
</div>
<div class="bloque_7">
<label for="drogttipotrans">Tipo Transfer</label>
<select id="drogttipotrans" name="drogttipotrans">
<option id="0" value="0" <?php if(!$tipotransfer) { echo "selected";} ?>></option>
<option id="A" value="A" <?php if($tipotransfer == "A"){ echo "selected";} ?>>A</option>
<option id="B" value="B" <?php if($tipotransfer == "B"){ echo "selected";} ?>>B</option>
<option id="C" value="C" <?php if($tipotransfer == "C"){ echo "selected";} ?>>C</option>
<option id="D" value="D" <?php if($tipotransfer == "D"){ echo "selected";} ?>>D</option>
</select>
</div>
<div class="bloque_8">
<label for="rentTl">Rent. TL</label>
<input id="rentTl" name="rentTl" type="text" value="<?php echo @$rentTl;?>" maxlength="10" onkeydown="ControlComa(this.id, this.value);" onkeyup="ControlComa(this.id, this.value);"/>
</div>
<div class="bloque_8">
<label for="rentTd">Rent. TD</label>
<input id="rentTd" name="rentTd" type="text" value="<?php echo @$rentTd;?>" maxlength="10" onkeydown="ControlComa(this.id, this.value);" onkeyup="ControlComa(this.id, this.value);"
</div>
<input type="hidden" name="drogtid" value="<?php echo @$id;?>" >
</fieldset>
</form>
</div> <!-- FIN box_body -->
<hr>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/informes/logica/vaciar_factcontra.php
<?php
$ruta = $_SERVER['DOCUMENT_ROOT'].'/pedidos/informes/archivos/facturas/contrareembolso/'; //Decalaramos una variable con la ruta en donde vaciaré los archivos
$files = glob($ruta.'*'); // get all file names
if ($files) {
$cont = 0;
foreach($files as $file){ // iterate files
if(is_file($file)) {
if((time()-filemtime($file) > 3600*24*15) and !(is_dir($file))){
unlink($file); // delete file
$cont++;
}
}
}
$mensage = 'Se eliminaron '.$cont.' facturas';
} else {
$mensage = 'No existen facturas para borrar';
}
echo $mensage;// Regresamos los mensajes generados al cliente*/
//Si desea borrar todo de la carpeta (incluidas las subcarpetas) utiliza esta combinación de array_map , unlink y glob :
//array_map('unlink', glob("path/to/temp/*"));
/**
* Delete a file or recursively delete a directory
*
* @param string $str Path to file or directory
*/
/*function recursiveDelete($str){
if(is_file($str)){
return @unlink($str);
}
elseif(is_dir($str)){
$scan = glob(rtrim($str,'/').'/*');
foreach($scan as $index=>$path){
recursiveDelete($path);
}
return @rmdir($str);
}
}*/
?><file_sep>/js/provincias/selectScript.provincia.js
/*La funcion $( document ).ready hace que no se carge el script hasta que este cargado el html*/
$( document ).ready(function() {
/*Esta funcion se activa cada vez que se cambia el elemento seleccionado del <select id=provincia>*/
$('#provincia').change(function(){
/*Variable para almacenar la informacion que nos devuelve el servicio php*/
var localidades;
/*Coge el value de elemento seleccionado del <select id=provincia>*/
var idProvincia = $('#provincia option:selected').val();
/*Esta es la funcion de la peticion ajax. El primer parametro es la direccion del servicio php
en el que se hace la peticion de informacion, el segundo parametro es la funcion que se ejecuta
cuando se devuelve los datos por JSON.
El ajax accede desde el html que lo carga no desde el script de js.*/
$.getJSON('/pedidos/js/provincias/getLocalidades.php?codigoProvincia='+idProvincia, function(datos) {
localidades = datos;
/*Borro la lista cada vez que se pide una nueva provincia para que no se acumulen las anteriores*/
$('#f_localidad').find('option').remove();
/*Hago un foreach en jQuery para cada elemento del array ciudades y lo inserto en el <select id="ciudad">*/
$.each( localidades, function( key, value ) {
$('#f_localidad').append("<option value='" + value + "'>" + value + "</option>");
});
});
});
});
<file_sep>/contactos/logica/ajax/delete.contacto.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$_ctoid = empty($_REQUEST['ctoid']) ? 0 : $_REQUEST['ctoid'];
if ($_ctoid) {
$_contactoobject = DataManager::newObjectOfClass('TContacto', $_ctoid);
$_contactoobject->__set('ID', $_ctoid);
$ID = DataManager::deleteSimpleObject($_contactoobject);
}
echo 1; exit;
?><file_sep>/pedidos/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$idPropuesta = empty($_REQUEST['propuesta']) ? 0 : $_REQUEST['propuesta'];
$condPago = 0;
if($idPropuesta) {
$propObject = DataManager::newObjectOfClass('TPropuesta', $idPropuesta);
$idCuenta = $propObject->__get('Cuenta');
$usrAsignado = $propObject->__get('UsrAsignado');
$idEmpresa = $propObject->__get('Empresa');
$estado = $propObject->__get('Estado');
$idLaboratorio = $propObject->__get('Laboratorio');
$nombreCuenta = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $idCuenta, $idEmpresa);
$lista = DataManager::getCuenta('ctalista', 'ctaidcuenta', $idCuenta, $idEmpresa);
$listaNombre = DataManager::getLista('NombreLT', 'IdLista', $lista);
$observacion = $propObject->__get('Observacion');
$detalles = DataManager::getPropuestaDetalle($idPropuesta);
if ($detalles) {
foreach ($detalles as $j => $det) {
$condPago = $det["pdcondpago"];
$idArt = $det['pdidart'];
$unidades = $det['pdcantidad'];
$descripcion = DataManager::getArticulo('artnombre', $idArt, 1, 1);
$precio = $det['pdprecio'];
$b1 = ($det['pdbonif1'] == 0) ? '' : $det['pdbonif1'];
$b2 = ($det['pdbonif2'] == 0) ? '' : $det['pdbonif2'];
$desc1 = ($det['pddesc1'] == 0) ? '' : $det['pddesc1'];
$desc2 = ($det['pddesc2'] == 0) ? '' : $det['pddesc2'];
}
}
} else {
$idCuenta = "";
$nombreCuenta = "";
$usrAsignado = $_SESSION["_usrid"];
$idEmpresa = 1;
$estado = "";
$idLaboratorio = 1;
$observacion = "";
$lista = 0;
$listaNombre = "";
} ?>
<!DOCTYPE html>
<html lang='es'>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php"; ?>
<script language="JavaScript" src="/pedidos/pedidos/logica/jquery/jquery.js" type="text/javascript"></script>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "pedidos";
$_subsection = "nuevo_pedido";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<div class="box_body">
<div class="bloque_1">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
<fieldset id='box_observacion' class="msg_alerta">
<div id="msg_atencion"></div>
</fieldset>
</div>
<form id="fmPedidoWeb" name="fmPedidoWeb" method="post">
<input type="text" id="pwestado" name="pwestado" value="<?php echo $estado; ?>" hidden="hidden">
<input type="text" id="pwidcondcomercial" name="pwidcondcomercial" value="0" hidden="hidden">
<div class="bloque_5">
<h2><label id="pwcondcomercial"></label></h2>
</div>
<input type="text" id="pwlista" name="pwlista" value="<?php echo $lista; ?>" hidden="hidden">
<div class="bloque_5">
<h2><label id="pwlistanombre"><?php echo $listaNombre; ?></label></h2>
</div>
<hr>
<fieldset>
<legend>Pedido Web</legend>
<div class="bloque_5">
<label for="pwusrasignado">Asignado a</label>
<select id="pwusrasignado" name="pwusrasignado">
<option id="0" value="0" selected></option> <?php
$vendedores = DataManager::getUsuarios( 0, 0, 1, NULL, '"V"');
if (count($vendedores)) {
foreach ($vendedores as $k => $vend) {
$idVend = $vend["uid"];
$nombreVend = $vend['unombre'];
$rolVend = $vend['urol'];
if ($rolVend == 'V'){
if ($usrAsignado == $idVend ){
?><option id="<?php echo $idVend; ?>" value="<?php echo $idVend; ?>" selected><?php echo $nombreVend; ?></option><?php
} else { ?>
<option id="<?php echo $idVend; ?>" value="<?php echo $idVend; ?>"><?php echo $nombreVend; ?></option><?php
}
}
}
} ?>
</select>
</div>
<?php
$hiddenTipo = ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="M" || $_SESSION["_usrrol"]=="G") ? "" : "hidden";?>
<div class="bloque_7" <?php echo $hiddenTipo; ?> >
<label for="pwtipo" <?php echo $hiddenTipo; ?> >Tipo</label>
<select name="pwtipo" <?php echo $hiddenTipo; ?> >
<option value=""></option>
<option value="PARTICULAR">Cliente Particular</option>
<option value="SP">Salida Promoción</option>
<option value="SF">Solo Facturar</option>
<option value="VALE">Vale</option>
</select>
</div>
<div class="bloque_7">
<a id="btsend" title="Enviar">
<br>
<img class="icon-send">
</a>
</div>
<div class="bloque_5">
<label for="empselect">Empresa</label>
<select id="empselect" name="empselect" onchange="javascript:dac_selectChangeEmpresa(this.value);"> <?php
$empresas = DataManager::getEmpresas(1);
if (count($empresas)) {
foreach ($empresas as $k => $emp) {
$idEmp = $emp["empid"];
$nombreEmp = $emp["empnombre"];
if ($idEmp == $idEmpresa){ ?>
<option id="<?php echo $idEmp; ?>" value="<?php echo $idEmp; ?>" selected><?php echo $nombreEmp; ?></option><?php
} else { ?>
<option id="<?php echo $idEmp; ?>" value="<?php echo $idEmp; ?>"><?php echo $nombreEmp; ?></option><?php
}
}
} ?>
</select>
</div>
<div class="bloque_5">
<label for="labselect">Laboratorio</label>
<select name="labselect" id="labselect" onchange="javascript:dac_selectChangeLaboratorio(this.value);"><?php
$laboratorios = DataManager::getLaboratorios();
if (count($laboratorios)) {
foreach ($laboratorios as $k => $lab) {
$idLab = $lab["idLab"];
$descripcion = $lab["Descripcion"];
if ($idLab == $idLaboratorio){ ?>
<option id="<?php echo $idLab; ?>" value="<?php echo $idLab; ?>" selected><?php echo $descripcion; ?></option><?php
} else { ?>
<option id="<?php echo $idLab; ?>" value="<?php echo $idLab; ?>"><?php echo $descripcion; ?></option><?php
}
}
} ?>
</select>
</div>
<div class="bloque_8">
<label for="pwidcta">Cuenta</label>
<input type="text" name="pwidcta" id="pwidcta" value="<?php echo $idCuenta; ?>" readonly/>
</div>
<div class="bloque_5">
<label>Razón social</label>
<input type="text" name="pwnombrecta" id="pwnombrecta" value="<?php echo $nombreCuenta; ?>" readonly/>
</div>
<div class="bloque_8">
<label for="pworden">Orden</label>
<input type="text" name="pworden" id="pworden" maxlength="10"/>
</div>
<div class="bloque_7">
<label>Archivo</label>
<input name="file" class="file" type="file" hidden="hidden">
</div>
<div class="bloque_5">
<label>Condición de pago </label>
<select name="condselect" id="condselect"> <?php
$condicionesPago = DataManager::getCondicionesDePago(0, 0, 1);
if (count($condicionesPago)) { ?>
<option id="0" value="0" selected></option><?php
foreach ($condicionesPago as $k => $cond) {
$idCond = $cond['condid'];
$condCodigo = $cond['IdCondPago'];
$condNombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $cond['condtipo']);
$condDias = "(";
$condDias .= empty($cond['Dias1CP']) ? '0' : $cond['Dias1CP'];
$condDias .= empty($cond['Dias2CP']) ? '' : ', '.$cond['Dias2CP'];
$condDias .= empty($cond['Dias3CP']) ? '' : ', '.$cond['Dias3CP'];
$condDias .= empty($cond['Dias4CP']) ? '' : ', '.$cond['Dias4CP'];
$condDias .= empty($cond['Dias5CP']) ? '' : ', '.$cond['Dias5CP'];
$condDias .= " Días)";
$condDias .= ($cond['Porcentaje1CP'] == '0.00') ? '' : ' '.$cond['Porcentaje1CP'].' %';
$selected = ($condPago == $condCodigo) ? 'selected' : '' ;
?>
<option id="<?php echo $idCond; ?>" value="<?php echo $condCodigo; ?>" <?php echo $selected; ?>><?php echo $condNombre." - ".$condDias; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<input type="text" name="pwidpropuesta" id="pwidpropuesta" value="<?php echo $idPropuesta; ?>" hidden="hidden">
<input type="checkbox" name="pwpropuesta" id="pwpropuesta" value="1" style="margin-top:15px; float: left;" <?php if($idPropuesta){ echo "checked='checked'";}; ?>>
<br>
<label for="pwpropuesta"><strong>PROPUESTA</strong></label>
</div>
<div class="bloque_7">
<input type="checkbox" name="cadena" id="cadena" style="margin-top:15px; float: left;"/>
<br>
<label for="cadena" style="padding:20px 0 0 10px"><strong>CADENA</strong></label>
</div>
<div class="bloque_1">
<label>Observación</label>
<textarea type="text" name="pwobservacion" id="pwobservacion" maxlength="200" ><?php echo $observacion; ?></textarea>
</div>
</fieldset>
<fieldset>
<legend>Artículos</legend>
<div id="lista_articulos2"></div>
<div class="bloque_3">
<div id="pwsubtotal" style="display:none;"></div>
</div>
</fieldset>
</form>
</div> <!-- FIN box_body-->
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Cuentas</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn" type="text" value="tblTablaCta" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<div id='tablacuenta'></div>
</div> <!-- Fin lista -->
<div class="barra">
<div class="bloque_1">
<h1>Packs</h1>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<div id='tablacondiciones'></div>
</div> <!-- Fin lista -->
<div class="barra">
<div class="bloque_5">
<h1>Artículos</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar2" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn2" type="text" value="tblTablaArt" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<fieldset id='box_cargando3' class="msg_informacion">
<div id="msg_cargando3"></div>
</fieldset>
<div id='tablaarticulos'></div>
</div> <!-- Fin lista -->
</div> <!-- FIN box_seccion-->
<hr>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html>
<script language="JavaScript" type="text/javascript">
dac_selectChangeEmpresa(<?php echo $idEmpresa; ?>);
</script>
<?php
if($idPropuesta){
$detalles = DataManager::getPropuestaDetalle($idPropuesta);
if ($detalles) {
foreach ($detalles as $j => $det) {
$idArt = $det['pdidart'];
$unidades = $det['pdcantidad'];
$descripcion= DataManager::getArticulo('artnombre', $idArt, 1, 1);
$precio = $det['pdprecio'];
$b1 = ($det['pdbonif1'] == 0) ? '' : $det['pdbonif1'];
$b2 = ($det['pdbonif2'] == 0) ? '' : $det['pdbonif2'];
$desc1 = ($det['pddesc1'] == 0) ? '' : $det['pddesc1'];
$desc2 = ($det['pddesc2'] == 0) ? '' : $det['pddesc2'];
echo "<script>";
echo "javascript:dac_CargarArticulo('$idArt', '$descripcion', '$precio', '$b1', '$b2', '$desc1', '$desc2', '$unidades');";
echo "</script>";
}
}
} ?><file_sep>/includes/footer.inc.php
<?php
if($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="M" || $_SESSION["_usrrol"]=="G") {
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.admin.php");
} ?>
<div id="pie_contenido">
<?php
$_password = sprintf( "<a id=\"btsend\" href=\"/pedidos/usuarios/password/\" title=\"Cambiar Clave\">%s</a>", "<img class=\"icon-key\"/>");
if ($_SESSION["_usrrol"]!= "C"){ echo $_password; }
?>
<span class="copyright" title="Desarrollo Web + Diseño por Cioccolanti, <NAME>">Copyright © 2014-2020 <a href="https://www.neo-farma.com.ar" rel="copyright" title="Sitio web oficial de neo-farma.com.ar">neo-farma.com.ar</a> (daciocco)</span>
</div>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-120786037-1"></script>
<script>
/* <EMAIL> */
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-120786037-1');
</script>
<file_sep>/cuentas/facturacion/lista.php
<div class="box_body">
<fieldset>
<legend>Factura</legend>
<div class="bloque_1">
<div id="fact" style="overflow:auto;"></div>
</div>
</fieldset>
</div> <!-- Fin box_body -->
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1> Facturas Contrarreembolso</h1>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista"><?php
$ruta = $_SERVER['DOCUMENT_ROOT'].'/pedidos/informes/archivos/facturas/contrareembolso/';
$data = dac_listar_directorios($ruta);
if($data){ ?>
<table align="center">
<thead>
<tr align="left">
<th>Subido</th>
<th>Factura</th>
</tr>
</thead>
<tbody>
<?php
$fila = 0;
$zonas = explode(", ", $_SESSION["_usrzonas"]);
foreach ($data as $file => $timestamp) {
$name = explode("-", $timestamp);
for($i = 0; $i < count($zonas); $i++){
$nro_zona = trim($name[3]);
if($nro_zona == $zonas[$i]){
$archivo = trim($name[3])."-Factura-".$name[5]."-".$name[6];
$fila = $fila + 1;
(($fila % 2) == 0)? $clase="par" : $clase="impar"; ?>
<tr class="<?php echo $clase;?>" onclick="javascript:dac_ShowFactura('<?php echo $archivo;?>')">
<td><?php echo $name[0]."/".$name[1]."/".$name[2]; ?></td>
<td><?php echo $name[5]."-".$name[6]; ?></td>
</tr>
<?php
}
}
} ?>
</tbody>
</table> <?php
} else { ?>
<table align="center">
<tr>
<td colspan="3"><?php echo "No hay facturas cargadas."; ?></td>
</tr>
</table><?php
} ?>
</div> <!-- Fin listar -->
</div> <!-- Fin box_seccion -->
<hr>
<script language="JavaScript" type="text/javascript">
function dac_ShowFactura(archivo){
$("#fact").empty();
campo = '<iframe src=\"https://docs.google.com/gview?url=https://neo-farma.com.ar/pedidos/informes/archivos/facturas/contrareembolso/'+archivo+'&embedded=true\" style=\"width:560px; height:800px;\" frameborder=\"0\"></iframe>';
$("#fact").append(campo);
}
</script><file_sep>/includes/start.php
<?php
session_start();
if (empty($_SESSION["_usrid"])) {
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrid"];
header("Location: $_nextURL");
exit;
}
date_default_timezone_set('America/Argentina/Buenos_Aires');
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/detect.Browser.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php");
?><file_sep>/includes/class/class.cuenta.php
<?php
require_once('class.PropertyObject.php');
class TCuenta extends PropertyObject {
protected $_tablename = 'cuenta';
protected $_fieldid = 'ctaid';
protected $_fieldactivo = 'ctaactiva';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'ctaid';
$this->propertyTable['Empresa'] = 'ctaidempresa';
$this->propertyTable['Cuenta'] = 'ctaidcuenta'; //(NroVendedor + nrolibre)
$this->propertyTable['Tipo'] = 'ctatipo'; //CLIENTE/TRANSFER/PROSPECTO/PROVEEDOR
$this->propertyTable['Estado'] = 'ctaestado'; //Estado actual Ej: Solicita Alta
$this->propertyTable['Nombre'] = 'ctanombre';
$this->propertyTable['CUIT'] = 'ctacuit'; //CUIT
$this->propertyTable['Zona'] = 'ctazona'; //idvendedor Hiper y ZONA GEOGRÁFICA
$this->propertyTable['ZonaEntrega'] = 'ctazonaentrega'; //para deposito
$this->propertyTable['Pais'] = 'ctaidpais';
$this->propertyTable['Provincia'] = 'ctaidprov';
$this->propertyTable['Localidad'] = 'ctaidloc';
$this->propertyTable['LocalidadNombre'] = 'ctalocalidad';
$this->propertyTable['Direccion'] = 'ctadireccion';
$this->propertyTable['DireccionEntrega'] = 'ctadireccionentrega';
$this->propertyTable['Numero'] = 'ctadirnro';
$this->propertyTable['Piso'] = 'ctadirpiso';
$this->propertyTable['Dpto'] = 'ctadirdpto';
$this->propertyTable['CP'] = 'ctacp';
$this->propertyTable['Longitud'] = 'ctalongitud';
$this->propertyTable['Latitud'] = 'ctalatitud';
$this->propertyTable['Ruteo'] = 'ctaruteo'; //cada cuantos días vender al cliente.
$this->propertyTable['CategoriaComercial'] = 'ctacategoriacomercial'; // Categoría Comercial
$this->propertyTable['Referencias'] = 'ctareferencias'; //cantidad vendidas 12 meses
$this->propertyTable['CuentaContable'] = 'ctacuentacontable'; //cuentascontables deHiperwin
$this->propertyTable['CondicionPago'] = 'ctacondpago';
$this->propertyTable['Empleados'] = 'ctacantempleados';
$this->propertyTable['Bonif1'] = 'ctabonif1';
$this->propertyTable['Bonif2'] = 'ctabonif2';
$this->propertyTable['Bonif3'] = 'ctabonif3';
$this->propertyTable['CategoriaIVA'] = 'ctacategoriaiva'; //"TipoIva" Tabla "Categorias"
$this->propertyTable['RetencPercepIVA'] = 'ctaretperciva'; //Ret(Cliente)-Perc(Proveedor)
$this->propertyTable['Credito'] = 'ctacredito'; //límite aceptado al cliente
$this->propertyTable['NroEmpresa'] = 'ctanroempresa';
$this->propertyTable['NroIngresosBrutos'] = 'ctanroingbruto';
$this->propertyTable['FechaAlta'] = 'ctafechaalta'; //SI pasa solicitud Alta a ALTA)?
$this->propertyTable['FechaCompra'] = 'ctafechacompra';
$this->propertyTable['Email'] = 'ctacorreo';
$this->propertyTable['Telefono'] = 'ctatelefono';
$this->propertyTable['Web'] = 'ctaweb';
$this->propertyTable['Observacion'] = 'ctaobservacion';
$this->propertyTable['Imagen1'] = 'ctaimagen1'; //id de imagen
$this->propertyTable['Imagen2'] = 'ctaimagen2'; //id de imagen
$this->propertyTable['IDCuentaRelacionada'] = 'ctaidctarelacionada'; //tabla"cuenta_relacionada"
$this->propertyTable['UsrCreated'] = 'ctausrcreated';
$this->propertyTable['DateCreated'] = 'ctacreated';
$this->propertyTable['UsrAssigned'] = 'ctausrassigned';
$this->propertyTable['UsrUpdate'] = 'ctausrupdate';
$this->propertyTable['LastUpdate'] = 'ctaupdate';
$this->propertyTable['Activa'] = 'ctaactiva';
$this->propertyTable['Lista'] = 'ctalista';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/proveedores/logica/changestatus.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$_provid = empty($_REQUEST['provid']) ? 0 : $_REQUEST['provid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/proveedores/' : $_REQUEST['backURL'];
if ($_provid) {
$_provobject = DataManager::newObjectOfClass('TProveedor', $_provid);
/*************************************************************/
//Al cambiar el estatus, si llega a ser nro 3 (solicitud de activación realizada)
//se procederá a enviar mail al email del proveedor, infoweb y <EMAIL> que el usuario fue dado de alta.
if($_provobject->__get('Activo') == 3){
//**************************************************
// Armado del CORREO para el envío
//**************************************************
$_usuario = $_provobject->__get('Login');
$_email = $_provobject->__get('Email');
$_empresa = $_provobject->__get('Empresa');
$_empresas = DataManager::getEmpresas(1);
if (count($_empresas)) {
foreach ($_empresas as $k => $_emp) {
$_idemp = $_emp["empid"];
if ($_idemp == $_empresa){
$_nombreemp = $_emp["empnombre"];
}
}
}
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = "<EMAIL>"; //mail de solicitante
$mail->FromName = "InfoWeb GEZZI"; //"Vendedor: ".$_SESSION["_usrname"];
$mail->Subject = "Datos de registro de ".$_usuario." en ".$_nombreemp.", guarde este email.";
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
$_total = '
<html>
<head>
<title>Confirmación de Alta de Proveedor</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 90%;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 0px;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>
<body>
<div align="center">
<table width="600" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
El usuario <b>'.$_usuario.' </b> <strong>HA SIDO ACTIVADO</strong> en <strong>'.$_nombreemp.'</strong> <br />
Puede acceder a la web haciendo clic en <a href="https://www.neo-farma.com.ar/pedidos/login/">acceso web</a> o desde el Uso Interno en web www.neo-farma.com.ar
<div />
</td >
</tr>
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con la empresa al 4555-3366 de Lunes a Viernes de 10 a 17 horas.
</font>
</br></br>
</div>
</td>
</tr>
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Gracias por registrarse en '.$_nombreemp.'<br />
Le Saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
';
$mail->msgHTML($_total);
$mail->AddAddress($_email, "InfoWeb");
$mail->AddBCC("<EMAIL>", "InfoWeb");
$mail->AddBCC("<EMAIL>", "InfoWeb");
switch($_empresa) {
case 1:
$mail->AddBCC("<EMAIL>");
break;
case 3:
$mail->AddBCC("<EMAIL>");
break;
case 4:
$mail->AddBCC("<EMAIL>");
break;
default:
$mail->AddBCC("<EMAIL>");
break;
}
//*****************************************************************//
//*******************************************************************
//no se controla error de correo
if(!$mail->Send()) {
echo "Ocurrió un ERROR al intentar activar el Usuario. Consulte con el administrador de la web antes de volver a intentarlo."; exit;
//Si el envío falla, que mande otro mail indicando que la solicittud no fue correctamente enviada?=?
//echo 'Fallo en el envío';
/*$_goURL = "../index.php?sms=21";
header('Location:' . $_goURL);
exit;*/
}
//*******************************************************************
$_status = 1;
} else {
$_status = ($_provobject->__get('Activo')) ? 0 : 1;
}
$_provobject->__set('Activo', $_status);
$ID = DataManager::updateSimpleObject($_provobject);
}
header('Location: '.$backURL.'?pag='.$_pag);
?><file_sep>/login/index.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/detect.Browser.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
$HOME = $_SERVER['DOCUMENT_ROOT']."/pedidos/index.php";
$_step = empty($_REQUEST["_step"]) ? 1 : $_REQUEST["_step"];
$_nextURL = (isset($_REQUEST["_go"])) ? sprintf("%s?_go=%s", $_SERVER["PHP_SELF"], $_REQUEST["_go"]) : $HOME;
$_goURL = (isset($_REQUEST["_go"])) ? $_REQUEST["_go"] : "/pedidos/index.php"; // url destino
$_salimos = false;
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/login/': $_REQUEST['backURL'];
switch ($_step) {
// Solo la primera vez ( el resto entra por el caso por defecto)
case 1:
$usrusuario = "";
$usrpassword = "";
$usrtipo = "";
//$usrrol = $USR_OPERADOR;
$_message = "";
break;
default:
$_message = "Introduzca credenciales de usuario";
$usrusuario = $_REQUEST["usrusuario"];
$usrpassword = $_REQUEST["usrpassword"];
$usrtipo = (isset($_REQUEST["usrtipo"])) ? $_REQUEST["usrtipo"] : '';
unset($_SESSION["_usrid"], $_SESSION["_usrrol"], $_SESSION["_usrname"], $_SESSION["_usrlogin"]);
switch ($usrtipo){
case 'P':
$_ID = DataManager::getIDByField('TProveedor', 'provlogin', $usrusuario);
break;
default:
$_ID = DataManager::getIDByField('TUsuario', 'ulogin', $usrusuario);
break;
}
if ($_ID > 0) {
switch ($usrtipo){
case 'P':
$_usrobject = DataManager::newObjectOfClass('TProveedor', $_ID);
$usrtipo = 'P';
break;
default:
$_usrobject = DataManager::newObjectOfClass('TUsuario', $_ID);
break;
}
$_SESSION["_usractivo"] = $_usrobject->__get("Activo");
//Si el usuario fue desactivado, no podrá loguearse
if ($_SESSION["_usractivo"] != 1) {
$_message = "Su usuario está inactivo.";
} else {
if ($_usrobject->login(md5($usrpassword))) {
$_SESSION["_usrid"] = $_ID;
$_SESSION["_usrname"] = $_usrobject->__get("Nombre");
$_SESSION["_usrlogin"] = $_usrobject->__get("Login");
$_SESSION["_usrclave"] = $_usrobject->__get("Clave");
$_SESSION["_usremail"] = $_usrobject->__get("Email");
if (empty($usrtipo)){
$_SESSION["_usrrol"] = $_usrobject->__get("Rol");
$_SESSION["_usrdni"] = $_usrobject->__get("Dni");
} else {
$_SESSION["_usrrol"] = $usrtipo;
$_SESSION["_usrcuit"] = $_usrobject->__get("Cuit");
//Si el usuario es proveedor, debo tener sus datos extras
if ($usrtipo == 'P') {
$_SESSION["_usridemp"] = $_usrobject->__get("Empresa");
}
}
$_goURL = empty($_goURL) ? "/pedidos/index.php" : $_goURL;
$_salimos = true;
// SI EL ROL ES DISTINTO DE P O C
// Teniendo el Vendedor, consulto sus Zonas
if ($_SESSION["_usrrol"] != "P"){
if (empty($usrtipo)){
$_zonas = DataManager::getZonasVendedor($_ID, 0);
unset($_SESSION["_usrzonas"]);
if (count($_zonas) ) {
foreach ($_zonas as $k => $_zona) {
if ($_SESSION["_usrzonas"] == ""){ $_SESSION["_usrzonas"] = $_zona["zona"];
} else { $_SESSION["_usrzonas"] = $_SESSION["_usrzonas"].", ".$_zona["zona"]; }
}
}
}
}
} else { $_message = "Password incorrecto"; }
}
} else { $_message = "Usuario inexistente"; }
break;
}
if ($_salimos) {
header("Location: $_goURL");
exit;
}
// valores para configuracion del formulario
$_step++;
$btAccion = sprintf("<input id=\"bt_login\" name=\"_accion\" type=\"submit\" value=\"Iniciar\"/>");
/**************************/
$_info = "";
$_sms = empty($_GET['sms']) ? 0 : $_GET['sms'];
if ($_sms) {
$_rec_usuario = $_SESSION['s_usuario'];
$_rec_mail = $_SESSION['s_email'];
switch ($_sms) {
case 1: $_info = "El usuario es incorrecto."; break;
case 2: $_info = "El formato de correo es incorrecto."; break;
case 3: $_info = "El correo es incorrecto."; break;
case 4: $_info = "Se han enviado los datos a la cuenta de correo del usuario."; break;
} // mensaje de error
}
$_button = sprintf("<input type=\"submit\" id=\"f_enviar\" name=\"_accion\" value=\"Restaurar\"/>");
$_action = "/pedidos/usuarios/logica/recupera.usuario.php?backURL=".$backURL;
?>
<script language="JavaScript" src="/pedidos/js/jquery/jquery-2.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
// FUNCIONES PARA ABRIR Y CERRAR LOS POPUPS
$(document).ready(function(){
$('#recuperar-clave').click(function(){
$('#popup-recupera').fadeIn('slow');
$('#popup-recupera').css({ //coloca el popup-recupera centrado en la web, solo al momento de crearse
'left': ($(window).width() / 2 - $('popup-recupera').width() / 2) + 'px',
'top': ($(window).height() / 2 - $('popup-recupera').height() / 2) + 'px'
});
$('.popup-overlay').fadeIn('slow');
$('.popup-overlay').height($(window).height());
return false;
});
$('#close-recupera').click(function(){
$('#popup-recupera').fadeOut('slow');
$('.popup-overlay').fadeOut('slow');
return false;
});
});
</script>
<script type="text/javascript">
function dac_recuperar(sms){
if (sms){
document.getElementById("popup-recupera").style.display = 'inline';
}
}
</script>
<!DOCTYPE html>
<html lang='es'>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php"; ?>
</head>
<!-- uso de particles -->
<body id="particles-js">
<!--main></main-->
<div class="fmlogin" align="center">
<img id="imglogo" src="../images/logo/logoLogin.png" width="260px" />
<form method="post" action="<?php sprintf("%s", $_nextURL); ?>" >
<fieldset>
<div class="bloque_3">
<input name="usrusuario" id="usrusuario" maxlength="15" type="text" placeholder="Usuario" title="Usuario" value="<?php echo @$usrusuario;?>"/>
</div>
<div class="bloque_7">
<img title="Usuario" class="icon-user"/>
</div>
<div class="bloque_3">
<input name="usrpassword" id="usrpassword" maxlength="10" type="password" title="Clave no debe superar los 10 dígitos" placeholder="Clave" value="<?php echo @$usrpassword;?>"/>
</div>
<div class="bloque_7">
<img title="Clave" class="icon-key-loguin"/>
</div>
<hr>
<div class="bloque_3" align="right">
<label>Soy Proveedor
<input name="usrtipo" id="usrtipo" type="radio" value="P">
</label>
</div>
<div class="bloque_7">
<img title="Proveedor" class="icon-provider"/>
</div>
<div class="bloque_1" align="right">
</div>
<div class="bloque_1" align="right">
<div id="recuperar-clave" class="link-loguin" align="right">¿Olvidé mi clave?</div>
</div>
<div class="bloque_1" align="right">
<a href="registrarme/" style="text-decoration:none;"><div id="registrarme" class="link-loguin" align="right">Registrarme como Proveedor</div></a>
</div>
<div class="bloque_1" align="right">
</div>
<div class="bloque_4"></div>
<div class="bloque_6"> <?php echo $btAccion;?> </div>
</fieldset>
<input type="hidden" name="_step" id="_step" value="<?php echo @$_step;?>"/>
<div class="bloque_1">
<?php if($_message) { ?>
<fieldset id='box_error' class="msg_error" style="display: block">
<div id="msg_error"><?php echo $_message;?></div>
</fieldset>
<?php } ?>
</div>
</form>
<div id="popup-recupera" style="display:none;">
<form method="post" action="<?php echo $_action;?>">
<fieldset>
<legend>Restaurar Clave</legend>
<div class="bloque_1">
<a href="#" id="close-recupera" style="float:right;">
<img id="img-close" src="/pedidos/images/popup/close.png"/></a>
</div>
<div class="bloque_3">
<input name="rec_usuario" id="rec_usuario" maxlength="15" type="text" placeholder="Usuario" value="<?php echo @$_rec_usuario;?>" />
</div>
<div class="bloque_7">
<img title="Usuario" class="icon-user"/>
</div>
<div class="bloque_3">
<input name="rec_mail" id="rec_mail" maxlength="50" type="text" placeholder="Correo electrónico" value="<?php echo @$_rec_mail;?>" />
</div>
<div class="bloque_7">
<img class="icon-mail"/>
</div>
<div class="bloque_4"></div>
<div class="bloque_6"><?php echo $_button; ?></div>
</fieldset>
<input type="hidden" name="_sms" id="_sms" value="<?php echo @$_sms;?>" />
<div class="bloque_1">
<?php if($_info) { ?>
<fieldset id='box_error' class="msg_error" style="display: block">
<div id="msg_error"><?php echo $_info;?></div>
</fieldset>
<?php } ?>
</div>
</form>
</div><!-- fin popup-recupera -->
<?php
echo "<script>";
echo "javascript:dac_recuperar(".$_sms.")";
echo "</script>";
?>
</div>
</body>
<!-- uso de query particles -->
<script src="../js/particles/particles.js"></script>
<script>
particlesJS.load('particles-js', '../js/particles/particles.json', function(){
//console.log('particles.json loaded...');
});
</script>
<!---------------------------->
</html><file_sep>/relevamiento/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_relid = empty($_REQUEST['relid']) ? 0 : $_REQUEST['relid'];
if ($_relid) {
$_rel = DataManager::newObjectOfClass('TRelevamiento', $_relid);
$_nro = $_rel->__get('Relevamiento');
$_orden = $_rel->__get('Orden');
$_nulo = $_rel->__get('Nulo');
$_pregunta = $_rel->__get('Pregunta');
$_tipo = $_rel->__get('Tipo');
} else {
$_nro = "";
$_orden = "";
$_nulo = 0;
$_pregunta = "";
$_tipo = "";
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
<script type="text/javascript" src="jquery/jquery.enviar.js"></script>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = 'relevamientos';
$_subsection = 'nuevo_relevamiento';
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav> <!-- fin menu -->
<main class="cuerpo">
<div class="box_body">
<form id="fm_rel_edit" name="fm_rel_edit" method="post">
<fieldset>
<legend>Relevamiento</legend>
<div class="bloque_1">
<fieldset id='box_informacion' class="msg_informacion">
<div id="msg_informacion"></div>
</fieldset>
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<input type="hidden" id="relid" name="relid" value="<?php echo @$_relid;?>" />
<div class="bloque_8">
<label for="nro">Nro</label>
<input type="text" name="nro" id="nro" maxlength="2" value="<?php echo @$_nro;?>"/>
</div>
<div class="bloque_8">
<label for="orden">Orden</label>
<input type="text" name="orden" id="orden" maxlength="2" value="<?php echo @$_orden;?>"/>
</div>
<div class="bloque_7">
<label for="tipo">Tipo Respuesta</label>
<select id="tipo" name="tipo"/>
<option value="" <?php if(empty($_tipo)){echo 'selected="selected"';}?>></option>
<option value="abierto" <?php if($_tipo=="abierto"){echo 'selected="selected"';}?>>Abierto</option>
<option value="sino" <?php if($_tipo=="sino"){echo 'selected="selected"';}?>>Si/No</option>
<option value="cant" <?php if($_tipo=="cant"){echo 'selected="selected"';}?>>Cantidad</option>
<!--option value="multiopcion">Múltiples Opciones</option>
<option value="unicaopcion">Única Opción</option-->
</select>
</div>
<div class="bloque_7">
<label for="nulo" >Admite Nulos </label></br>
<input id="nulo" name="nulo" type="checkbox" <?php if($_nulo){echo "checked=checked";};?> />
</div>
<div class="bloque_8">
<br>
<input id="btsend" type="button" value="Enviar" title="Enviar Relevamiento"/>
</div>
<div class="bloque_1">
<label for="pregunta">Pregunta</label>
<textarea id="pregunta" name="pregunta" value="<?php echo $_pregunta;?>" onKeyUp="javascript:dac_LimitaCaracteres(event, 'pregunta', 200);" onKeyDown="javascript:dac_LimitaCaracteres(event, 'pregunta', 200);"/><?php echo $_pregunta;?></textarea>
</div>
</fieldset>
</form>
</div> <!-- boxbody -->
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/informes/logica/exportar.liquidacionPendExce.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
//*******************************************
// 1) UNIDADES PENDIENTES / EXCEDENTES
// Mostrará el ESTADO con un número positivo o negativo
// Si las unidades liquidadas son distintas a las unidades transfers pedidas
// y el número de diferencia por cada artículo
// 2) ARTÍCULOS FALTANTES
// Mostrará el ESTADO FALTANTES
// Si se pidió un artículo y la droguería núnca lo liquidó?
// 3) PEDIDOS SIN LIQUIDAR
// Mostrará el ESTADO SIN LIQUIDAR, si el número transfer
// no se encuentra liquidado en dicha droguería.
//
//*******************************************
$fechaDesde = (isset($_POST['fechaDesde'])) ? $_POST['fechaDesde'] : NULL;
$fechaHasta = (isset($_POST['fechaHasta'])) ? $_POST['fechaHasta'] : NULL;
if(empty($fechaDesde) || empty($fechaHasta)){ echo "Debe indicar las fechas a exportar"; exit; }
//*******************************************
$fechaInicio = new DateTime(dac_invertirFecha($fechaDesde));
$fechaFin = new DateTime(dac_invertirFecha($fechaHasta));
//$fechaFin->modify("+1 day");
//*************************************************
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=LiquidacionPendExce-".date('d-m-y').".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos .::</TITLE>
<head></head>
<body>
<?php
$droguerias = DataManager::getDrogueria();
if (count($droguerias)) { ?>
<table border="0">
<thead>
<tr>
<th scope="col" align="left" colspan="3">Exportado: <?php echo date("d-m-Y"); ?></th>
<th scope="col" align="left" colspan="2">Desde: <?php echo $fechaInicio->format("d-m-Y"); ?></th>
<th scope="col" align="left" colspan="2">Hasta: <?php echo $fechaFin->format("d-m-Y"); ?></th>
</tr>
<tr>
<th colspan="7">DIFERENCIA DE UNIDADES, ARTÍCULOS FALTANTES y PEDIDOS SIN LIQUIDAR</th>
</tr>
<tr> <th colspan="7"></th> </tr>
<tr>
<th align="left">Droguería</th>
<th align="left">Nombre</th>
<th align="left">Localidad</th>
<th align="left">Nro Transfer</th>
<th align="left">Artículo</th>
<th align="left">Fecha</th>
<th align="left">Estado</th>
</tr>
</thead>
<?php
foreach ($droguerias as $k => $drog) {
$drog = $droguerias[$k];
$drogId = $drog["drogtid"];
$drogIdCliente = $drog["drogtcliid"];
$drogIdEmpresa = $drog["drogtidemp"];
$drogNombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $drogIdCliente, $drogIdEmpresa);
$idLoc = DataManager::getCuenta('ctaidloc', 'ctaidcuenta', $drogIdCliente, $drogIdEmpresa);
$drogLocalidad = DataManager::getLocalidad('locnombre', $idLoc);
//*************************************//
//Consulta liquidaciones desde - hasta //
//*************************************//
$liquidaciones = DataManager::getDetalleLiquidaciones(0, $fechaInicio->format("Y-m-d"), $fechaFin->format("Y-m-d"), $drogIdCliente, 'TL');
if (count($liquidaciones)) {
unset($arrayArtLiq);
$arrayArtLiq = array();
unset($arrayTransfer);
$arrayTransfer = array();
foreach ($liquidaciones as $k => $liq){
$liq = $liquidaciones[$k];
$liqId = $liq['liqid'];
$liqTransfer = $liq['liqnrotransfer'];
$liqFecha = $liq['liqfecha'];
$arrayTransfer[]= $liqTransfer;
$liqcant = $liq['liqcant'];
$liqEAN = str_replace("", "", $liq['liqean']);
$ctrlCant = '';
$estado = '';
$cantPedidas = 0;
$cantUnidades = 0;
$bonifArtId = DataManager::getFieldArticulo('artcodbarra', $liqEAN);
$artId = $bonifArtId[0]['artidart'];
if(!empty($artId)){
//DataManager::getDetallePedidoTransfer($liqTransfer);
$_detallestransfer =
DataManager::getTransfersPedido(NULL, NULL, NULL, NULL, NULL, NULL, $liqTransfer);
if ($_detallestransfer) {
unset($arrayArtPedido);
$arrayArtPedido = array();
unset($arrayArtFaltantes);
$arrayArtFaltantes = array();
foreach ($_detallestransfer as $j => $_dettrans){
$_dettrans = $_detallestransfer[$j];
$_ptiddrog = $_dettrans['ptiddrogueria'];
$_ptidart = $_dettrans['ptidart'];
$arrayArtPedido[] = $_ptidart;
$_ptunidades= $_dettrans['ptunidades'];
//Cantidad Pedida del TRANSFER Original
if($_ptidart == $artId){ $cantPedidas += $_ptunidades; }
}
//Si droguería del pedido == a la liquidación
if($_ptiddrog == $drogIdCliente) {
//**************************************//
// #1 UNIDADES PENDIENTE / EXCEDENTES //
//**************************************//
//Si EAN no salió aún en la liquidación
$cantUnidades = $liqcant;
$liqTransfers = DataManager::getDetalleLiquidacionTransfer($liqId, $drogIdCliente, $liqTransfer, $liqEAN);
if($liqTransfers){
foreach ($liqTransfers as $j => $liqTrans){
$liqTrans = $liqTransfers[$j];
$liqtCant = $liqTrans['liqcant'];
//Suma las unidades totales de dicho transfer en liquidaciones
$cantUnidades += $liqtCant;
}
}
// DIFERENCIA entre Unidades LIQUIDADAS y Unidades PEDIDAS
if($cantUnidades != $cantPedidas){
if(!in_array($artId, $arrayArtLiq)){
$arrayArtLiq[] = $artId;
$estado = $cantUnidades - $cantPedidas;
}
}
} /*else { $estado = "#ErrorDrog $_ptiddrog"; }*/
if(!in_array($artId, $arrayArtPedido)){
$arrayArtFaltantes[] = $artId;
}
} /*else { //Si transfer no existe! $estado = "#ErrorNroTrans"; }*/
} else {
$estado = "#ErrorEAN";
}
if($estado){ ?>
<tr>
<th scope="row" align="left"><?php echo $drogIdCliente; ?></th>
<th scope="row" align="left"><?php echo $drogNombre; ?></th>
<th scope="row" align="left"><?php echo $drogLocalidad; ?></th>
<td scope="row" align="left"><?php echo $liqTransfer; ?></td>
<td scope="row" align="left"><?php echo $artId; ?></td>
<td scope="row" align="left"><?php echo dac_invertirFecha( $liqFecha ); ?></td>
<td scope="row" align="left"><?php echo $estado; ?></td>
</tr>
<?php
}
if(count($arrayArtFaltantes)){
if(in_array($artId, $arrayArtFaltantes)){ ?>
<tr>
<th scope="row" align="left"><?php echo $drogIdCliente; ?></th>
<th scope="row" align="left"><?php echo $drogNombre; ?></th>
<th scope="row" align="left"><?php echo $drogLocalidad; ?></th>
<td scope="row" align="left"><?php echo $liqTransfer; ?></td>
<td scope="row" align="left"><?php echo $artId; ?></td>
<td scope="row" align="left"><?php echo dac_invertirFecha( $liqFecha ); ?></td>
<td scope="row" align="left"><?php echo "Faltante"; ?></td>
</tr>
<?php
}
}
}
}
unset($arrayTransfersSinLiquidar);
$arrayTransfersSinLiquidar = array();
$transfers = DataManager::getTransfersPedido(0, $fechaInicio->format("Y-m-d H:m:s"), $fechaFin->format("Y-m-d H:m:s"), $drogIdCliente);
//getTransfers2(0, $fechaInicio->format("Y-m-d H:m:s"), $fechaFin->format("Y-m-d H:m:s"), $drogIdCliente, NULL);
if($transfers){
foreach ($transfers as $k => $transf){
$transf = $transfers[$k];
$nroPedido = $transf['ptidpedido'];
$fechaPedido= $transf['ptfechapedido'];
if(!in_array($nroPedido, $arrayTransfer)){
if(!in_array($nroPedido, $arrayTransfersSinLiquidar)){
$arrayTransfersSinLiquidar[] = $nroPedido; ?>
<tr>
<th scope="row" align="left"><?php echo $drogIdCliente; ?></th>
<th scope="row" align="left"><?php echo $drogNombre; ?></th>
<th scope="row" align="left"><?php echo $drogLocalidad; ?></th>
<td scope="row" align="left"><?php echo $nroPedido; ?></td>
<td scope="row" align="left"></td>
<td scope="row" align="left"><?php echo $fechaPedido; ?></td>
<td scope="row" align="left"><?php echo "Sin Liquidar"; ?></td>
</tr> <?php
}
}
}
}
} ?>
</table> <?php
} ?>
</body>
</html>
<file_sep>/transfer/gestion/abmtransferdrog/editar.php
<?php
session_start();
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_drogid = empty($_REQUEST['drogid']) ? 0 : $_REQUEST['drogid'];
if(empty($_REQUEST['fecha_abm'])){
$_mes = date("m"); $_anio = date("Y");
} else {
list($_mes, $_anio) = explode('-', str_replace('/', '-', $_REQUEST['fecha_abm']));
}
//Consultar el estado del primer registro de la fecha y droguería, para saber si está activo o inactivo
$_ABMestado = DataManager::getDetalleAbm($_mes, $_anio, $_drogid, 'TD');
if ($_ABMestado) {
$_contador_filas = count($_ABMestado);
foreach ($_ABMestado as $k => $_ABMest){
$_ABMest = $_ABMestado[$k];
$_activo = $_ABMest['abmactivo'];
break;
}
} else {
$_contador_filas= 2;
$_activo = 0;
}
$_guardar = sprintf( "<img id=\"btsend\" value=\"Guardar Cambios\" title=\"Guardar Cambios\" class=\"icon-save\" onclick=\"javascript:dac_sendForm(%s, 'logica/update.abm.php');\" />", 'fm_abm_edit');
if($_drogid){
$_boton_exportar= sprintf( "<a href=\"logica/exportar.abm.php?mes=%d&anio=%d&drogid=%d\" title=\"exportar abm\"><img class=\"icon-xls-export\"/></a> ", $_mes, $_anio, $_drogid);
$_boton_copy = sprintf( "<img src=\"/pedidos/images/icons/ico-copy.png\" border=\"0\" align=\"absmiddle\" title=\"duplicar abm\" onclick=\"javascript:dac_Duplicarabm(%d, %d, %d, 0)\"/>", $_mes, $_anio, $_drogid);
}
?>
<div class="box_body">
<form id="fm_abm_edit" name="fm_abm_edit" method="POST" >
<fieldset>
<div class="bloque_3">
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<div class="bloque_1">
<label for="drogid">Droguería: </label> <?php
$_droguerias = DataManager::getDrogueria('');
if (count($_droguerias)) { ?>
<select name='drogid' id='drogid' onchange="javascript:dac_chageDrogueria();">
<option value="0" selected>Seleccione Droguería...</option><?php
foreach ($_droguerias as $k => $_drogueria) {
$_drogueria = $_droguerias[$k];
$_Did = $_drogueria["drogtid"];
$_Didcliente = $_drogueria["drogtcliid"];
$_Dnombre = $_drogueria["drogtnombre"];
$_Dlocalidad = $_drogueria["drogtlocalidad"];
if($_drogid == $_Didcliente){ ?>
<option value="<?php echo $_Didcliente; ?>" selected><?php echo $_Didcliente." | ".$_Dnombre." | ".$_Dlocalidad; ?></option> <?php } else { ?>
<option value="<?php echo $_Didcliente; ?>"><?php echo $_Didcliente." | ".$_Dnombre." | ".$_Dlocalidad; ?></option> <?php }
} ?>
</select> <?php
} ?>
</div>
<div class="bloque_2">
<label for="fecha_abm" >Fecha ABM: </label>
<?php echo listar_mes_anio('fecha_abm', $_anio, $_mes, 'dac_chageDrogueria()',''); ?>
</div>
<div class="bloque_3">
<?php echo $_guardar; ?>
<?php echo $_boton_print; ?>
<?php echo $_boton_exportar; ?>
<?php echo $_boton_copy; ?>
</div>
<input id="mes_abm" name="mes_abm" type="text" value="<?php echo $_mes; ?>" hidden/>
<input id="anio_abm" name="anio_abm" type="text" value="<?php echo $_anio; ?>" hidden/>
<input id="drogid_abm" name="drogid_abm" type="text" value="<?php echo $_drogid; ?>" hidden/>
<div style="width:550px; height:350px; overflow-x:auto;">
<table name="tabla_abm" class="tabla_abm" border="0">
<thead>
<?php if(!empty($_drogid)){ ?>
<tr>
<th colspan="2" align="center">Artículo</th>
<th align="center" >% Desc.</th>
<th align="center" >Plazo</th>
<th align="center" >Dif. de Comp. p/ Droguería</th>
<th></th>
</tr>
<?php } ?>
</thead>
<tbody id="lista"> <?php
//***********************************//
//Consulta ABM del mes y su drogueria//
//***********************************//
$_abms = DataManager::getDetalleAbm($_mes, $_anio, $_drogid, 'TD');
if ($_abms) {
foreach ($_abms as $k => $_abm){
$_abm = $_abms[$k];
$_abmID = $_abm['abmid'];
$_abmDrog = $_abm['abmdrogid'];
$_abmArtid = $_abm['abmartid'];
$_artnombre = DataManager::getArticulo('artnombre', $_abmArtid, 1, 1);
$_abmDesc = $_abm['abmdesc'];
$_abmPlazo = $_abm['abmcondpago'];
$_abmDifComp = $_abm['abmdifcomp']; //Diferencia de Compensación
((($k % 2) != 0)? $clase="par" : $clase="impar"); ?>
<tr id="lista_abm<?php echo $k;?>" class="<?php echo $clase;?>">
<td>
<input id="idabm" name="idabm[]" type="text" value="<?php echo $_abmID;?>" hidden/>
<input id="art" name="art[]" type="text" value="<?php echo $_abmArtid;?>" hidden/>
<?php echo $_abmArtid." - ".$_artnombre; ?></td>
<td>
<input id="desc" name="desc[]" type="text" maxlength="2" value="<?php echo $_abmDesc; ?>" align="center" placeholder="%" style="width:80px;"/></td>
<td> <?php
$_plazos = DataManager::getCondicionesDePagoTransfer();
if (count($_plazos)) { ?>
<select id='plazoid' name='plazoid[]'> <?php
foreach ($_plazos as $j => $_plazo) {
$_plazo = $_plazos[$j];
$_condid = $_plazo["condid"];
$_condcodigo = $_plazo["condcodigo"];
$_condnombre = $_plazo["condnombre"];
$_conddias = $_plazo["conddias"];
if($_condid == $_abmPlazo){ ?>
<option value="<?php echo $_condid; ?>" selected><?php echo $_condnombre; ?></option> <?php
} else { ?>
<option value="<?php echo $_condid; ?>"><?php echo $_condnombre; ?></option> <?php
}
} ?>
</select> <?php
} ?>
</td>
<td>
<input id="difcompens" name="difcompens[]" type="text" size="10px" maxlength="5" value="<?php echo $_abmDifComp; ?>" align="center" placeholder="%" onblur="javascript:ControlComa(this.id, this.value);" style="width:80px;"/></td>
<td class="eliminar">
<img class="icon-delete" onclick="javascript:dac_eliminarAmb(<?php echo $k;?>)" />
</td>
</tr> <?php
} //FIN del FOR
} else { ?>
<?php
} ?>
</tbody>
</table>
</div>
</fieldset>
</form>
</div> <!-- END box_body -->
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Artículos</h1>
</div>
<div class="bloque_5">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar..."/>
<input id="txtBuscarEn" type="text" value="tblTablaArt" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<table border="0" id="tblTablaArt" align="center">
<thead>
<tr align="center">
<th>Id</th>
<th>Nombre</th>
<th>EAN</th>
</tr>
</thead>
<tbody> <?php
$_articulos = DataManager::getArticulos($_pag,$_LPP, FALSE, NULL, 1, 1);
if (count($_articulos)) {
foreach ($_articulos as $k => $_articulo) {
$_articulo = $_articulos[$k];
$_idart = $_articulo['artidart'];
$_nombre = $_articulo['artnombre'];
$_artean = $_articulo['artcodbarra'];
((($k % 2) == 0)? $clase="par" : $clase="impar")?>
<tr class="<?php echo $clase;?>" onClick="javascript:dac_CargarArticuloAbm('<?php echo $_idart; ?>', '<?php echo $_nombre; ?>')">
<td><?php echo $_idart; ?></td>
<td><?php echo $_nombre; ?></td>
<td><?php echo $_artean; ?></td>
</tr> <?php
}
} else { ?>
<tr>
<td colspan="3"><?php echo "ACTUALMENTE NO HAY ARTÍCULOS ACTIVOS. Gracias."; ?></td>
</tr> <?php
} ?>
</tbody>
</table>
</div> <!-- Fin listar -->
</div> <!-- FIN box_seccion -->
<script type="text/javascript">
// función para crear un nuevo div de artículo
var nextinput = <?php echo $_contador_filas-1;?>;
function dac_CargarArticuloAbm(idart, nombre){
nextinput++;
(((nextinput % 2) != 0) ? clase="par" : clase="impar");
campo = '<tr id="lista_abm'+nextinput+'" class='+clase+'><td><input id="idabm" name="idabm[]" type="text" hidden="hidden" /><input id="art" name="art[]" type="text" value="'+idart+'" hidden="hidden"/>'+idart+' - '+nombre+'</td><td><input id="desc" name="desc[]" type="text" size="10px" maxlength="2" align="center" placeholder="%" style="width:80px;"/></td>';
campo +='<td><select id="plazoid" name="plazoid[]" style="width:100px; background-color:transparent;">'
campo +='<option value="" selected>Seleccione plazo...</option>';
<?php
$_plazos = DataManager::getCondicionesDePagoTransfer();
if (count($_plazos)) {
foreach ($_plazos as $k => $_plazo) {
$_plazo = $_plazos[$k];
$_condid = $_plazo["condid"];
$_condcodigo = $_plazo["condcodigo"];
$_condnombre = $_plazo["condnombre"];?>
campo += '<option value="<?php echo $_condid; ?>"><?php echo $_condnombre; ?></option>'; <?php
}
} ?>
campo +='</select></td>';
campo +='<td><input id="difcompens'+nextinput+'" name="difcompens[]" type="text" size="10px" maxlength="5" placeholder="%" onblur="javascript:ControlComa(this.id, this.value);" style="width:80px;"/></td><td class="eliminar"><img class="icon-delete" onClick="dac_eliminarAmb('+nextinput+')"/></td></tr>';
$("#lista").append(campo);
}
// función del botón eliminar para quitar un div de artículos
function dac_eliminarAmb(id){
elemento=document.getElementById('lista_abm'+id);
elemento.parentNode.removeChild(elemento);
}
</script>
<script type="text/javascript" src="logica/jquery/jquery.processabm.js"></script>
<script type="text/javascript">
function dac_chageDrogueria(){
var fecha = $('#fecha_abm').val();
var drogueria = $('#drogid').val();
window.location = '/pedidos/transfer/gestion/abmtransferdrog/index.php?fecha_abm='+fecha+'&drogid='+drogueria;
}
function dac_Duplicarabm(mes, anio, drogid, toAll){
if(confirm("Recuerde que se borrará cualquier dato en la fecha donde duplique el ABM. ¿Desea continuar?")){
mes_sig = prompt("Ingrese el mes a donde desea duplicar el ABM. (de 1 a 12)");
if(mes_sig < 1 || mes_sig > 12){
alert("El mes indicado es incorrecto. El duplicado no se realizará. Vuelva a Intentarlo.");
} else {
anio_sig= prompt("Ingrese el año a donde desea duplicar el ABM. (ejemplo 2017)");
if(anio_sig < 2015 || anio_sig > 2025){
alert("El año indicado es incorrecto. El duplicado no se realizará. Vuelva a Intentarlo.");
}else{
if(mes == mes_sig && anio == anio_sig){
alert("Ha intentado duplicar un ABM en la misma fecha. Vuelva a Intentarlo.");
} else {
if(!(mes_sig < 1 || mes_sig > 12) && !(anio_sig < 2015 || anio_sig > 2025)){
$.ajax({
type : 'POST',
url : 'logica/ajax/duplicar.abm.php',
data:{ drogid : drogid,
mes : mes,
mes_sig : mes_sig,
anio : anio,
toAll : toAll,
anio_sig: anio_sig
},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
if (resultado){
$('#box_cargando').css({'display':'none'});
if (resultado == "1"){
//Confirmación
$('#box_confirmacion').css({'display':'block'});
$("#msg_confirmacion").html('Los datos fueron registrados');
} else {
//El pedido No cumple Condiciones
$('#box_error').css({'display':'block'});
$("#msg_error").html(resultado);
}
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error en el proceso");
},
});
}
}
}
}
}
}
</script>
<file_sep>/transfer/gestion/liquidacion/logica/jquery/jquery.script.file.js
$(function(){ $('#importar').click(ImportarLiq); });
/****************************/
// archivo de liquidacion //
/****************************/
function ImportarLiq(){
var drog = document.getElementById("drogid").value;
var fecha_liq = document.getElementById("fecha_liquidacion").value;
var activa = 0;
alert(fecha_liq);
//CONTROL//
//Si liquidación está ACTIVA (liquidada) NO permitirá importar
$('input[name="activa[]"]:text').each(function(){
if($(this).val() == "1"){ activa = 1; }
});
if( (activa == 1) && confirm("ATENCI\u00D3N! Importar\u00E1 una liquidadaci\u00F3n en un mes ya liquidado. Si lo hace, ELIMINAR\u00C1 la informaci\u00F3n existente. Desea Continuar?")){
activa = 0;
}
if (activa == 0) {
var archivos = document.getElementById("file");
var archivo = archivos.files;
var archivos = new FormData();
archivos.append('archivo',archivo);
for(i=0; i<archivo.length; i++){
archivos.append('archivo'+i,archivo[i]); //Añadimos cada archivo al arreglo con un indice direfente
}
archivos.append('drog', drog);
archivos.append('fecha_liq', '01-'+fecha_liq);
$.ajax({
url:'/pedidos/transfer/gestion/liquidacion/logica/importar_liq.php',
type:'POST',
contentType:false,
data:archivos,
processData:false,
cache:false
}).done(function(msg){
alert(msg);
location.reload();
});
} else {
alert("La importaci\u00F3n no fue realizada");
}
}<file_sep>/transfer/gestion/liquidacion/logica/exportar.unidades_pendientes.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_drogid = empty($_REQUEST['drogid'])? 0 : $_REQUEST['drogid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/transfer/gestion/liquidacion/': $_REQUEST['backURL'];
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=Liquidacion-Unidades-Pendientes-".$_drogid.".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos (Liquidacion) .::</TITLE>
<head></head>
<body>
<div id="cuadro-liquidacion">
<div id="muestra_liquidacion">
<table id="tblliquidaciones">
<thead>
<tr>
<th scope="col" colspan="3" align="center">UNIDADES PENDIENTES</th>
</tr>
<tr>
<th scope="col" colspan="3" align="left">Fecha Exportado: <?php echo date("d-m-Y"); ?></th>
</tr>
<tr>
<th colspan="3" align="left"> <?php
$_droguerias = DataManager::getDrogueria('');
if (count($_droguerias)) {
foreach ($_droguerias as $k => $_drogueria) {
$_drogueria = $_droguerias[$k];
$_Did = $_drogueria["drogtid"];
$_Didcliente = $_drogueria["drogtcliid"];
$_Dnombre = $_drogueria["drogtnombre"];
$_Dlocalidad = $_drogueria["drogtlocalidad"];
if($_drogid == $_Didcliente){
echo $_Didcliente." | ".$_Dnombre." | ".$_Dlocalidad;
}
}
} ?>
</th>
</tr>
<tr>
<th scope="col" colspan="3"></th>
</tr>
<tr>
<th scope="col" height="18">Fecha</th>
<th scope="col" >Nro. Transfer</th>
<th scope="col" >Cliente</th>
</tr>
</thead>
<tbody id="lista_liquidacion">
<?php
$_transfers_liquidados = DataManager::getTransfersLiquidados(NULL, 'LP', $_drogid);
if ($_transfers_liquidados) {
for( $k=0; $k < count($_transfers_liquidados); $k++ ){
$_detalle = $_transfers_liquidados[$k];
$_fecha = $_detalle["ptfechapedido"];
$_nropedido = $_detalle["ptidpedido"];
$_nombre = $_detalle["ptclirs"];
((($k % 2) != 0)? $clase="par" : $clase="impar");
?>
<tr id="lista_liquidacion<?php echo $k;?>" class="<?php echo $clase;?>">
<td align="center"><?php echo $_fecha; ?></td>
<td align="center"><?php echo $_nropedido; ?></td>
<td align="center"><?php echo $_nombre; ?></td>
</tr>
<?php
}
} else { ?>
<tr>
<td scope="colgroup" colspan="3" height="25" align="center">No hay Transfer con UNIDADES PENDIENTES</td>
</tr> <?php
} ?>
</tbody>
</table>
<div hidden="hidden"><button id="btnExport" hidden="hidden"></button></div>
</div> <!-- FIN muestra_bonif -->
</div> <!-- FIN liquidacion -->
</body>
</html>
<file_sep>/contactos/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$_origen = empty($_REQUEST['origen']) ? 0 : $_REQUEST['origen'];
$_origenid = empty($_REQUEST['origenid']) ? 0 : $_REQUEST['origenid'];
$_ctoid = empty($_REQUEST['ctoid']) ? 0 : $_REQUEST['ctoid'];
if ($_ctoid) {
$_action = "Guardar";
$_proveedor = DataManager::newObjectOfClass('TContacto', $_ctoid);
$_origen = $_proveedor->__get('Origen');
$_sector = $_proveedor->__get('Sector');
$_puesto = $_proveedor->__get('Puesto');
$_nombre = $_proveedor->__get('Nombre');
$_apellido = $_proveedor->__get('Apellido');
$_genero = $_proveedor->__get('Genero');
$_telefono = $_proveedor->__get('Telefono');
$_interno = $_proveedor->__get('Interno');
$_correo = $_proveedor->__get('Email');
} else {
$_action = "Crear";
//$_origen = "";
$_sector = "";
$_puesto = "";
$_nombre = "";
$_apellido = "";
$_genero = "";
$_telefono = "";
$_interno = "";
$_correo = "";
}
$_button = sprintf("<input type=\"submit\" id=\"btsend\" name=\"_accion\" value=\"%s\"/>", $_action);
?>
<!DOCTYPE html>
<html lang="es">
<body class="body-contact">
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
<script language="JavaScript" type="text/javascript" src="/pedidos/contactos/logica/jquery/jquery.enviar.js"></script>
</head>
<form method="POST">
<input name="ctoid" id="ctoid" type="text" value="<?php echo $_ctoid; ?>" hidden/>
<input name="origenid" id="origenid" type="text" value="<?php echo $_origenid; ?>" hidden/>
<div class="bloque_5">
<label for="ctoorigen">Origen</label>
<select id="ctoorigen" name="ctoorigen"/>
<option></option>
<option value="<?php echo $_origen; ?>" selected><?php echo substr($_origen,1); ?></option>
</select>
</div>
<div class="bloque_5">
<label for="ctosector">Sector / Departamento</label>
<select id="ctosector" name="ctosector"/>
<option></option> <?php
$_sectores = DataManager::getSectores(1);
if($_sectores){
foreach ($_sectores as $k => $_sect) {
$_sectid = $_sect['sectid'];
$_sectnombre = $_sect['sectnombre'];
if($_sectid == $_sector){ ?>
<option value="<?php echo $_sectid;?>" selected><?php echo $_sectnombre;?></option><?php
} else {?>
<option value="<?php echo $_sectid;?>"><?php echo $_sectnombre;?></option><?php
}
}
} else { ?>
<option selected>Error Sectores</option> <?php
} ?>
</select>
</div>
<div class="bloque_5">
<label for="ctopuesto">Puesto</label>
<select id="ctopuesto" name="ctopuesto"/>
<option></option> <?php
$_puestos = DataManager::getPuestos(1);
if($_puestos){
foreach ($_puestos as $k => $_pto) {
$_ptoid = $_pto['ptoid'];
$_ptonombre = $_pto['ptonombre'];
if($_ptoid == $_puesto){ ?>
<option value="<?php echo $_ptoid;?>" selected><?php echo $_ptonombre;?></option><?php
} else {?>
<option value="<?php echo $_ptoid;?>"><?php echo $_ptonombre;?></option><?php
}
}
} else { ?>
<option selected>Error Puestos</option> <?php
} ?>
</select>
</div>
<div class="bloque_5">
<label>Género</label>
<select id="ctogenero" name="ctogenero"/>
<?php
if ($_genero == "F"){ ?>
<option></option>
<option value="<?php echo $_genero; ?>" selected><?php echo $_genero; ?></option>
<option value="M">M</option> <?php
} else {
if ($_genero == "M"){ ?>
<option></option>
<option value="F">F</option>
<option value="<?php echo $_genero; ?>" selected><?php echo $_genero; ?></option> <?php
} else { ?>
<option selected></option>
<option value="F">F</option>
<option value="M">M</option> <?php
}
} ?>
</select>
</div>
<div class="bloque_5">
<input name="ctonombre" id="ctonombre" type="text" placeholder="Nombre" maxlength="50" value="<?php echo $_nombre;?>"/>
</div>
<div class="bloque_5">
<input name="ctoapellido" id="ctoapellido" type="text" placeholder="Apellido" maxlength="50" value="<?php echo $_apellido;?>"/>
</div>
<div class="bloque_5">
<input name="ctotelefono" id="ctotelefono" type="text" placeholder="Teléfono" maxlength="20" value="<?php echo $_telefono;?>"/>
</div>
<div class="bloque_5">
<input name="ctointerno" id="ctointerno" type="text" placeholder="Interno" maxlength="10" value="<?php echo $_interno; ?>"/>
</div>
<div class="bloque_1">
<input name="ctocorreo" id="ctocorreo" type="text" placeholder="Correo" maxlength="50" value="<?php echo $_correo;?>"/>
</div>
<div class="bloque_1">
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<div class="bloque_5">
<?php echo $_button; ?>
</div>
</form>
</body>
</html><file_sep>/transfer/gestion/liquidacion/logica/update.liquidacion.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_mes = $_POST['mes'];
$_anio = $_POST['anio'];
$_drogid = $_POST['drogid'];
$_conciliar = $_POST['conciliar'];
//Arrays
$_idliquid = explode("|", substr($_POST['idliquid'], 1));
$_fecha = explode("|", substr($_POST['fecha'], 1));
$_transfer = explode("|", substr($_POST['transfer'], 1));
$_fechafact = explode("|", substr($_POST['fechafact'], 1));
$_desc = explode("|", substr($_POST['desc'], 1));
$_nrofact = explode("|", substr($_POST['nrofact'], 1));
$_ean = explode("|", substr($_POST['ean'], 1));
$_idart = explode("|", substr($_POST['idart'], 1));
$_cant = explode("|", substr($_POST['cant'], 1));
$_unitario = explode("|", substr($_POST['unitario'], 1));
$_importe = explode("|", substr($_POST['importe'], 1));
$_estado = explode("|", substr($_POST['estado'], 1));
/*****************/
//Control de Datos
/*****************/
if(empty($_drogid) || $_drogid==0){
echo "Debe seleccionar una droguería"; exit;
}
for($i=0; $i<count($_idliquid); $i++){
if(empty($_transfer[$i])){
echo "Error en número de transfer en la fila ".($i+1); exit;
}
if(empty($_fechafact[$i])){
echo "Error en fecha de factura en la fila ".($i+1); exit;
}
if(empty($_nrofact[$i])){
echo "Error en número de factura en la fila ".($i+1); exit;
}
if(empty($_ean[$i]) || !is_numeric($_ean[$i])){
echo "Error de número EAN en la fila ".($i+1); exit;
}
if(empty($_cant[$i]) || !is_numeric($_cant[$i])){
echo "Error de cantidad en la fila ".($i+1); exit;
}
if(empty($_unitario[$i]) || !is_numeric($_unitario[$i])){
echo "Error de PSL Unitario en la fila ".($i+1); exit;
}
if(empty($_desc[$i]) || !is_numeric($_desc[$i])){
echo "Error de descuento en la fila ".($i+1)." (quite el simbolo '%')"; exit;
}
if(empty($_importe[$i]) || !is_numeric($_importe[$i])){
echo "Error de Importe NC en la fila ".($i+1); exit;
}
}
//**********************//
// Edito Liquidación //
//**********************//
for($i=0; $i<count($_idliquid); $i++){
if (!empty($_transfer[$i])){
//**********************************//
// Registro Estado del Transfer // LT (Liquidado Total) | LP (Liquidado PArcial) | LE (Liquidado Excedente)
//**********************************//
//Consulto transfer para que devuelva idtransfers y editar estado de artículo.
$_ptransfers = DataManager::getTransfersPedido(NULL, NULL, NULL, NULL, NULL, NULL, $_transfer[$i]); //DataManager::getDetallePedidoTransfer($_transfer[$i]);
if ($_ptransfers) {
foreach ($_ptransfers as $j => $_pt){
$_pt = $_ptransfers[$j];
$_ptID = $_pt['ptid'];
$_ptidart = $_pt['ptidart'];
if ($_idart[$i] == $_ptidart){
//EDITA ESTADO DEL ARTÍCULO TRANSFER
$_ptobject = DataManager::newObjectOfClass('TPedidostransfer', $_ptID);
$_ptobject->__set('Liquidado', $_estado[$i]);
$ID = DataManager::updateSimpleObject($_ptobject);
}
}
} else {
//echo "El pedido transfer ".$_transfer[$i]." no se encuentra o es inexistente"; exit;
}
//EDITA ESTADO DEL ARTÍCULO LIQUIDADO
$_liqobject = DataManager::newObjectOfClass('TLiquidacion', $_idliquid[$i]);
$_liqobject->__set('Activa', 1);
$ID = DataManager::updateSimpleObject($_liqobject);
} else {
echo "Ocurrió un error al querer actualizar el estado de transfers. Verifique el transfer ".$_transfer[$i]." y vuelva a intentarlo."; exit;
}
}
echo "1";
//borro los registros que están en la ddbb y ya no están en la tabla
/*$_liquidaciones = DataManager::getDetalleLiquidacion($_mes, $_anio, $_drogid, 'TL');
if ($_liquidaciones) {
foreach ($_liquidaciones as $k => $_liquid){
$_liquid = $_liquidaciones[$k];
$_liquidID = $_liquid['liqid'];
//busco si hay algún artículo que no esté en la tabla
$encontrado = 0; $i = 0;
while(($i<count($_idliquid)) && ($encontrado == 0)){
if(($_liquidID == $_idliquid[$i])){ $encontrado = 1; }
$i++;
}
if ($encontrado == 0){ //borrar de la ddbb $_liquidID
$_liquidobject = DataManager::newObjectOfClass('TLiquidacion', $_liquidID);
$_liquidobject->__set('ID', $_liquidID );
$ID = DataManager::deleteSimpleObject($_liquidobject);
}
}
}*/
//el siguiente control no se hace, porque puede haber de un mismo transfer liquidado el mismo mes, pero separados por una fecha de factura diferente.
//**********************************//
// Controlo para conciliar // //Controlo Que no se repita en un mismo Nro transfer un número EAN
//**********************************//
/*for($i = 0; $i < count($_idliquid); $i++){
$cont = 0;
for($j = 0; $j < count($_idliquid); $j++){
if($_transfer[$i] == $_transfer[$j]){
if($_ean[$i] == $_ean[$j]){
$cont = $cont + 1;
}
}
}
if ($cont > 1){
echo "Hay códigos EAN repetidos en la liquidación, Verifique."; exit;
}
}*/
//REGISTRO SU UN ARTÍCULO SE ACEPTO COMO LT LIQUIDADO TOTAL, para que quede como liqactiva = 1 y así no volver a modificar o consultar por este???
//Recorro nuevamente cada registro para grabar y/o insertar los nuevos registros de liquidacion
//update para los que tengan idliquid e insert para los que no
/*for($i=0; $i<count($_idliquid); $i++){
$_liquidid = empty($_idliquid[$i]) ? 0 : $_idliquid[$i];
$_liquidobject = ($_liquidid) ? DataManager::newObjectOfClass('TLiquidacion', $_liquidid) : DataManager::newObjectOfClass('TLiquidacion');
$_liquidobject->__set('Drogueria', $_drogid);
$_liquidobject->__set('Fecha', $_fecha[$i]);
$_liquidobject->__set('Transfer', $_transfer[$i]);
$_liquidobject->__set('FechaFact', dac_invertirFecha( $_fechafact[$i] ) );
$_liquidobject->__set('NroFact', $_nrofact[$i]);
$_liquidobject->__set('EAN', $_ean[$i]);
$_liquidobject->__set('Cantidad', $_cant[$i]);
$_liquidobject->__set('Unitario', $_unitario[$i]);
$_liquidobject->__set('Descuento', $_desc[$i]);
$_liquidobject->__set('ImporteNC', $_importe[$i]);
$_liquidobject->__set('ImporteNC', $_importe[$i]);
if($_conciliar == 1){ $_liquidobject->__set('Activa', 1); }
if ($_liquidid) { //Modifica liquidacion
$ID = DataManager::updateSimpleObject($_liquidobject);
} else { //La liquidacion es nueva
$_liquidobject->__set('ID', $_liquidobject->__newID());
$ID = DataManager::insertSimpleObject($_liquidobject);
}
}*/
?><file_sep>/proveedores/fechaspago/logica/ajax/update.pagos.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$fecha = (isset($_POST['fecha'])) ? dac_invertirFecha($_POST['fecha']) : NULL ;
//Arrays
$idFact = explode("-", substr($_POST['idfact'], 1));
$empresa = explode("-", substr($_POST['empresa'], 1));
$idProv = explode("-", substr($_POST['idprov'], 1));
$nombre = explode("-", substr($_POST['nombre'], 1));
$plazo = explode("-", substr($_POST['plazo'], 1));
$fvto = explode("-", substr($_POST['fechavto'], 1));
$tipo = explode("-", substr($_POST['tipo'], 1));
$factNro = explode("-", substr($_POST['factnro'], 1));
$fcbte = explode("-", substr($_POST['fechacbte'], 1));
$saldo = explode("-", substr($_POST['saldo'], 1));
$observacion= explode("-", substr($_POST['observacion'], 1));
/*
for($i=0; $i < count($fcbte); $i=$i+3){
$fechaCbte[] = $fcbte[$i]."-".$fcbte[$i+1]."-".$fcbte[$i+2];
$fechaVto[] = $fvto[$i]."-".$fvto[$i+1]."-".$fvto[$i+2];
}*/
if(empty($fecha)){
echo "Error en la fecha seleccionada."; exit;
}
//Recorre las facturas de la fecha actual
for($i=0; $i < count($idFact); $i++){
//Controlar que no haya duplicados
$cont = 0;
for($j=0; $j < count($idFact); $j++){
if($empresa[$i] == $empresa[$j] && $idProv[$i] == $idProv[$j] && $tipo[$i] == $tipo[$j] && $factNro[$i] == $factNro[$j]){
$cont++;
if($cont > 1) {
echo "El siguiente registro está repetido: </br> Emp: ".$empresa[$i]." Código: ".$idProv[$i]." Tipo: ".$tipo[$i]." Nro: ".$factNro[$i]; exit;
}
}
}
//Controlar que la factura no exista cargada en otras fechas diferente a la actual
$facturas = DataManager::getFacturasProveedor($empresa[$i], NULL, NULL, $tipo[$i], $factNro[$i], $idProv[$i]);
if($facturas) {
foreach ($facturas as $k => $fact) {
$factFechaCbte = $fact['factfechapago'];
if($factFechaCbte != $fecha && $factFechaCbte != '2001-01-01'){
echo "El comprobante $tipo[$i] - $factNro[$i] del proveedor $idProv[$i] ya existe cargado en la fecha ".dac_invertirFecha($factFechaCbte); exit;
}
}
}
}
//Busco registros ya guardados en ésta fecha y pongo en cero si no están en el array (si fueron eliminados)
$facturasPago = DataManager::getFacturasProveedor(NULL, 1, $fecha);
if($facturasPago) {
foreach ($facturasPago as $k => $factPago) {
$idFactura = $factPago['factid'];
$activa = $factPago['factactiva'];
//si el idfact NO aparece en el array, se hace un UPDATE para ponerlo a cero
if (!in_array($idFactura, $idFact)) {
$factObject = DataManager::newObjectOfClass('TFacturaProv', $idFactura);
$factObject->__set('Pago' , '2001-01-01');
$factObject->__set('Observacion', ' ');
$factObject->__set('Activa' , 0);
$ID = DataManager::updateSimpleObject($factObject);
}
}
}
//----------------------------------
// Edicion de las fact como pagos
for($i=0; $i < count($idFact); $i++){
if ($idFact[$i]){
$factObject = DataManager::newObjectOfClass('TFacturaProv', $idFact[$i]);
$factObject->__set('Pago' , $fecha);
$factObject->__set('Observacion', $observacion[$i]);
$factObject->__set('Activa' , 1);
$ID = DataManager::updateSimpleObject($factObject);
}/* else {
echo "Error al ingresar los datos de las facturas. Verifique el resultado."; exit;
}*/
}
echo "1"; exit;
?><file_sep>/localidades/logica/jquery/jqueryUsrFooter.js
$(document).ready(function() {
"use strict";
var idLoc = $('#idLoc').val();
var idProv = $('#provincia').val();
$.ajax({
type : 'POST',
cache : false,
url : 'logica/ajax/getCuentas.php',
data : { idLoc : idLoc,
idProv : idProv},
beforeSend : function () {
$('#box_confirmacion').css({'display':'none'});
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
$('#box_cargando').css({'display':'none'});
if (resultado){
document.getElementById('tablacuenta').innerHTML = resultado;
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al intentar consultar los registros.");
},
});
});<file_sep>/includes/menu.inc.php
<script type="text/javascript">
$(document).ready(main);
var contador = 1;
function main() {
$('.menu_bar').click(function(){
// $('nav').toggle();
$('.burguer').toggleClass('cruz');
if(contador == 1){
$('nav').animate({
left: '0'
});
contador = 0;
} else {
$('nav').animate({
left: '-100%'
});
contador = 1;
}
});
};
</script>
<style>
.content-burguer {
/*position: absolute;*/
float: left;
width: 30px;
height: 30px;
background-color: transparent;
/* Flex-box */
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.burguer {
position: relative;
height: 15%;
width: 100%;
background: white;
/* */
transition: 1s;
}
.burguer:after,
.burguer:before,
.hamburguesa {
position: absolute;
width: 100%;
content: ''; /*se coloca para que aparezcan otras líneas de styles */
background: white;
}
.burguer:after {
top: 10px;
height: 100%;
}
.burguer:before{
top: -10px;
height: 100%;
}
.cruz {
transition: 1s;
transform: rotateZ(45deg);
}
</style>
<?php
$_section = empty($_section) ? "inicio" : $_section;
$_subsection = empty($_subsection) ? "inicio" : $_subsection;
?>
<?php if ($_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="V" || $_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="M" || $_SESSION["_usrrol"]=="P"){?>
<header>
<div class="menu_bar">
<a href="#" class="bt-menu">
<div class="content-burguer">
<div class="burguer">
</div>
</div>
<script>
/*$(document).on('ready', function()
$('.content-burguer').on('click', function()
$('.burguer').toggleClass('cruz');
})
})*/
</script>
Menu
</a>
</div>
<div id="navegador" align="center">
<nav>
<ul>
<li>
<a href="/pedidos/index.php" title="Home">
<img class="icon-home"/>
</a>
</li>
<?php
//---------------------//
// USUARIOS INTERNOS //
if ($_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="V" || $_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="M"){ ?>
<?php
if ($_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="M"){ ?>
<li class="<?php echo ($_section=="articulos") ? "current_menu" : "boton_menu";?>">
<a href="/pedidos/articulos/">ARTÍCULOS</a>
</li>
<?php }?>
<li class="<?php echo ($_section=="pedidos") ? "current_menu" : "boton_menu";?>">
<a href="#">PEDIDOS</a>
<ul>
<?php if ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="M" || $_SESSION["_usrrol"]=="V"){ ?>
<li class="<?php echo ($_subsection=="nuevo_pedido") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/pedidos/editar.php" title="Realizar un nuevo pedido">
Nuevo Pedido </a>
</li>
<?php }?>
<li class="<?php echo ($_subsection=="pendientes") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/pedidos/pendientes/" title="Ver pedidos pendientes">
Seguimiento de Pedidos</a>
</li>
<li class="<?php echo ($_subsection=="prefacturados") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/pedidos/prefacturados/" title="Ver pedidos prefacturados">
Pedidos Pre Facturados </a>
</li>
<li class="<?php echo ($_subsection=="facturacion") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/cuentas/facturacion/" title="Facturación de Cuentas">
Facturación </a>
</li>
<li class="<?php echo ($_subsection=="mis_propuestas") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/pedidos/propuestas/" title="Ver propuestas realizadas">
Propuestas </a>
</li>
<li class="<?php echo ($_subsection=="nuevo_transfer") ? "current_submenu" : "current_menu"; ?>">
<a href="/pedidos/transfer/editar.php" title="Realizar un pedido transfer">
Nuevo Transfer </a>
</li>
<li class="<?php echo ($_subsection=="mis_transfers") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/transfer/" title="Ver transfers pendientes">
Transfers Pendientes </a>
</li>
<li class="<?php echo ($_subsection=="enviados") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/transfer/enviados/" title="Ver transfers enviados">
Transfers Enviados </a>
</li>
</ul>
</li>
<li class="<?php echo ($_section=="cuentas") ? "current_menu" : "boton_menu";?>">
<a href="#">CUENTAS</a>
<ul>
<?php if ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="M"){ ?>
<li class="<?php echo ($_subsection=="listar_cadenas") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/cadenas/" title="Cadenas">
Cadenas </a>
</li>
<?php } ?>
<?php if ($_SESSION["_usrrol"]=="A" ){ ?>
<li class="<?php echo ($_subsection=="lista_droguerias") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/droguerias">
Droguerías</a>
</li>
<li class="<?php echo ($_subsection=="lista_relevamientos") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/relevamiento/">
Relevamientos</a>
</li>
<?php } ?>
<li class="<?php echo ($_subsection=="listar_cuentas") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/cuentas/" title="Cuentas">
Cuentas </a>
</li>
<li class="<?php echo ($_subsection=="editar_cuenta") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/cuentas/editar.php" title="Nueva Cuenta">
Nueva Cuenta</a>
</li>
</ul>
</li>
<li class="<?php echo ($_section=="condiciones") ? "current_menu" : "boton_menu";?>">
<a href="#">CONDICIONES</a>
<ul>
<li class="<?php echo ($_subsection=="condiciones_comerciales") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/condicion/" title="Condiciones Comerciales">
Condiciones Comerciales </a>
</li>
<?php if ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]=="M"){ ?>
<li class="<?php echo ($_subsection=="condiciones_pago") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/condicionpago/">
Condiciones de Pago</a>
</li>
<?php } ?>
<?php if ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="M"){ ?>
<li class="<?php echo ($_subsection=="listas_precios") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/listas/">Listas de precios</a>
</li>
<?php } ?>
</ul>
</li>
<li class="<?php echo ($_section=="informes") ? "current_menu" : "boton_menu";?>">
<a href="/pedidos/informes/" title="Informes">
INFORMES </a>
</li>
<li class="<?php echo ($_section=="planificar") ? "current_menu" : "boton_menu";?>">
<a href="#">
PLANIFICAR </a>
<ul>
<li class="<?php echo ($_subsection=="planificar") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/planificacion/" title="Planificar visitas">
Planificar </a>
</li>
<li class="<?php echo ($_subsection=="lista_zonas") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/zonas">
Zonas de cuentas</a>
</li>
<?php if ($_SESSION["_usrrol"]=="A" || $_SESSION["_usrrol"]=="M"){ ?>
<li class="<?php echo ($_subsection=="nueva_zona") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/zonas/editar.php">
Nueva Zona de Cuenta</a>
</li>
<?php } ?>
<?php if ($_SESSION["_usrrol"]=="A" ){ ?>
<li class="<?php echo ($_subsection=="lista_acciones") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/acciones/">Acciones</a>
</li>
<?php } ?>
</ul>
</li>
<li class="<?php echo ($_section=="cuentas_corrientes") ? "current_menu" : "boton_menu";?>">
<a href="#">
CUENTAS CORRIENTES</a>
<ul>
<li class="<?php echo ($_subsection=="rendicion") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/rendicion/" title="Rendición de cobranzas">
Rendición </a>
</li>
</ul>
</li>
<?php /*if ($_SESSION["_usrrol"]== "A" || $_SESSION["_usrrol"]== "G" || $_SESSION["_usrrol"]== "M"){ ?>
<li class="<?php echo ($_section=="transfer") ? "current_menu" : "boton_menu";?>">
<a href="#">TRANSFER</a>
<ul>
<li class="<?php echo ($_subsection=="abm_transfer") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/transfer/gestion/abmtransfer/" title="ABM Transfer">
ABM </a>
</li>
<li class="<?php echo ($_subsection=="abm_transfer_drog") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/transfer/gestion/abmtransferdrog/" title="ABM Transfer">
ABM Droguerías</a>
</li>
<li class="<?php echo ($_subsection=="liquidacion_transfer") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/transfer/gestion/liquidacion/" title="Liquidación Transfer">
Liquidación </a>
</li>
<li class="<?php echo ($_subsection=="liquidacion_transfer_drog") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/transfer/gestion/liquidaciondrog/" title="Liquidación Transfer">
Liquidación Droguertía</a>
</li>
</ul>
</li>
<?php } */ ?>
<?php /*if ($_SESSION["_usrrol"]== "A" || $_SESSION["_usrrol"]== "V" || $_SESSION["_usrrol"]== "G"){?>
<li class="<?php echo ($_section=="pdv") ? "current_menu" : "boton_menu";?>">
<a>PDV</a>
<ul>
<li class="<?php echo ($_subsection=="pdv_infycam") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/pdv/infycam/" title="Informes y Campañas (propios)">
Informes y Campañas (propios)</a>
</li>
<li class="<?php echo ($_subsection=="pdv_acc_comp") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/pdv/accionescompe/" title="Acciones Competencia">
Acciones Competencia </a>
</li>
</ul>
</li>
<?php } */?>
<?php if ($_SESSION["_usrrol"]== "A" || $_SESSION["_usrrol"]== "M"){?>
<li class="<?php echo ($_section=="proveedores") ? "current_menu" : "boton_menu";?>">
<a href="#">PROVEEDORES</a>
<ul>
<li class="<?php echo ($_subsection=="listado") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/proveedores/" title="Listado">
Listado</a>
</li>
<li class="<?php echo ($_subsection=="fechaspago") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/proveedores/fechaspago/" title="Fechas de Pago">
Fechas de Pago </a>
</li>
</ul>
</li>
<?php }?>
<?php if ($_SESSION["_usrrol"]=="A"){?>
<li class="<?php echo ($_section=="juegos") ? "current_menu" : "boton_menu";?>">
<a href="/pedidos/juegos/" title="Juegos">
<img class="icon-game"/>
</a>
</li>
<li class="<?php echo ($_section=="soporte") ? "current_menu" : "boton_menu";?>">
<a href="/pedidos/soporte/tickets/" title="Soporte">
<img class="icon-support"/>
</a>
</li>
<?php }?>
<li class="<?php echo ($_section=="agenda") ? "current_menu" : "boton_menu";?>">
<a href="/pedidos/agenda/" title="Agenda">
<img class="icon-calendar-menu"/>
</a>
</li>
<li class="<?php echo ($_section=="webmail") ? "current_menu" : "boton_menu";?>">
<a href="https://webmail.ferozo.com/appsuite/" title="Webmail" target="_blank">
<img class="icon-mail-menu"/>
</a>
</li>
<li class="<?php echo ($_section=="ayuda") ? "current_menu" : "boton_menu";?>">
<a href="/pedidos/ayuda/" title="Ayuda">
<img class="icon-help"/>
</a>
</li>
<?php }?>
<?php
// MENÚ USUARIOS PROVEEDORES //
if ($_SESSION["_usrrol"]=="P") { ?>
<li class="<?php echo ($_section=="provpagos") ? "current_menu" : "boton_menu";?>">
<a href="#">
PAGOS</a>
<ul>
<li class="<?php echo ($_subsection=="provfechapago") ? "current_submenu" : "current_menu";?>">
<a href="/pedidos/proveedores/pagos/solicitarfecha/" title="Solicitar Fecha de Pago">
Solicitar Fecha de Pago</a>
</li>
</ul>
</li>
<?php
}
//******************************// ?>
<?php if (!empty($_SESSION['_usrname'])) { ?>
<li>
<a href="/pedidos/login/logout.php" title="Logout">
<img class="icon-logout"/>
</a>
</li>
<?php }?>
</ul>
</nav>
</div>
</header>
<?php } ?><file_sep>/inicio/logica/reactivar.cliente.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
$_idcliente= (isset($_POST['idcliente'])) ? $_POST['idcliente'] : null;
$_ruteo = (isset($_POST['ruteo'])) ? $_POST['ruteo'] : null;
$_rs = (isset($_POST['rs'])) ? $_POST['rs'] : null;
$_email = (isset($_POST['email'])) ? strtolower($_POST['email']) : null;
/***************************************************/
/* Uso datos de SESSION del Vendedor para el correo*/
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = $_SESSION["_usremail"];
$mail->FromName = "Vendedor: ".$_SESSION["_usrname"];
$mail->Subject = "Solicitud de REACTIVACIÓN de Cliente.";
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
$_total= '
<html>
<head>
<title>Notificación de Solicitud</title>
<style type="text/css"> <!--
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 350px;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 0px;
}
.saludo {
width: 250px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
} -->
</style>
</head>
<body>
<table width="750" border="0" align="center">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<p>
<div class="texto" style="width:500px">
<font face="Geneva, Arial, Helvetica, sans-serif" size="2">
Estimad@, se envían los datos de <strong>SOLICITUD DE REACTIVACIÓN</strong> del siguiente cliente:
</font>
</div>
</p>
<div class="texto" align="center">
<p>
<table width="500px" style="border:2px solid #597D92">
<tr>
<th colspan="2" style="border:2px solid #597D92">
Zonas: '.$_SESSION["_usrzonas"].'<br />
Vendedor: '.$_SESSION["_usrname"].'<br />
'.$_SESSION["_usremail"].'<br />
</th>
</tr>
<tr>
<th rowspan="2" align="right" width="450px" style="border:2px solid #597D92">
Nro. Cliente:<br />
Razón Social:<br />
Rutéo:<br />
E-mail:
</th>
<th rowspan="2" align="left" width="450px" style="border:2px solid #597D92">
'.$_idcliente.'<br />
'.$_rs.'<br />
'.$_ruteo.'<br />
'.$_email.'
</th>
</tr>
</table>
</p>
<p>
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con el Administrador de la Web del Sector de Sistemas al 4555-3366 de lunes a viernes de 10 a 17.00 horas o por email escribiendo a: <a href="mailto:<EMAIL>"><EMAIL></a>
</font>
</p>
</div>
</td>
</tr>
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo">Los Saludamos atentamente,<br />
Dpto. de Sistemas - NEO FARMA S.A.
</div>
</td>
</tr>
<tr align="right">
<td valign="top">'.$pie.'</td>
</tr>
</table>
</body>
</html>
';
$mail->msgHTML($_total);
$mail->AddAddress("<EMAIL>");
$mail->AddAddress("<EMAIL>");
$mail->AddAddress("<EMAIL>");
$mail->AddAddress($_SESSION["_usremail"]);
if(!$mail->Send()) {
echo 'Fallo en el envío';
} else {
//*******************************************************************
//Grabo datos en cambios_cliente de pedido de reactivación
$_cambioscliobject = DataManager::newObjectOfClass('TCambiosCliente');
$_cambioscliobject->__set('ID', $_cambioscliobject->__newID());
$_cambioscliobject->__set('FechaSolicitud', date("Y-m-d"));
$_cambioscliobject->__set('Usuario', $_SESSION["_usrid"]);
$_cambioscliobject->__set('Cliente', $_idcliente);
$_cambioscliobject->__set('Estado', "REACTIVACION");
$ID = DataManager::insertSimpleObject($_cambioscliobject);
//*******************************************************************
$_goURL = "/pedidos/index.php"; //?sms=4
header('Location:'.$_goURL);
}
exit;
?>
<file_sep>/soporte/motivos/logica/update.motivo.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G"){
echo "SU SESIÓN HA EXPIRADO."; exit;
}
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/soporte/motivos/lista.php': $_REQUEST['backURL'];
$sector = empty($_POST['sector']) ? 0 : $_POST['sector'];
$responsable= empty($_POST['responsable']) ? 0 : $_POST['responsable'];
$motid = empty($_POST['motid']) ? 0 : $_POST['motid'];
$motivo = empty($_POST['motivo']) ? 0 : $_POST['motivo'];
if (empty($sector)) { echo "Seleccione un sector."; exit; }
if (empty($responsable)) { echo "Seleccione un responsable."; exit; }
if (empty($motivo)) { echo "Indique un motivo."; exit; }
$object = ($motid) ? DataManager::newObjectOfClass('TTicketMotivo', $motid) : DataManager::newObjectOfClass('TTicketMotivo');
$object->__set('Sector' , $sector);
$object->__set('Motivo' , $motivo);
$object->__set('UsrResponsable' , $responsable);
if($motid) {
$object->__set('UsrUpdate' , $_SESSION["_usrid"]);
$object->__set('LastUpdate' , date("Y-m-d H:m:s"));
DataManager::updateSimpleObject($object);
} else {
$object->__set('UsrCreated' , $_SESSION["_usrid"]);
$object->__set('DateCreated', date("Y-m-d H:m:s"));
$object->__set('Activo' , 1);
$object->__set('ID' , $object->__newID());
$ID = DataManager::insertSimpleObject($object);
}
echo "1"; exit;
?><file_sep>/transfer/gestion/liquidaciondrog/logica/exportar.liquidacion.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_mes = empty($_GET['mes']) ? 0 : $_GET['mes'];
$_anio = empty($_GET['anio']) ? 0 : $_GET['anio'];
$_drogid = empty($_GET['drogid']) ? 0 : $_GET['drogid'];
if ($_drogid == 0){ echo "No se cargó correctamente la droguería"; exit; }
if ($_mes == 0 || $_anio == 0){ echo "No se cargó correctamente la fecha de liquidación."; exit; }
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=Liquidacion-".$_mes."-".$_anio.".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos (Liquidacion) .::</TITLE>
<head></head>
<body>
<div id="cuadro-liquidacion">
<div id="muestra_liquidacion">
<table id="tabla_liquidacion" name="tabla_liquidacion" class="tabla_liquidacion" border="0">
<thead>
<tr>
<th colspan="13" align="left">
Droguería: <?php
$_droguerias = DataManager::getDrogueria('');
if (count($_droguerias)) {
foreach ($_droguerias as $k => $_drog) {
$_drog = $_droguerias[$k];
$_Did = $_drog["drogtid"];
$_Didcliente = $_drog["drogtcliid"];
$_DidEmp = $_drog["drogtidemp"];
$_Dnombre = $_drog["drogtnombre"];
$_Dlocalidad = $_drog["drogtlocalidad"];
if($_drogid == $_Didcliente){
$_drogidemp = $_DidEmp;
echo $_Didcliente." | ".$_Dnombre." | ".$_Dlocalidad;
}
}
} ?>
</th>
</tr>
<tr>
<th colspan="13" align="left"> Fecha liquidacion: <?php echo $_mes." - ".$_anio; ?> </th>
</tr>
<tr height="60px;"> <!-- Títulos de las Columnas -->
<th align="center">Transfer</th>
<th align="center">Fecha Factura</th>
<th align="center">EAN</th>
<th align="center">Artículo</th>
<th align="center">Detalle</th>
<th align="center">Cantidad</th>
<th align="center">P.S.L. Unit.</th>
<th align="center">Desc. P.S.L</th>
<th align="center">Importe NC</th>
<th align="center">PSL Unit.</th>
<th align="center">Desc. PSL</th>
<th align="center">Importe NC</th>
<th align="center">Estado</th>
</tr>
</thead>
<tbody id="lista_liquidacion"> <?php
//******************************************//
//Consulta liquidacion del mes actual y su drogueria//
//******************************************//
$_liquidaciones = DataManager::getDetalleLiquidacion($_mes, $_anio, $_drogid, 'TD');
if ($_liquidaciones) {
foreach ($_liquidaciones as $k => $_liq){
$_liq = $_liquidaciones[$k];
$_liqID = $_liq['liqid'];
$_liqFecha = $_liq['liqfecha'];
$_liqTransfer = $_liq['liqnrotransfer'];
$_liqFechaFact = dac_invertirFecha( $_liq['liqfechafact'] );
$_liqean = str_replace(" ", "", $_liq['liqean']);
$_articulo = DataManager::getFieldArticulo("artcodbarra", $_liqean);
$_nombreart = $_articulo['0']['artnombre'];
$_idart = $_articulo['0']['artidart'];
$_liqcant = $_liq['liqcant'];
$_liqunit = $_liq['liqunitario'];
$_liqdesc = $_liq['liqdescuento'];
$_liqimportenc = $_liq['liqimportenc'];
$_TotalNC += $_liqimportenc;
$_liqactiva = $_liq['liqactiva'];
((($k % 2) != 0)? $clase="par" : $clase="impar");
// CONTROLA las Condiciones de las Liquidaciones y Notas de Crédito//
include($_SERVER['DOCUMENT_ROOT']."/pedidos/transfer/gestion/liquidaciondrog/logica/controles.liquidacion.php");
/*****************/
?>
<tr id="lista_liquidacion<?php echo $k;?>" class="<?php echo $clase;?>">
<td><?php echo $_liqTransfer;?></td>
<td><?php echo $_liqFechaFact;?></td>
<td style="mso-style-parent:style0; mso-number-format:\@"><?php echo $_liqean;?></td>
<td><?php echo $_idart;?></td>
<td><?php echo $_nombreart;?></td>
<td><?php echo $_liqcant;?></td>
<td><?php echo $_liqunit;?></td>
<td><?php echo $_liqdesc;?></td>
<td><?php echo $_liqimportenc;?></td>
<td width="120" align="center" style="border-bottom:1px #CCCCCC solid; color:#ba140c; font-weight:bold;"><?php echo $_CtrlPSLUnit;?></td>
<td width="120" align="center" style="border-bottom:1px #CCCCCC solid; color:#ba140c; font-weight:bold;"><?php echo $_CtrlDescPSL;?></td>
<td width="120" align="center" style="border-bottom:1px #CCCCCC solid; color:#ba140c; font-weight:bold;"><?php echo $_CtrlImpNT;?></td>
<td align="center"><?php echo $_Estado; ?></td>
</tr> <?php
} //FIN del FOR
} else { ?>
<tr class="impar"><td colspan="13" align="center">No hay liquidaciones cargadas</td></tr><?php
}?>
</form>
</tbody>
<tfoot>
<tr>
<th colspan="7" height="30px" style="border:none; font-weight:bold;"></th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;">Total</th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;"><?php echo $_TotalNC; ?></th>
<th colspan="2" height="30px" style="border:none; font-weight:bold;"></th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;"><?php echo $_CtrlTotalNC; ?></th>
<th colspan="1" height="30px" style="border:none; font-weight:bold;"></th>
</tr>
</tfoot>
</table>
<div hidden="hidden"><button id="btnExport" hidden="hidden"></button></div>
</div> <!-- FIN muestra_bonif -->
</div> <!-- FIN liquidacion -->
</body>
</html>
<file_sep>/inicio/logica/anular.pedido.php
<?php
session_start();
$_idcliente = (isset($_POST['idcliente2'])) ? $_POST['idcliente2'] : NULL;
$_idpedido = (isset($_POST['idpedido'])) ? $_POST['idpedido'] : NULL;
$_motivo = (isset($_POST['motivo'])) ? $_POST['motivo'] : NULL;
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail = new PHPMailer();
$mail->From = "<EMAIL>"; //$_SESSION["_usremail"];
$mail->FromName = "Información Neo-farma"; //Vendedor: ".$_SESSION["_usrname"]
$mail->Subject = "Solicitud de ANULACIÓN de pedido.";
$_total= "
Hola, se envían los datos de solicitud de ANULACIÓN de pedido.<br /><br />
<table border='1' cellpadding='10' width='500px'>
<tr>
<th colspan='2'>
Vendedor:".$_SESSION["_usrname"]."<br />
E-mail: ".$_SESSION["_usremail"]."<br />
</th>
</tr>
<tr>
<th rowspan='2' align='right' width=450px>
Nro. Cliente:<br />
Id Pedido Web:<br />
Motivo:
</th>
<th rowspan='2' align='left' width=450px>
".$_idcliente."<br />
".$_idpedido." <br />
".$_motivo." <br />
</th>
</tr>
</table>
<br />Saludos.";
$mail->msgHTML($_total);
$mail->AddAddress("<EMAIL>", "Solicitud de ANULACIÓN de pedido");
$mail->AddAddress("<EMAIL>.ar");
$mail->AddAddress($_SESSION["_usremail"], "Solicitud de ANULACIÓN(comprobante)");
if(!$mail->Send()) {
echo 'Fallo en el envío';
} else {
$_goURL = "/pedidos/index.php";
header('Location:'.$_goURL);
}
exit;
?>
<file_sep>/localidades/logica/exportar.localidades.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
header("Content-Type: application/vnd.ms-excel");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition:attachment;filename=Localidades-".date('d-m-y').".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos .::</TITLE>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<style>
.datatab{
font-size:14px;
}
tr th {
font-weight:bold;
height: 20px;
}
td.par {
background-color: #fff;
height: 20px;
}
td.impar {
background-color: #cfcfcf;
height: 20px;
font-weight:bold;
}
</style>
</head>
<body>
<table border="0" style="table-layout: fixed;">
<thead>
<tr>
<TD style="font-size:16px; color:#117db6; border:1px solid #666">Provincia</TD>
<TD style="font-size:16px; color:#117db6; border:1px solid #666">Localidad</TD>
<TD style="font-size:16px; color:#117db6; border:1px solid #666">Código Postal</TD>
<TD style="font-size:16px; color:#117db6; border:1px solid #666">Zona Vendedor</TD>
<TD style="font-size:16px; color:#117db6; border:1px solid #666; word-wrap:break-word" >Excepciones</TD>
<TD style="font-size:16px; color:#117db6; border:1px solid #666">Zona Entrega</TD>
</tr>
</thead>
<?php
$localidades= DataManager::getLocalidades();
if($localidades){
foreach ($localidades as $k => $loc) {
$idProv = $loc["locidprov"];
$provincia = DataManager::getProvincia('provnombre', $idProv);
$idLoc = $loc["locidloc"];
$localidad = $loc["locnombre"];
$cp = $loc["loccodpostal"];
$zonaV = $loc["loczonavendedor"];
$zonaD = $loc["loczonaentrega"];
$zonaDNombre= DataManager::getZonaDistribucion('NombreZN', 'IdZona', $zonaD);
$zonaDistribucion = $zonaD."|".$zonaDNombre;
$excepciones = '';
$zonasExpecion = DataManager::getZonasExcepcion($idLoc);
if(count($zonasExpecion)){
foreach ($zonasExpecion as $k => $ze) {
$zeCtaIdDDBB= $ze['zeCtaId'];
$zeZonaDDBB = $ze['zeZona'];
$idCuenta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $zeCtaIdDDBB);
$nombre = DataManager::getCuenta('ctanombre', 'ctaid', $zeCtaIdDDBB);
$excepciones= '';
$excepciones= "$zeZonaDDBB|$idCuenta|$nombre";
echo sprintf("<tr align=\"left\">");
if(($k % 2) == 0){
echo sprintf("<td class='par'>%s</td><td class='par'>%s</td><td class='par'>%s</td class='par'><td class='par'>%s</td><td class='par'>%s</td><td class='par'>%s</td>", $provincia, $localidad, $cp, $zonaV, $excepciones, $zonaDistribucion);
} else {
echo sprintf("<td class='impar'>%s</td><td class='impar'>%s</td><td class='impar'>%s</td class='impar'><td class='impar'>%s</td><td class='impar'>%s</td><td class='impar'>%s</td>", $provincia, $localidad, $cp, $zonaV, $excepciones, $zonaDistribucion);
}
echo sprintf("</tr>");
}
} else {
echo sprintf("<tr align=\"left\">");
if(($k % 2) == 0){
echo sprintf("<td class='par'>%s</td><td class='par'>%s</td><td class='par'>%s</td class='par'><td class='par'>%s</td><td class='par'>%s</td><td class='par'>%s</td>", $provincia, $localidad, $cp, $zonaV, $excepciones, $zonaDistribucion);
} else {
echo sprintf("<td class='impar'>%s</td><td class='impar'>%s</td><td class='impar'>%s</td class='impar'><td class='impar'>%s</td><td class='impar'>%s</td><td class='impar'>%s</td>", $provincia, $localidad, $cp, $zonaV, $excepciones, $zonaDistribucion);
}
echo sprintf("</tr>");
}
}
} ?>
</table>
</body>
</html>
<file_sep>/informes/logica/exportar.transfer.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
//*******************************************
$fechaDesde = (isset($_POST['fechaDesde'])) ? $_POST['fechaDesde'] : NULL;
$fechaHasta = (isset($_POST['fechaHasta'])) ? $_POST['fechaHasta'] : NULL;
//*******************************************
if(empty($fechaDesde) || empty($fechaHasta)){
echo "Debe completar las fechas de exportación"; exit;
}
$fechaInicio = new DateTime(dac_invertirFecha($fechaDesde));
$fechaFin = new DateTime(dac_invertirFecha($fechaHasta));
$fechaFin->modify("+1 day");
//*************************************************
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=PedidosTransfers-".date('d-m-y').".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos (Pedidos Transfers) .::</TITLE>
<head></head>
<body>
<table border="0">
<thead>
<tr>
<td scope="col" >Empresa</td>
<td scope="col" >Cliente</td>
<td scope="col" >Razón Social</td>
<td scope="col" >Domicilio</td>
<td scope="col" >Localidad</td>
<td scope="col" >Provincia</td>
<td scope="col" >Tipo</td>
<td scope="col" >Suc</td>
<td scope="col" >Nro Transfer</td>
<td scope="col" >IdLab</td>
<td scope="col" >ID Artículo</td>
<td scope="col" >Fecha</td>
<td scope="col" >IdStock</td>
<td scope="col" >Cantidad</td>
<td scope="col" >Bonificadas</td>
<td scope="col" >Importe Total</td>
<td scope="col" >Precio</td>
<td scope="col" >Precio Final</td>
<td scope="col" >Descuento</td>
<td scope="col" ></td>
<td scope="col" ></td>
<td scope="col" ></td>
<td scope="col" ></td>
<td scope="col" ></td>
<td scope="col" ></td>
<td scope="col" ></td>
<td scope="col" >Categ.</td>
<td scope="col" >Dni Asig</td>
<td scope="col" >Asignado a</td>
<td scope="col" >Mes</td>
<td scope="col" >Año</td>
<td scope="col" >Total</td>
<td scope="col" >Rubro</td>
<td scope="col" >Familia</td>
<td scope="col" >Canal</td>
<td scope="col" >Cuit</td>
<td scope="col" >Cadena</td>
<td scope="col" >Dni</td>
<td scope="col" >Vendedor</td>
<td scope="col" >Id Drogueria</td>
<td scope="col" >Drogueria</td>
</tr>
</thead>
<?php
$_transfers_recientes = DataManager::getTransfers(0, NULL, $fechaInicio->format('Y-m-d'), $fechaFin->format('Y-m-d'));
if($_transfers_recientes){
for( $k=0; $k < count($_transfers_recientes); $k++ ){
$_transfer_r = $_transfers_recientes[$k];
$fecha = explode(" ", $_transfer_r["ptfechapedido"]);
list($ano, $mes, $dia) = explode("-", $fecha[0]);
$_fecha = $dia."-".$mes."-".$ano;
$_nropedido = $_transfer_r["ptidpedido"];
$_nombre = $_transfer_r["ptclirs"];
$_detalles = DataManager::getTransfersPedido(NULL, NULL, NULL, NULL, NULL, NULL, $_nropedido);
//DataManager::getDetallePedidoTransfer($_nropedido);
if ($_detalles) {
for( $j=0; $j < count($_detalles); $j++ ){
$_precio_final = 0;
$_importe_final = 0;
$cadNombre = '';
$_detalle = $_detalles[$j];
$_nombreven = DataManager::getUsuario('unombre', $_detalle['ptidvendedor']);
$_nombreven = utf8_decode($_nombreven);
$_dniven = DataManager::getUsuario('udni', $_detalle['ptidvendedor']);
$nombreAsignado = DataManager::getUsuario('unombre', $_detalle['ptparaidusr']);
$nombreAsignado = utf8_decode($nombreAsignado);
$dniAsignado = DataManager::getUsuario('udni', $_detalle['ptparaidusr']);
$empresa = 1;
$_idcliente_drog= $_detalle['ptnroclidrog'];
if ($_detalle['ptidclineo'] != 0) {
$ctaId = $_detalle['ptidclineo'];
$_ruteo = DataManager::getCuenta('ctaruteo', 'ctaid', $ctaId);
$_categoria = DataManager::getCuenta('ctacategoriacomercial', 'ctaid', $ctaId);
$cuit = DataManager::getCuenta('ctacuit', 'ctaid', $ctaId);
$empresa = DataManager::getCuenta('ctaidempresa', 'ctaid', $ctaId);
$cuenta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $ctaId);
//-----------------
$idCadenaCad= 0;
$cuentasCad = DataManager::getCuentasCadena($empresa, NULL, $cuenta);
if (count($cuentasCad)) {
foreach ($cuentasCad as $q => $ctaCad) {
$idCadenaCad = $ctaCad['IdCadena'];
}
}
$cadNombre = '';
if($idCadenaCad){
$cadenas = DataManager::getCadenas($empresa, $idCadenaCad);
if (count($cadenas)) {
foreach ($cadenas as $q => $cad) {
$cadNombre = $cad["NombreCadena"];
}
}
}
$canal = '';
if(empty($cadNombre)){
$cadNombre = $_nombre;
$canal = 'Minorista';
} else {
$canal = 'Cadena';
}
//----------------
$_ruteo = ($_ruteo == 0) ? '' : $_ruteo;
$_categoria = ($_categoria == 0) ? '' : $_categoria;
$categoria = $_ruteo.$_categoria;
} else {
$ctaId = $_idcliente_drog;
$categoria = "Transfer";
}
$_iddrogueria = $_detalle['ptiddrogueria'];
$_nombredrog = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $_iddrogueria, $empresa);
$_contacto = $_detalle['ptcontacto'];
$_unidades = $_detalle['ptunidades'];
$_descuento = $_detalle['ptdescuento'];
$_ptidart = $_detalle['ptidart'];
$_ptprecio = $_detalle['ptprecio'];
$_descripcion = DataManager::getArticulo('artnombre', $_ptidart, $empresa, 1);
$artIdRubro = DataManager::getArticulo('artidrubro', $_ptidart, $empresa, 1);
$artIdFamilia = DataManager::getArticulo('artidfamilia', $_ptidart, $empresa, 1);
$rubroDesc = '';
$rubros = DataManager::getRubros($artIdRubro);
if (count($rubros)) {
foreach ($rubros as $q => $rub) {
$rubroDesc = $rub["Descripcion"];
}
}
$nombreFlia = '';
$familias = DataManager::getCodFamilias(0,0,$empresa, $artIdFamilia);
if (count($familias)) {
foreach ($familias as $q => $flia) {
$nombreFlia = $flia["Nombre"];
}
}
$_precio_final = round( ($_ptprecio - (($_descuento/100)*$_ptprecio)), 3);
$_importe_final = round( $_precio_final * $_unidades, 3);
echo sprintf("<tr align=\"left\">");
echo sprintf("<td>1</td><td >%s</td><td>%s</td><td>0</td><td>0</td><td>0</td><td>Transfer</td><td>0</td><td>%s</td><td>1</td><td>%s</td><td>%s</td><td>0</td><td>%s</td><td>0</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>", $cuenta, $_nombre, $_nropedido, $_ptidart, $_fecha, $_unidades, $_importe_final, $_ptprecio, $_precio_final, $_descuento, $categoria, $dniAsignado, $nombreAsignado, $mes, $ano, $_unidades, $rubroDesc, $nombreFlia, $canal, $cuit, $cadNombre, $_dniven, $_nombreven, $_iddrogueria, $_nombredrog);
echo sprintf("</tr>");
}
}
}
}
?>
</table>
</body>
</html>
<file_sep>/cuentas/logica/update.transfer.relacionado.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$ctaId = (isset($_POST['ctaId'])) ? $_POST['ctaId'] : NULL;
$tipo = (isset($_POST['tipo'])) ? $_POST['tipo'] : NULL;
//Arrays
$arrayCtaIdDrog = (isset($_POST['cuentaIdDrog'])) ? $_POST['cuentaIdDrog'] : NULL;
$arrayCtaCliente = (isset($_POST['cuentaIdTransfer'])) ? $_POST['cuentaIdTransfer'] : NULL;
if(empty($tipo) || $tipo == "PS" || $tipo == "O"){
echo 'El tipo de cuenta no admite cuentas transfers relacionadas.'; exit;
}
if(!empty($arrayCtaIdDrog)){
if(count($arrayCtaIdDrog)){
for($i = 0; $i < count($arrayCtaIdDrog); $i++){
if (empty($arrayCtaCliente[$i])){
echo "Indique cliente transfer para la cuenta ".$i; exit;
}
}
}
//Controla Droguerías duplicadas
if(count($arrayCtaIdDrog) != count(array_unique($arrayCtaIdDrog))){
echo "Hay droguerías duplicadas."; exit;
}
}
//-------------------//
// GUARDAR CAMBIOS //
if ($ctaId) {
//--------------------------------//
// UPDATE TRANSFERS RELACIONADAS //
if(!empty($arrayCtaIdDrog)){
if(count($arrayCtaIdDrog)){
$cuentasRelacionadas = DataManager::getCuentasRelacionadas($ctaId); //$empresa, $idCuenta
if (count($cuentasRelacionadas)) {
foreach ($cuentasRelacionadas as $k => $ctaRel) {
$ctaRel = $cuentasRelacionadas[$k];
$relId = $ctaRel['ctarelid'];
$relIdDrog = $ctaRel['ctarelidcuentadrog'];
//Creo Array de Droguerias Relacionadas de BBDD
$arrayDrogDDBB[] = $relIdDrog;
if (in_array($relIdDrog, $arrayCtaIdDrog)) {
//UPDATE
$key = array_search($relIdDrog, $arrayCtaIdDrog); //Indice donde se encuentra la cuenta
$ctaRelObject = DataManager::newObjectOfClass('TCuentaRelacionada', $relId);
$ctaRelObject->__set('Transfer' , $arrayCtaCliente[$key]); //nro de cliente para la droguería
DataManager::updateSimpleObject($ctaRelObject);
} else {
//DELETE de cuentas relacionadas
$ctaRelObject = DataManager::newObjectOfClass('TCuentaRelacionada', $relId);
$ctaRelObject->__set('ID', $relId);
DataManager::deleteSimpleObject($ctaRelObject);
}
}
foreach ($arrayCtaIdDrog as $k => $ctaIdDrog) {
if (!in_array($ctaIdDrog, $arrayDrogDDBB)) {
//INSERT
$ctaRelObject = DataManager::newObjectOfClass('TCuentaRelacionada');
$ctaRelObject->__set('Cuenta' , $ctaId);
$ctaRelObject->__set('Drogueria' , $ctaIdDrog);
$ctaRelObject->__set('Transfer' , $arrayCtaCliente[$k]);
$ctaRelObject->__set('ID' , $ctaRelObject->__newID());
$IDRelacion = DataManager::insertSimpleObject($ctaRelObject);
}
}
} else { //INSERT - Si no hay cuentas relacionadas, las crea
foreach ($arrayCtaIdDrog as $k => $ctaIdDrog) {
$ctaRelObject = DataManager::newObjectOfClass('TCuentaRelacionada');
$ctaRelObject->__set('Cuenta' , $ctaId);
$ctaRelObject->__set('Drogueria' , $ctaIdDrog); //nro iddrogueria
$ctaRelObject->__set('Transfer' , $arrayCtaCliente[$k]); //nro cliente transfer
$ctaRelObject->__set('ID' , $ctaRelObject->__newID());
$IDRelacion = DataManager::insertSimpleObject($ctaRelObject);
}
}
}
} else {
$cuentasRelacionadas = DataManager::getCuentasRelacionadas($ctaId); //$empresa, $idCuenta
if (count($cuentasRelacionadas)) {
//DELETE de cuentas relacionadas
foreach ($cuentasRelacionadas as $k => $ctaRel) {
$ctaRel = $cuentasRelacionadas[$k];
$relId = $ctaRel['ctarelid'];
$ctaRelObject = DataManager::newObjectOfClass('TCuentaRelacionada', $relId);
$ctaRelObject->__set('ID', $relId);
DataManager::deleteSimpleObject($ctaRelObject);
}
}
}
//*********************//
// Registro MOVIMIENTO //
//**********************//
$movimiento = 'UPDATE_TRANSFERS_RELACIONADOS';
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", $ctaId);
echo '1'; exit;
} else {
echo "La cuenta aún no fue creada."; exit;
}
?><file_sep>/pedidos/propuestas/lista.php
<?php
$_LPP = 5000;
$_pag = 1;
?>
<?php
if ($_SESSION["_usrrol"] == "A" || $_SESSION["_usrid"] == "17" || $_SESSION["_usrrol"] == "M" || $_SESSION["_usrrol"] == "V" || $_SESSION["_usrrol"] == "G"){
?>
<script language="JavaScript" src="/pedidos/pedidos/logica/jquery/jquery.aprobar.js" type="text/javascript"></script>
<div class="box_down"> <!-- datos -->
<div class="barra">
<div class="bloque_1">
<h1>Propuestas</h1>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table>
<thead>
<tr>
<td scope="col" height="18">Fecha</td>
<td scope="col" >Prop</td>
<td scope="col" >Cuenta</td>
<td scope="col" >Nombre</td>
<td scope="col" >Vendedor</td>
<td scope="col" >Estado</td>
<td colspan="2" scope="colgroup" align="center">Acciones</td>
</tr>
</thead>
<?php
$idUsr = ($_SESSION["_usrrol"] == "V") ? $_SESSION["_usrid"] : NULL;
$propPendientes = DataManager::getPropuestas(NULL, 1, $idUsr);
if ($propPendientes){
foreach ($propPendientes as $k => $propP) {
$idProp = $propP["propid"];
$idUsr = $propP["propusr"];
$nombreUsr = DataManager::getUsuario('unombre', $idUsr);
$fecha = $propP["propfecha"];
$idCuenta = $propP["propidcuenta"];
$propEmpresa= $propP["propidempresa"];
$estado = $propP["propestado"];
$estadoName = DataManager::getEstado('penombre', 'peid', $estado);
switch ($estado){
case 0:
$status = "<a title='".$estadoName."' ><img class=\"icon-status-close\"/></a>";
break;
case 1:
$status = "<a title=".$estadoName."><img class=\"icon-status-pending\" /></a>";
break;
case 2:
$status = "<a title=".$estadoName."><img class=\"icon-status-active\" /></a>";
break;
case 3:
$status = "<a title=".$estadoName."><img class=\"icon-status-inactive\" /></a>";
break;
default:
$status = $estadoName;
break;
}
$nombreCuenta= DataManager::getCuenta('ctanombre', 'ctaidcuenta', $idCuenta, $propEmpresa);
$clase = ((($k % 2) == 0)? "par" : "impar");
$_detalle = sprintf("<a href=\"../detalle.propuesta.php?propuesta=%d\" title=\"Detalle\">%s</a>", $idProp, "<img class=\"icon-detail\"/>");
$_editar = sprintf( "<a href=\"../editar.php?propuesta=%d\" target=\"_blank\" title=\"Editar\">%s</a>", $idProp, "<img class=\"icon-edit\"/>");
echo sprintf("<tr class=\"%s\">", $clase);
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>", $fecha, $idProp, $idCuenta, $nombreCuenta, $nombreUsr, $status, $_detalle, $_editar);
echo sprintf("</tr>");
}
} else {
?>
<tr>
<td scope="colgroup" colspan="8" height="25" align="center">No hay registros.</td>
</tr>
<?php
}
?>
</table>
</div> <!-- Fin lista -->
</div> <!-- Fin datos -->
<div class="box_down"> <!-- datos -->
<div class="barra">
<div class="bloque_5">
<h1>Propuestas Finalizadas</h1>
</div>
<hr>
</div> <!-- Fin Barra -->
<div class="lista">
<table>
<thead>
<tr>
<td scope="col" height="18">Fecha</td>
<td scope="col" >Prop</td>
<td scope="col" >Cuenta</td>
<td scope="col" >Nombre</td>
<td scope="col" >Vendedor</td>
<td scope="col" >Estado</td>
</tr>
</thead>
<?php
$idUsr = ($_SESSION["_usrrol"] == "V") ? $_SESSION["_usrid"] : NULL;
$dateTo = new DateTime('now');
$dateFrom = new DateTime('now');
$dateFrom ->modify('-6 month');
$propPendientes = DataManager::getPropuestas(NULL, 0, NULL, $dateFrom->format('Y-m-d'), $dateTo->format('Y-m-d'));
if ($propPendientes){
foreach ($propPendientes as $k => $propP) {
$idProp = $propP["propid"];
$idUsr = $propP["propusr"];
$nombreUsr = DataManager::getUsuario('unombre', $idUsr);
$fecha = $propP["propfecha"];
$fechaDesde = new DateTime();
$fechaDesde->modify('-1 year');
if($fecha > $fechaDesde->format('Y-m-d H:i:s')) {
$idCuenta = $propP["propidcuenta"];
$estado = (empty($propP["propestado"]) && $propP["propestado"] != 0) ? "" : $propP["propestado"];
$estadoName = DataManager::getEstado('penombre', 'peid', $estado);
$nombreCuenta= DataManager::getCuenta('ctanombre', 'ctaidcuenta', $idCuenta, NULL);
switch ($estado){
case 0:
$status = "<a title=".$estadoName."><img class=\"icon-status-close\" /></a>";
break;
case 1:
$status = "<a title=".$estadoName."><img class=\"icon-status-pending\" /></a>";
break;
case 2:
$status = "<a title=".$estadoName."><img class=\"icon-status-active\" /></a>";
break;
case 3:
$status = "<a title=".$estadoName."><img class=\"icon-status-inactive\" /></a>";
break;
default:
$status = $estadoName;
break;
}
$clase = ((($k % 2) == 0)? "par" : "impar");
echo sprintf("<tr class=\"%s\" style=\"cursor:pointer;\" onclick=\"window.open('../detalle.propuesta.php?propuesta=%d')\" title=\"Detalle\">", $clase, $idProp);
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>", $fecha, $idProp, $idCuenta, $nombreCuenta, $nombreUsr, $status);
echo sprintf("</tr>");
}
}
} else { ?>
<tr>
<td scope="colgroup" colspan="6" height="25" align="center">No hay registros.</td>
</tr>
<?php
} ?>
</table>
</div> <!-- Fin lista -->
</div> <!-- Fin datos -->
<?php } ?>
<hr><file_sep>/transfer/lista.php
<div class="box_down"> <!-- datos -->
<?php if ($_SESSION["_usrrol"]=="G" || $_SESSION["_usrrol"]== "A" || $_SESSION["_usrrol"]== "M"){ ?>
<div class="barra">
<div class="bloque_5" align="left">
<h1>Pendientes</h1>
</div>
<div class="bloque_6" align="right">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn" type="text" value="tblPTPendientes" hidden/>
</div>
<div class="bloque_8" align="right">
<?php if ($_SESSION["_usrrol"]!= "G"){ ?>
<a href="logica/enviar.pedido.php" title="Enviar">
<img class="icon-send"/>
</a>
<?php } ?>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblPTPendientes">
<thead>
<tr>
<td scope="col" width="20%" height="18">Fecha</td>
<td scope="col" width="20%">Transfer</td>
<td scope="col" width="50%">Cliente</td>
<td scope="colgroup" colspan="3" width="10%" align="center">Acciones</td>
</tr>
</thead>
<?php
$_transfers_recientes = DataManager::getTransfers(1);
$_max = count($_transfers_recientes);
if ($_max != 0) {
for( $k=0; $k < $_max; $k++ ) {
if ($k < $_max){
$_transfer_r = $_transfers_recientes[$k];
$_fecha = $_transfer_r["ptfechapedido"];
$_nropedido = $_transfer_r["ptidpedido"];
$_nombre = $_transfer_r["ptclirs"];
$_eliminar = sprintf ("<a href=\"logica/eliminar.pedido.php?ptid=%d&backURL=%s\" title=\"eliminar pedido\" onclick=\"return confirm('¿Está Seguro que desea ELIMINAR EL PEDIDO?')\"> <img class=\"icon-delete\"/> </a>", $_nropedido, $_SERVER['PHP_SELF'], "eliminar");
$_detalle = sprintf( "<a href=\"detalle_transfer.php?idpedido=%d&backURL=%s\" target=\"_blank\" title=\"detalle pedido\">%s</a>", $_nropedido, $_SERVER['PHP_SELF'], "<img class=\"icon-detail\"/>");
$_espacio = sprintf("<img src=\"/pedidos/images/icons/icono-vacio.png\" border=\"0\" align=\"absmiddle\" />");
}
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_fecha, $_nropedido, $_nombre, $_eliminar, $_espacio, $_detalle);
echo sprintf("</tr>");
}
} else { ?>
<tr>
<td scope="colgroup" colspan="3" height="25" align="center">No hay pedidos Transfer pendientes</td>
</tr> <?php
} ?>
</table>
</div> <!-- Fin listar -->
<?php }?>
<?php if ($_SESSION["_usrrol"]=="V" || $_SESSION["_usrrol"]== "A"){ ?>
<div class="barra">
<div class="bloque_5" align="left">
<h1>Mis Pendientes</h1>
</div>
<div class="bloque_6" align="right">
<input id="txtBuscar2" type="search" autofocus placeholder="Buscar"/>
<input id="txtBuscarEn2" type="text" value="tblMisPTPendientes" hidden/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblMisPTPendientes">
<thead>
<tr>
<td scope="col" width="20%" height="18">Fecha</td>
<td scope="col" width="20%">Transfer</td>
<td scope="col" width="50%">Cliente</td>
<td scope="colgroup" colspan="3" width="10%" align="center">Acciones</td>
</tr>
</thead>
<?php
$_transfers_recientes = DataManager::getTransfers(1, $_SESSION["_usrid"]);
$_max = count($_transfers_recientes);
if ($_max != 0) {
for( $k=0; $k < $_max; $k++ ){
if ($k < $_max){
$_transfer_r = $_transfers_recientes[$k];
$_fecha = $_transfer_r["ptfechapedido"];
$_nropedido = $_transfer_r["ptidpedido"];
$_nombre = $_transfer_r["ptclirs"];
$_eliminar = sprintf ("<a href=\"logica/eliminar.pedido.php?ptid=%d&backURL=%s\" title=\"eliminar pedido\" onclick=\"return confirmar('¿Está Seguro que desea ELIMINAR EL PEDIDO?')\"> <img class=\"icon-delete\"/> </a>", $_nropedido, $_SERVER['PHP_SELF'], "eliminar");
$_detalle = sprintf( "<a href=\"detalle_transfer.php?idpedido=%d&backURL=%s\" target=\"_blank\" title=\"detalle pedido\">%s</a>", $_nropedido, $_SERVER['PHP_SELF'], "<img class=\"icon-detail\"/>");
$_espacio = sprintf("<img src=\"/pedidos/images/icons/icono-vacio.png\" border=\"0\" align=\"absmiddle\" />");
}
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_fecha, $_nropedido, $_nombre, $_eliminar, $_espacio, $_detalle);
echo sprintf("</tr>");
}
} else { ?>
<tr>
<td scope="colgroup" colspan="3" height="25" align="center">No hay pedidos Transfer pendientes</td>
</tr> <?php
} ?>
</table>
</div> <!-- Fin listar -->
<?php }?>
</div> <!-- Fin datos --><file_sep>/localidades/logica/ajax/getLocalidades.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
//------------------------------------------------
$idProv = (isset($_POST['idProv'])) ? $_POST['idProv'] : NULL;
$idZonaV = (isset($_POST['idZonaV'])) ? $_POST['idZonaV'] : NULL;
$idZonaD = (isset($_POST['idZonaD'])) ? $_POST['idZonaD'] : NULL;
//------------------------------------------------
$localidades= DataManager::getLocalidades(NULL, $idProv, $idZonaV, $idZonaD);
$rows = count($localidades);
echo "<table id=\"tblLocalidades\" style=\"table-layout:fixed;\">";
if ($rows) {
echo "<thead><tr align=\"left\"><th width=\"25%\">Provincia</th><th width=\"25%\">Localidad</th><th width=\"10%\">CP</th><th width=\"15%\">Zona Vendedor</th><th width=\"15%\">Zona Entrega</th><th align=\"center\" width=\"10%\">Acciones</th></tr></thead>";
echo "<tbody>";
for( $k=0; $k < $rows; $k++ ) {
$loc = $localidades[$k];
$idLoc = $loc['locidloc'];
$locNombre = $loc['locnombre'];
$idProv = $loc['locidprov'];
$codPostal = $loc['loccodpostal'];
$nombreProv = DataManager::getProvincia('provnombre', $idProv);
$zonaVendedor = $loc['loczonavendedor'];
$zonaEntrega = $loc['loczonaentrega'];
$_editar = sprintf( "onclick=\"window.open('editar.php?idLoc=%d')\" style=\"cursor:pointer;\"",$idLoc);
$checkBox = "<input type=\"checkbox\" name=\"editSelected\" value=\"$idLoc\" onClick=\"dac_addLocalidad()\">";
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class=".$clase.">";
echo "<td height=\"15\" ".$_editar.">".$nombreProv."</td><td ".$_editar.">".$locNombre."</td><td ".$_editar.">".$codPostal."</td><td ".$_editar.">".$zonaVendedor."</td><td ".$_editar.">".$zonaEntrega."</td><td >".$checkBox."</td>";
echo "</tr>";
}
} else {
echo "<tbody>";
echo "<thead><tr><th colspan=\"6\" align=\"center\">No hay cuentas relacionadas</th></tr></thead>"; exit;
}
echo "</tbody></table>";
?><file_sep>/transfer/gestion/liquidaciondrog/logica/update.liquidacion.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_drogueria = empty($_POST['drogid']) ? 0 : $_POST['drogid'];
$_fecha_liq = empty($_POST['fecha_liquidacion']) ? 0 : $_POST['fecha_liquidacion'];
if (empty($_drogueria)){ echo "Seleccione una droguería"; exit; }
if ($_fecha_liq == 0){ echo "Seleccione un fecha a conciliar."; exit; }
list($_mes, $_anio) = explode("-", $_fecha_liq);
//**************************//
// Concilio Liquidación //
//**************************//
$_liquidaciones = DataManager::getDetalleLiquidacion($_mes, $_anio, $_drogueria, 'TD');
if ($_liquidaciones) {
foreach ($_liquidaciones as $k => $_liq) {
$_liq = $_liquidaciones[$k];
$_liqID = $_liq['liqid'];
//EDITA ESTADO DE LIQUIDADO
$liqObject = DataManager::newObjectOfClass('TLiquidacion', $_liqID);
if($liqObject->__get('Activa')){
echo "La liquidación ya fue conciliada. No puede volver a liquidarla."; exit;
}
$liqObject->__set('Activa', 0);
$ID = DataManager::updateSimpleObject($liqObject);
}
//**********************//
// Registro MOVIMIENTO //
//**********************//
$movimiento = 'LIQUIDACION_NC';
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TAbm");
echo "1";
} else {
echo "Ocurrió un error al querer actualizar el estado de liquidaciones. Vuelva a intentarlo."; exit;
}
?><file_sep>/js/ajax/send.email.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
//*************************************************
$empresa = (isset($_POST['idemp'])) ? $_POST['idemp'] : NULL;
$from = (isset($_SESSION["_usremail"])) ? $_SESSION["_usremail"]: "<EMAIL>"; //mail del usuario
$fromName = (isset($_SESSION["_usremail"])) ? $_SESSION["_usremail"]: "infoWeb"; //nombre del usuario
$email = (isset($_POST['email'])) ? $_POST['email'] : NULL;
$asunto = (isset($_POST['asunto'])) ? $_POST['asunto'] : 'Sin asunto';
$mensaje = (isset($_POST['mensaje'])) ? $_POST['mensaje'] : NULL;
//*************************************************
if(empty($empresa)){
echo "No se registró desde que empresa está haciendo el envío del corréo"; exit;
}
$from = trim($from, ' ');
if (!dac_validateMail($from)) {
echo "El corréo del usuario es incorrecto para enviar emails"; exit;
}
$email = trim($email, ' ');
if (!dac_validateMail($email)) {
echo "El corréo del destinatario es incorrecto"; exit;
}
if(empty($mensaje)){
echo "Debe escribir algún mensaje"; exit;
}
//******************//
// Envío de Email //
//******************//
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = $from;
$mail->FromName = $fromName; //"InfoWeb GEZZI";
$mail->Subject = $asunto;
/*****************************/
//Manejo de Multifile Via Ajax
/*****************************/
if ($_FILES['multifile']){
foreach($_FILES['multifile']['name'] as $key => $name){
//Si el archivo se paso correctamente
if($_FILES['multifile']['error'][$key] == UPLOAD_ERR_OK){
$original = $_FILES['multifile']['name'][$key];
$temporal = $_FILES['multifile']['tmp_name'][$key];
if(filesize($temporal) > ((1024 * 1024) * 4)){ //(1MG == 1024KB && 1KB == 1024) ==> 1MB == 1048576 Bytes
echo '<b>'.$original.'</b> no debe superar los 4 MB. <br>'; exit;
}
$mail->AddAttachment($temporal, $original); //($destino);
}
if($_FILES['multifile']['error'][$key] != UPLOAD_ERR_OK && $_FILES['multifile']['error'][$key] != UPLOAD_ERR_NO_FILE){
echo 'Error '.$_FILES['multifile']['error'][$key].' al subir el archivo <b>'.$original.'</b>'; exit;
}
}
} else {
echo '</b> Error al intentar cargar archivos. <br> Recuerde que no se pueden enviar más de 8MB totales en adjuntos'; exit; //Una opción es que esté intentando superar un archivo con 8 MB
}
/*****************************/
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
$_total = '
<html>
<head>
<title>Email de Empresa</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 90%;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 0px;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>
<body>
<div align="center">
<table width="600" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
'.$mensaje.'
<div />
</td >
</tr>
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif" style="font-size:12px">
Por cualquier consulta, póngase en contacto con la empresa al 4555-3366 de Lunes a Viernes de 10 a 17 horas.
</font>
</div>
</td>
</tr>
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo" align="left">
Gracias por confiar en nosotros.<br/>
Le saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div/>
</body>
';
$mail->msgHTML($_total);
$mail->AddAddress($email); //El PARA $para, saldrá en todos los destino BCC
$mail->AddBCC("<EMAIL>");
//*********************************//
if(!$mail->Send()) {
echo "Hubo un error al intentar enviar el correo"; exit;
}
//**************************//
echo 1;
?><file_sep>/zonas/logica/changestatus.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$_zid = empty($_REQUEST['zid']) ? 0 : $_REQUEST['zid'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/zonas/': $_REQUEST['backURL'];
if ($_zid) {
$_zobject = DataManager::newObjectOfClass('TZonas', $_zid);
$zona = $_zobject->__get('Zona');
//---------------------------
//verificar que no haya cuentas con esa zona definida
$cuentas = DataManager::getCuentaAll('*', 'ctazona', $zona);
if (count($cuentas)) {
echo "Existen cuentas que aún tienen definida ésta ZONA."; exit;
}
//---------------------------
$_status = ($_zobject->__get('Activo')) ? 0 : 1;
$_zobject->__set('Activo', $_status);
$ID = DataManager::updateSimpleObject($_zobject);
}
header('Location: '.$backURL.'?pag='.$_pag);
?><file_sep>/proveedores/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$_provid = empty($_REQUEST['provid']) ? 0 : $_REQUEST['provid'];
$_sms = empty($_GET['sms']) ? 0 : $_GET['sms'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/proveedores/' : $_REQUEST['backURL'];
if ($_sms) {
$_idempresa = $_SESSION['s_empresa'];
$_idproveedor = $_SESSION['s_idproveedor'];
$_nombre = $_SESSION['s_nombre'];
$_direccion = $_SESSION['s_direccion'];
$_idprovincia = $_SESSION['s_provincia'];
$_idloc = $_SESSION['s_localidad'];
$_cp = $_SESSION['s_cp'];
$_cuit = $_SESSION['s_cuit'];
$_nroIBB = $_SESSION['s_nroIBB'];
$_telefono = $_SESSION['s_telefono'];
$_correo = $_SESSION['s_correo'];
$_observacion = $_SESSION['s_observacion'];
$_activo = $_SESSION['s_activo'];
switch ($_sms) {
case 1: $_info = "El número de empresa es obligatorio."; break;
case 2: $_info = "El número de proveedor es obligatorio o ya existe."; break;
case 3: $_info = "El nombre es obligatorio."; break;
case 4: $_info = "La Dirección es obligatoria."; break;
case 5: $_info = "La Provincia es obligatoria."; break;
case 6: $_info = "La Localidad es obligatoria."; break;
case 7: $_info = "El CP es incorrecto."; break;
case 8: $_info = "El CUIT es obligatorio o incorrecto."; break;
case 9: $_info = "Por favor, introduce un e-mail correcto."; break;
case 10: $_info = "El Teléfono o Corre es obligatorio."; break;
case 11: $_info = "El Tamaño del archivo no debe superar 4MB."; break;
case 12: $_info = "Error al intentar subir el archivo."; break;
case 13: $_info = "Error al intentar eliminar el archivo."; break;
case 14: $_info = "El proveedor ya existe registrado. Controle los datos existentes y actualice."; break;
case 15: $_info = "El código de proveedor ya existe en la empresa indicada."; break;
case 16: $_info = "Complete Ingresos Brutos"; break;
//case 17: $_info = "El archivo fue eliminado."; break;
} // mensaje de error
}
if ($_provid) {
if (!$_sms) {
$_proveedor = DataManager::newObjectOfClass('TProveedor', $_provid);
$_idempresa = $_proveedor->__get('Empresa');
$_idproveedor = $_proveedor->__get('Proveedor');
$_loguin = $_proveedor->__get('Login');
$_nombre = $_proveedor->__get('Nombre');
$_direccion = $_proveedor->__get('Direccion');
$_idprovincia = $_proveedor->__get('Provincia');
$_idloc = $_proveedor->__get('Localidad');
$_cp = $_proveedor->__get('CP');
$_cuit = $_proveedor->__get('Cuit');
$_nroIBB = $_proveedor->__get('NroIBB');
$_telefono = $_proveedor->__get('Telefono');
$_correo = $_proveedor->__get('Email');
$_observacion = $_proveedor->__get('Observacion');
$_activo = $_proveedor->__get('Activo');
}
$_button = sprintf("<input type=\"submit\" id=\"btsend\" name=\"_accion\" value=\"Enviar\"/>");
$_action = "logica/update.proveedor.php?backURL=".$backURL;
} else {
//if (!$_sms) {
$_idempresa = "";
$_idproveedor = "";
$_loguin = "";
$_nombre = "";
$_direccion = "";
$_idprovincia = "";
$_idloc = "";
$_cp = "";
$_cuit = "";
$_nroIBB = "";
$_telefono = "";
$_correo = "";
$_observacion = "";
//}
$_button = sprintf("<input type=\"submit\" id=\"btsend\" name=\"_accion\" value=\"Enviar\"/>");
$_action = sprintf("logica/update.proveedor.php?provid=%d&backURL=", $_provid, $backURL);
} ?>
<!DOCTYPE html>
<html ang="es">
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
<style>
#pdf_ampliado{
overflow: hidden;
position:fixed;
display: none;
z-index: 1;
background-color: rgba(50,50,50,0.8);
display:none;
width:80%;
margin:-10px 0px 0px 0px;
padding:3%;
}
</style>
<script language="JavaScript" type="text/javascript">
function dac_ShowPdf(archivo){
$("#pdf_ampliado").empty();
campo = '<iframe src=\"https://docs.google.com/gview?url='+archivo+'&embedded=true\" style=\"width:650px; min-height:260px; height:90%;\" frameborder=\"0\"></iframe>';
$("#pdf_ampliado").append(campo);
$('#pdf_ampliado').fadeIn('slow');
$('#pdf_ampliado').css({
'width': '100%',
'height': '100%',
'left': ($(window).width() / 2 - $(img_ampliada).width() / 2) + 'px',
'top': ($(window).height() / 2 - $(img_ampliada).height() / 2) + 'px'
});
//document.getElementById("pdf_ampliado").src = src;
$(window).resize();
return false;
}
function dac_ClosePdfZoom(){
$('#pdf_ampliado').fadeOut('slow');
return false;
}
</script>
<script type="text/javascript">
function dac_ShowImgZoom(src){
$('#img_ampliada').fadeIn('slow');
$('#img_ampliada').css({
'width': '100%',
'height': '100%',
'left': ($(window).width() / 2 - $(img_ampliada).width() / 2) + 'px',
'top': ($(window).height() / 2 - $(img_ampliada).height() / 2) + 'px'
});
document.getElementById("imagen_ampliada").src = src;
$(window).resize();
return false;
}
//**********************************//
function dac_CloseImgZoom(){
$('#img_ampliada').fadeOut('slow');
return false;
}
//**********************************//
$(window).resize(function(){
$('#img_ampliada').css({
'width': '100%',
'height': '100%',
'left': ($(window).width() / 2 - $(img_ampliada).width() / 2) + 'px',
'top': ($(window).height() / 2 - $(img_ampliada).height() / 2) + 'px'
});
$('#pdf_ampliado').css({
'width': '100%',
'height': '100%',
'left': ($(window).width() / 2 - $(img_ampliada).width() / 2) + 'px',
'top': ($(window).height() / 2 - $(img_ampliada).height() / 2) + 'px'
});
});
</script>
<!-- Scripts para SUBIR ARCHIVOS -->
<script type="text/javascript" src="jquery/jquery.script.file.js"></script>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = 'proveedores';
$_subsection = '';
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<div id="img_ampliada" align="center" onclick="javascript:dac_CloseImgZoom()">
<img id="imagen_ampliada" style="width:80%; margin:10px 0px 10px 0px;"/>
</div>
<div id="pdf_ampliado" align="center" onclick="javascript:dac_ClosePdfZoom()">
<div id="pdf_amp"></div>
</div>
<div class="box_body">
<form id="fm_proveedor_edit" name="fm_proveedor_edit" method="post" action="<?php echo $_action;?>">
<fieldset >
<legend>Proveedor</legend>
<div class="bloque_1">
<?php
if ($_sms) {
if ($_sms < 17) { ?>
<fieldset id='box_error' class="msg_error" style="display:block;">
<div id="msg_error"><?php echo $_info; ?></div>
</fieldset> <?php
} else { ?>
<fieldset id='box_confirmacion' class="msg_confirmacion" style="display:block;">
<div id="msg_confirmacion"><?php echo $_info; ?></div>
</fieldset> <?php
}
} ?>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
</div>
<input type="hidden" id="provid" name="provid" value="<?php echo $_provid;?>" />
<input type="hidden" id="activo" name="activo" value="<?php echo $_activo;?>" />
<input type="hidden" name="pag" value="<?php echo $_pag;?>" />
<div class="bloque_5">
<label for="idempresa">Empresa *</label>
<select id="idempresa" name="idempresa" ><?php
$empresas = DataManager::getEmpresas(1);
if (count($empresas)) {
foreach ($empresas as $k => $emp) {
$idEmp = $emp["empid"];
$nombreEmp = $emp["empnombre"];
if ($idEmp == $_idempresa){ $selected="selected";
} else { $selected=""; } ?>
<option id="<?php echo $idEmp; ?>" value="<?php echo $idEmp; ?>" <?php echo $selected; ?>><?php echo $nombreEmp; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<label for="loguin">Usuario</label>
<input name="loguin" type="text" value="<?php echo $_loguin; ?>" disabled >
</div>
<div class="bloque_7">
<br>
<?php echo $_button; ?>
</div>
<hr>
<div class="bloque_7">
<label for="idproveedor">Id Proveedor</label>
<input name="idproveedor" id="idproveedor" type="text" maxlength="10" value="<?php echo $_idproveedor; ?>">
</div>
<div class="bloque_5">
<label for="nombre">Proveedor</label>
<input name="nombre" id="nombre" type="text" maxlength="50" value="<?php echo $_nombre;?>">
</div>
<div class="bloque_7">
<label for="cuit">CUIT</label>
<input name="cuit" id="cuit" type="text" maxlength="13" value="<?php echo $_cuit;?>">
</div>
<div class="bloque_7">
<label for="nroIBB">Nro. IBB</label>
<input name="nroIBB" id="nroIBB" type="text" maxlength="13" value="<?php echo $_nroIBB;?>"/>
</div>
<div class="bloque_6">
<label for="idprovincia">Provincia</label>
<select id="idprovincia" name="idprovincia"/>
<option value="0" selected> Provincia... </option> <?php
$provincias = DataManager::getProvincias();
if (count($provincias)) {
$idprov = 0;
foreach ($provincias as $k => $prov) {
if ($_idprovincia == $prov["provid"]){
$selected = "selected";
} else {
$selected = "";
} ?>
<option id="<?php echo $prov["provid"]; ?>" value="<?php echo $prov["provid"]; ?>" <?php echo $selected; ?>><?php echo $prov["provnombre"]; ?></option> <?php
}
} ?>
</select>
</div>
<div class="bloque_6">
<label for="idloc">Localidad</label>
<input name="idloc" id="idloc" type="text" maxlength="30" value="<?php echo $_idloc;?>"/>
</div>
<div class="bloque_5">
<label for="direccion">Dirección</label>
<input name="direccion" id="direccion" type="text" maxlength="50" value="<?php echo $_direccion;?>"/>
</div>
<div class="bloque_7">
<label for="cp">Cod Postal</label>
<input name="cp" id="cp" type="text" maxlength="10" value="<?php echo $_cp;?>"/>
</div>
<div class="bloque_7">
<label for="telefono">Teléfono</label>
<input name="telefono" id="telefono" type="text" maxlength="20" value="<?php echo $_telefono;?>" />
</div>
<div class="bloque_5">
<label for="correo">Correo</label>
<input name="correo" id="correo" type="text" maxlength="50" value="<?php echo $_correo;?>"/>
</div>
<div class="bloque_5">
<label for="observacion">Observación</label>
<textarea name="observacion" id="observacion" type="text" onkeyup="javascript:dac_LimitaCaracteres(event, 'observacion', 200);" onkeydown="javascript:dac_LimitaCaracteres(event, 'observacion', 200);" value="<?php echo $_observacion;?>"/><?php echo $_observacion;?></textarea>
</div>
</fieldset>
<fieldset>
<legend>Documentación</legend>
<div class="bloque_1">
<div class="lista"> <?php
$ruta = $_SERVER['DOCUMENT_ROOT'].'/pedidos/login/registrarme/archivos/proveedor/'.$_provid."/";
$data = dac_listar_directorios($ruta);
if($data){ ?>
<table name="tblTablaFact" border="0" width="100%" align="center">
<thead>
<tr align="left">
<th>Subido</th>
<th>Archivo</th>
<th>Imagen</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php
$fila = 0;
// $zonas = explode(", ", $_SESSION["_usrzonas"]);
foreach ($data as $file => $timestamp) {
$fila = $fila + 1;
(($fila % 2) == 0)? $clase="par" : $clase="impar";
$extencion = explode(".", $timestamp);
$ext = $extencion[1];
$name = explode("-", $timestamp, 4);
$archivo = trim($name[3]);
$_eliminar = sprintf ("<a href=\"logica/eliminar.archivo.php?provid=%d&backURL=%s&archivo=%s\" title=\"Eliminar\" onclick=\"return confirm('¿Está seguro que desea ELIMINAR EL ARCHIVO?')\"> <img class=\"icon-delete\"/></a>", $_provid, $_SERVER['PHP_SELF'], $archivo, "Eliminar");
if($ext == "pdf"){ ?>
<tr class="<?php echo $clase;?>">
<td><?php echo $name[0]."/".$name[1]."/".$name[2]; ?></td>
<td><?php echo $name[3]; ?></td>
<td align="center">
<a href='<?php echo "../login/registrarme/archivos/proveedor/".$_provid."/".$archivo; ?>' target="_blank">
<img id="imagen" class="icon-pdf"/>
</a>
</td>
<td><?php echo $_eliminar;?></td>
</tr> <?php
} else{ ?>
<tr class="<?php echo $clase;?>">
<td><?php echo $name[0]."/".$name[1]."/".$name[2]; ?></td>
<td><?php echo $name[3]; ?></td>
<td align="center">
<img id="imagen" src="<?php echo "../login/registrarme/archivos/proveedor/".$_provid."/".$archivo; ?>" onclick="javascript:dac_ShowImgZoom(this.src)" height="100px"/>
</td>
<td><?php echo $_eliminar;?></td>
</tr><?php
}
} ?>
</tbody>
</table> <?php
} else {?>
<table name="tblDocum" border="0" width="100%" align="center">
<tr>
<td colspan="4"><?php echo " No hay documentación disponible"; ?></td>
</tr>
</table><?php
}?>
</div>
</div>
<div class="bloque_5">
<input id="archivo" name="archivo" class="file" type="file"/>
</div>
<div class="bloque_8">
<input type="button" id="btfile_send" value="Subir">
</div>
</fieldset>
</form>
</div>
<div class="box_seccion"> <?php
$_origen = 'TProveedor';
$_idorigen = $_provid;
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.accord.php"); ?>
</div> <!-- fin boxbody menu -->
<hr>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html>
<file_sep>/rendicion/logica/ajax/enviar.rendicion.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$_nro_rendicion = $_REQUEST['nro_rendicion'];
//******************//
// CONTROL //
//******************//
//Controlo que los recibos cargados sean consecutivos para aceptar el envío
/*$_detrendiciones = DataManager::getDetalleRendicion($_SESSION["_usrid"], $_nro_rendicion);
if (count($_detrendiciones)) {
$_talAnt = 0;
$_recAnt = 0;
foreach ($_detrendiciones as $k => $_detrend){
$_detrend = $_detrendiciones[$k];
$_rendTal = $_detrend['Tal'];
$_rendRnro = $_detrend['RNro'];
if($_talAnt == 0){$_talAnt = $_rendTal;}
if($_recAnt == 0){$_recAnt = $_rendRnro - 1;}
if ($_talAnt == $_rendTal){
if ($_recAnt != ($_rendRnro - 1)){
echo "El Talonario: $_rendTal - Recibo: ".($_rendRnro - 1).", no fue ingresado para enviar la rendición."; exit;
}
}else{
$_talAnt = $_rendTal;
if ($_recAnt != ($_rendRnro - 1)){
echo "2_ El Talonario: $_rendTal - Recibo: ".($_rendRnro - 1).", no fue ingresado para enviar la rendición."; exit;
}
}
}
}*/
//*******************************************
// PARA GRABAR LA FECHA DE ENVÍO
//*******************************************
//Consultar si la rendición fue enviada.
$_rendiciones = DataManager::getRendicion($_SESSION["_usrid"], $_nro_rendicion, '1');
if (count($_rendiciones)){
foreach ($_rendiciones as $k => $_rendicion) {
$_rendid = $_rendicion['rendid'];
$_rendicionbject= DataManager::newObjectOfClass('TRendicion', $_rendid);
$_rendicionbject->__set('Envio', date('Y-m-d'));
$_rendicionbject->__set('Activa', 0);
$ID = DataManager::updateSimpleObject($_rendicionbject);
//**********************************//
// CORREO para notificar el envío
//**********************************//
if ($ID){
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = $_SESSION["_usremail"];
$mail->FromName = "Vendedor: ".$_SESSION["_usrname"];
$mail->Subject = "Rendicion de Cobranza Nro. ".$_nro_rendicion;
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
$_total= '
<html>
<head>
<title>Notificación de Envío</title>
<style type="text/css"> <!--
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 350px;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 0px;
}
.saludo {
width: 250px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
} -->
</style>
</head>
<body>
<table width="600" border="0" align="center">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<p>
<div class="texto" style="width:500px">
<font face="Geneva, Arial, Helvetica, sans-serif" size="2">
Estimad@, se envían los datos de <strong>RENDICIÓN DE COBRANZAS Nro $_nro_rendicion</strong> de ".$_SESSION["_usrname"]."
</font>
</div>
</p>
<div class="texto" align="center">
<p>
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con el Administrador de la Web del Sector de Sistemas al 4555-3366 de lunes a viernes de 10 a 17.00 horas o por email escribiendo a: <a href="mailto:<EMAIL>"><EMAIL></a>
</font>
</p>
</div>
</td>
</tr>
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo">Los Saludamos atentamente,<br />
Dpto. de Sistemas - NEO FARMA S.A.
</div>
</td>
</tr>
<tr align="right">
<td valign="top">'.$pie.'</td>
</tr>
</table>
</body>
</html>
';
$mail->msgHTML($_total);
$mail->AddAddress("<EMAIL>", "Rendicion de Cobranza Nro. $_nro_rendicion");
$mail->AddCC("<EMAIL>", "Rendicion de Cobranza Nro. $_nro_rendicion");
$mail->AddCC("<EMAIL>", "Rendicion de Cobranza Nro. $_nro_rendicion");
//$mail->AddAddress("<EMAIL>", "Rendicion de Cobranza Nro. $_nro_rendicion");
if(!$mail->Send()) {
echo 'Rendición enviada, pero falló la notificación del envío'; exit;
} else {
echo "1"; exit;
}
}
}
} else {
echo "No puede enviar la rendición porque ya fue enviada con anterioridad."; exit;
}
?>
<file_sep>/usuarios/password/index.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="P" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
?>
<!DOCTYPE html>
<html lang='es'>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = '';
$_subsection = '';
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav>
<main class="cuerpo">
<?php include "editar.php"; ?>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/relevamiento/jquery/jquery.enviar.js
$(document).ready(function() {
$("#btsend").click(function () { // desencadenar evento cuando se hace clic en el botón
var form = "form#fm_rel_edit";
var url = "/pedidos/relevamiento/logica/update.relevamiento.php";
var urlBack = "/pedidos/relevamiento/";
dac_sendForm(form, url, urlBack);
return false;
});
});<file_sep>/transfer/logica/exportar.historial.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=PedidosTransfers-".date('d-m-y').".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos (Pedidos Transfers) .::</TITLE>
<head></head>
<body>
<table border="0">
<thead>
<tr>
<td scope="col" width="10px">Fecha</td>
<td scope="col" width="10px">Transfer</td>
<td scope="col" width="40px">Cliente NEO</td>
<td scope="col" width="40px">Cliente Drog</td>
<td scope="col" width="40px">Nombre</td>
<td scope="col" width="40px">Domicilio</td>
</tr>
</thead>
<?php
$_transfers_recientes = DataManager::getTransfersVendedorXLS(0, $_SESSION["_usrid"]);
for( $k=0; $k < count($_transfers_recientes); $k++ ){
$_transfer_r = $_transfers_recientes[$k];
$fecha = explode(" ", $_transfer_r["ptfechapedido"]);
list($ano, $mes, $dia) = explode("-", $fecha[0]);
$_fecha = $dia."-".$mes."-".$ano;
$_nropedido = $_transfer_r["ptidpedido"];
$_clienteneo= empty($_transfer_r["ptidclineo"]) ? "" : $_transfer_r["ptidclineo"] ;
$_clientedrog= $_transfer_r["ptnroclidrog"];
$_nombre = $_transfer_r["ptclirs"];
$_domicilio = $_transfer_r["ptdomicilio"];
echo sprintf("<tr>");
echo sprintf("<td align=\"left\">%s</td><td align=\"left\">%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>", $_fecha, $_nropedido, $_clienteneo, $_clientedrog, $_nombre, $_domicilio);
echo sprintf("</tr>");
}
?>
</table>
</body>
</html>
<file_sep>/condicionpago/logica/update.condicion.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo "SESIÓN CADUCADA."; exit;
}
$condId = (isset($_POST['condid'])) ? $_POST['condid'] : NULL;
$codigo = (isset($_POST['condcodigo'])) ? $_POST['condcodigo'] : NULL;
$condTipo = (isset($_POST['condtipo'])) ? $_POST['condtipo'] : NULL;
$condCuotas = (isset($_POST['condcuotas'])) ? $_POST['condcuotas'] : NULL;
$condDecrece= (isset($_POST['conddecrece'])) ? $_POST['conddecrece'] : NULL;
if (empty($condTipo)) {
echo "Debe indicar un tipo de condición."; exit;
}
for($k=1; $k <= 5; $k++){
$condTipos[$k] = (isset($_POST["condtipo$k"])) ? $_POST["condtipo$k"] : NULL;
$condDias[$k] = (isset($_POST["conddias$k"])) ? $_POST["conddias$k"] : NULL;
$condPorcentajes[$k]= (isset($_POST["condporcentaje$k"])) ? $_POST["condporcentaje$k"] : NULL;
$condSignos[$k] = (isset($_POST["condsigno$k"])) ? $_POST["condsigno$k"] : NULL;
$condFechasDec[$k] = (isset($_POST["condfechadec$k"])) ? $_POST["condfechadec$k"] : NULL;
if(!empty($condTipos[$k])){
if(empty($condDias[$k]) && $condDias[$k] != 0){
echo "Debe indicar los días en cada condición."; exit;
}
if($condDecrece == 'S'){
if(!empty($condFechasDec[$k])){
//calcular días que restan
$dateFrom = new DateTime();
$dateTo = new DateTime(dac_invertirFecha($condFechasDec[$k]));
$dateFrom->setTime($dateTo->format('H'), $dateTo->format('m'), $dateTo->format('s'));
if($dateTo < $dateFrom){
echo "La fecha ".$condFechasDec[$k]." debe ser mayor al día de hoy."; exit;
}
$dateFrom ->modify('-1 day');
$interval = $dateFrom->diff($dateTo);
if($interval->format('%R%a') != $condDias[$k]){
echo "Los días para la fecha ".$condFechasDec[$k]." son incorrectos. <br> Deberían ser ".$interval->format('%R%a')." días."; exit;
}
} else {
echo "Debe indicar días y fecha para cada condición que cree."; exit;
}
} else {
if(!empty($condFechasDec[$k])){
echo "Debe indicar la opción Decrece en S si desea usar fechas."; exit;
}
}
} else {
if(!empty($condDias[$k]) || !empty($condPorcentajes[$k]) || !empty($condSignos[$k]) || !empty($condFechasDec[$k])){
echo "Debe indicar un tipo de condición para el día ".$condDias[$k]; exit;
}
}
$condTipos[$k] = ($condTipos[$k]) ? $condTipos[$k] : 0;
$condDias[$k] = ($condDias[$k]) ? $condDias[$k] : 0;
$condSignos[$k] = ($condSignos[$k]) ? $condSignos[$k] : '';
$condPorcentajes[$k]= ($condPorcentajes[$k])? $condPorcentajes[$k] : '0.00';
$condFechasDec[$k] = ($condFechasDec[$k]) ? $condFechasDec[$k] : '01-01-2001';
}
//controlar que se cargue al menos una condición
if(count(array_unique(array_filter($condTipos))) == 0){
echo "Debe completar al menos una condición."; exit;
}
//buscar días repetidos
if(count(array_filter($condDias)) != count(array_unique(array_filter($condDias)))){
echo "Existen días repetidos."; exit;
}
//Controlar si ya existe dicha condición de pago
$cont = 0;
$condiciones = DataManager::getCondicionesDePago();
if(count($condiciones)){
foreach($condiciones as $k => $condicion) {
if( $condTipo == $condicion['condtipo']
&& $condTipos[1] == $condicion['condtipo1']
&& $condTipos[2] == $condicion['condtipo2']
&& $condTipos[3] == $condicion['condtipo3']
&& $condTipos[4] == $condicion['condtipo4']
&& $condTipos[5] == $condicion['condtipo5']
&& $condDias[1] == $condicion['Dias1CP']
&& $condDias[2] == $condicion['Dias2CP']
&& $condDias[3] == $condicion['Dias3CP']
&& $condDias[4] == $condicion['Dias4CP']
&& $condDias[5] == $condicion['Dias5CP']
&& $condPorcentajes[1] == $condicion['Porcentaje1CP']
&& $condPorcentajes[2] == $condicion['Porcentaje2CP']
&& $condPorcentajes[3] == $condicion['Porcentaje3CP']
&& $condPorcentajes[4] == $condicion['Porcentaje4CP']
&& $condPorcentajes[5] == $condicion['Porcentaje5CP']
){
$cont++;
}
}
if($condId){
if($cont > 1){echo "La condición de pago ya existe"; exit;}
} else {
if($cont > 0){echo "La condición de pago ya existe"; exit;}
}
}
//busca un código de condiciones de pago disponible
if(!$condId) {
$condicionesPago = DataManager::getCondicionesDePago();
foreach($condicionesPago as $k => $condPago){
$codigos[] = $condPago['IdCondPago'];
}
//busca valores intermedios perdidos
$arrayRange = range(1,max($codigos));
$missingValues = array_diff($arrayRange, $codigos);
if(count($missingValues)){
reset($missingValues);
$codigo = reset($missingValues); //$missingValues[0];
} else {
$codigo = max($codigos) + 1;
}
}
$condObject = ($condId) ? DataManager::newObjectOfClass('TCondicionPago', $condId) : DataManager::newObjectOfClass('TCondicionPago');
$condObject->__set('Codigo' , $codigo);
$condObject->__set('Tipo' , $condTipo);
$condObject->__set('Tipo1' , $condTipos[1]);
$condObject->__set('Tipo2' , $condTipos[2]);
$condObject->__set('Tipo3' , $condTipos[3]);
$condObject->__set('Tipo4' , $condTipos[4]);
$condObject->__set('Tipo5' , $condTipos[5]);
$condObject->__set('Nombre' , DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condTipos[1]));
$condObject->__set('Nombre2' , DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condTipos[2]));
$condObject->__set('Nombre3' , DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condTipos[3]));
$condObject->__set('Nombre4' , DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condTipos[4]));
$condObject->__set('Nombre5' , DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $condTipos[5]));
$condObject->__set('Dias' , $condDias[1]);
$condObject->__set('Dias2' , $condDias[2]);
$condObject->__set('Dias3' , $condDias[3]);
$condObject->__set('Dias4' , $condDias[4]);
$condObject->__set('Dias5' , $condDias[5]);
$condObject->__set('Porcentaje' , $condPorcentajes[1]);
$condObject->__set('Porcentaje2',$condPorcentajes[2]);
$condObject->__set('Porcentaje3',$condPorcentajes[3]);
$condObject->__set('Porcentaje4',$condPorcentajes[4]);
$condObject->__set('Porcentaje5',$condPorcentajes[5]);
$condObject->__set('Signo' , $condSignos[1]);
$condObject->__set('Signo2' , $condSignos[2]);
$condObject->__set('Signo3' , $condSignos[3]);
$condObject->__set('Signo4' , $condSignos[4]);
$condObject->__set('Signo5' , $condSignos[5]);
$condObject->__set('Cuotas' , ($condCuotas) ? 'S' : 'N');
$condObject->__set('Cantidad' , ($condCuotas) ? $condCuotas : 0);
$condObject->__set('Decrece' , $condDecrece);
$condObject->__set('FechaFinDec', dac_invertirFecha($condFechasDec[1]));
$condObject->__set('FechaFinDec2', dac_invertirFecha($condFechasDec[2]));
$condObject->__set('FechaFinDec3', dac_invertirFecha($condFechasDec[3]));
$condObject->__set('FechaFinDec4', dac_invertirFecha($condFechasDec[4]));
$condObject->__set('FechaFinDec5', dac_invertirFecha($condFechasDec[5]));
$condObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$condObject->__set('Update' , date("Y-m-d"));
if ($condId) {
DataManagerHiper::updateSimpleObject($condObject, $condId);
DataManager::updateSimpleObject($condObject);
//REGISTRA MOVIMIENTO
$movTipo = 'UPDATE';
} else {
$condObject->__set('UsrCreated' , $_SESSION["_usrid"]);
$condObject->__set('Created' , date("Y-m-d"));
$condObject->__set('ID' , $condObject->__newID());
$condObject->__set('Activa' , 1);
DataManagerHiper::_getConnection('Hiper'); //Controla conexión a HiperWin
$ID = DataManager::insertSimpleObject($condObject);
DataManagerHiper::insertSimpleObject($condObject);
//REGISTRA MOVIMIENTO
$movTipo = 'INSERT';
$condId = $ID;
}
$movimiento = 'CONDICION_PAGO';
dac_registrarMovimiento($movimiento, $movTipo, "TCondicionPago", $condId);
echo "1"; exit;
?><file_sep>/includes/header.inc.php
<?php
$_img = "/pedidos/images/logo/logosHeaderWeb.png";
if (!empty($_SESSION['_usrname'])) {
if ($_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="A"){
if(isset($_SESSION["_usrzonas"])){
$TOPRight[] = sprintf("<span>%s - ( %s )</span>", $_SESSION["_usrname"], substr($_SESSION["_usrzonas"], 0, 15));
} else {
$TOPRight[] = sprintf("<span>%s</span>", $_SESSION["_usrname"]);
}
} else {
$TOPRight[] = sprintf("<span>%s</span>", $_SESSION["_usrname"]);
}
}
$TOPRight[] = sprintf("<span>%s</span>", infoFecha());
$TOPRightNav = implode(" | ", $TOPRight);
?>
<div id="top2" align="center">
<a href="/pedidos/index.php" title="Extranet">
<img id="img_cabecera" src="<?php echo $_img;?>" alt="pedidos"/>
</a>
</div>
<div id="top" align="center">
<div id="topcenter" align="center"><?php echo $TOPRightNav;?></div>
</div>
<file_sep>/includes/class/class.bonificacion.php
<?php
require_once('class.PropertyObject.php');
class TBonificacion extends PropertyObject {
protected $_tablename = 'bonificacion';
protected $_fieldid = 'bonifid';
protected $_fieldactivo = 'bonifactiva';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'bonifid';
$this->propertyTable['Empresa'] = 'bonifempid';
$this->propertyTable['Articulo'] = 'bonifartid';
$this->propertyTable['Mes'] = 'bonifmes';
$this->propertyTable['Anio'] = 'bonifanio';
$this->propertyTable['Precio'] = 'bonifpreciodrog';
$this->propertyTable['Publico'] = 'bonifpreciopublico';
$this->propertyTable['Iva'] = 'bonifiva';
$this->propertyTable['Digitado'] = 'bonifpreciodigitado';
$this->propertyTable['Oferta'] = 'bonifoferta';
$this->propertyTable['1A'] = 'bonif1a';
$this->propertyTable['1B'] = 'bonif1b';
$this->propertyTable['1C'] = 'bonif1c';
$this->propertyTable['3A'] = 'bonif3a';
$this->propertyTable['3B'] = 'bonif3b';
$this->propertyTable['3C'] = 'bonif3c';
$this->propertyTable['6A'] = 'bonif6a';
$this->propertyTable['6B'] = 'bonif6b';
$this->propertyTable['6C'] = 'bonif6c';
$this->propertyTable['12A'] = 'bonif12a';
$this->propertyTable['12B'] = 'bonif12b';
$this->propertyTable['12C'] = 'bonif12c';
$this->propertyTable['24A'] = 'bonif24a';
$this->propertyTable['24B'] = 'bonif24b';
$this->propertyTable['24C'] = 'bonif24c';
$this->propertyTable['36A'] = 'bonif36a';
$this->propertyTable['36B'] = 'bonif36b';
$this->propertyTable['36C'] = 'bonif36c';
$this->propertyTable['48A'] = 'bonif48a';
$this->propertyTable['48B'] = 'bonif48b';
$this->propertyTable['48C'] = 'bonif48c';
$this->propertyTable['72A'] = 'bonif72a';
$this->propertyTable['72B'] = 'bonif72b';
$this->propertyTable['72C'] = 'bonif72c';
$this->propertyTable['Activa'] = 'bonifactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/articulos/logica/changestock.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$id = empty($_REQUEST['id']) ? 0 : $_REQUEST['id'];
if ($id) {
$artObject = DataManager::newObjectOfClass('TArticulo', $id);
$stock = ($artObject->__get('Stock')) ? 0 : 1;
$artObject->__set('Stock', $stock);
$artObjectHiper = DataManagerHiper::newObjectOfClass('THiperArticulo', $id);
$artObjectHiper->__set('Stock', $stock);
DataManagerHiper::updateSimpleObject($artObjectHiper, $id);
DataManager::updateSimpleObject($artObject);
}
echo "1"; exit;
?><file_sep>/articulos/lista.php
<?php
$idEmpresa = isset($_REQUEST['empresa']) ? $_REQUEST['empresa'] : 1;
$idLaboratorio = isset($_REQUEST['laboratorio']) ? $_REQUEST['laboratorio'] : 1;
$activos = isset($_REQUEST['activos']) ? $_REQUEST['activos'] : 1;
$_LPP = 40;
$_pag = 0;
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/articulos/': $_REQUEST['backURL'];
$_total = DataManager::getArticulos(0, 0, '', $activos, $idLaboratorio, $idEmpresa);
$_paginas = ceil(count($_total)/$_LPP);
$_pag = isset($_REQUEST['pag']) ? min(max(1,$_REQUEST['pag']),$_paginas) : 1;
$_GOFirst = sprintf("<a class=\"icon-go-first\" href=\"%s?pag=%d&empresa=%d&laboratorio=%d&activos=%d\"></a>", $backURL, 1, $idEmpresa, $idLaboratorio, $activos);
$_GOPrev = sprintf("<a class=\"icon-go-previous\" href=\"%s?pag=%d&empresa=%d&laboratorio=%d&activos=%d\"></a>", $backURL, $_pag-1, $idEmpresa, $idLaboratorio, $activos);
$_GONext = sprintf("<a class=\"icon-go-next\" href=\"%s?pag=%d&empresa=%d&laboratorio=%d&activos=%d\"></a>", $backURL, $_pag+1, $idEmpresa, $idLaboratorio, $activos);
$_GOLast = sprintf("<a class=\"icon-go-last\" href=\"%s?pag=%d&empresa=%d&laboratorio=%d&activos=%d\"></a>", $backURL, $_paginas, $idEmpresa, $idLaboratorio, $activos);
$btnPreciosCondiciones = sprintf("<input type=\"button\" id=\"btPreciosCondiciones\" value=\"Actualizar $ Condiciones\" title=\"Actualizar Precio en Condiciones Comerciales\"/>");
$btnNuevo = sprintf( "<a class=\"icon-new\" href=\"editar.php\" title=\"Nuevo\"><img title=\"Nuevo\"/></a>");
?>
<script language="javascript" type="text/javascript">
//--------------------
// Select Articulos
function dac_selectArticulos(pag, rows, empresa, activos, laboratorio) {
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/articulos/logica/ajax/getArticulo.php',
data: { pag : pag,
rows : rows,
empresa : empresa,
activos : activos,
laboratorio : laboratorio
},
beforeSend : function () {
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
$('#box_cargando').css({'display':'none'});
if (resultado){
var tabla = resultado;
document.getElementById('tablaArticulos').innerHTML = tabla;
} else {
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
},
});
}
</script>
<div class="box_body"> <!-- datos -->
<div class="bloque_1">
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
</div>
<div class="barra">
<div class="bloque_7">
<select id="empselect" name="empselect" onchange="javascript:dac_selectArticulos(<?php echo $_pag; ?>, <?php echo $_LPP; ?>, empselect.value, actselect.value, labselect.value);"><?php
$empresas = DataManager::getEmpresas(1);
if (count($empresas)) {
foreach ($empresas as $k => $emp) {
$idemp = $emp["empid"];
$nombreEmp = $emp["empnombre"];
?><option id="<?php echo $idemp; ?>" value="<?php echo $idemp; ?>" <?php if ($idEmpresa == $idemp){ echo "selected"; } ?> ><?php echo $nombreEmp; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<select id="labselect" name="labselect" onchange="javascript:dac_selectArticulos(<?php echo $_pag; ?>, <?php echo $_LPP; ?>, empselect.value, actselect.value, labselect.value);"><?php
$laboratorios = DataManager::getLaboratorios();
if (count($laboratorios)) {
foreach ($laboratorios as $k => $lab) {
$idlab = $lab["idLab"];
$nombreLab = $lab["Descripcion"];
?><option id="<?php echo $idlab; ?>" value="<?php echo $idlab; ?>" <?php if ($idLaboratorio == $idlab){ echo "selected"; } ?> ><?php echo $nombreLab; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<select id="actselect" name="actselect" onchange="javascript:dac_selectArticulos(<?php echo $_pag; ?>, <?php echo $_LPP; ?>, empselect.value, actselect.value, labselect.value);">
<option value="1" <?php if ($activos == "1"){ echo "selected"; } ?> >Activos</option>
<option value="0" <?php if ($activos == "0"){ echo "selected"; } ?> >Inactivos</option>
</select>
</div>
<div class="bloque_8">
<?php echo $btnNuevo; ?>
</div>
<?php
echo "<script>";
echo "javascript:dac_selectArticulos($_pag, $_LPP, empselect.value, actselect.value, labselect.value)";
echo "</script>";
?>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<div id='tablaArticulos'></div>
</div> <!-- Fin listar -->
<?php
if ( $_paginas > 1 ) {
$_First = ($_pag > 1) ? $_GOFirst : " ";
$_Prev = ($_pag > 1) ? $_GOPrev : " ";
$_Last = ($_pag < $_paginas) ? $_GOLast : " ";
$_Next = ($_pag < $_paginas) ? $_GONext : " ";
echo("<table class=\"paginador\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
echo sprintf("<td>Mostrando página %d de %d</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td>", $_pag, $_paginas, $_First, $_Prev, $_Next, $_Last);
echo("</tr></table>");
} ?>
</div> <!-- Fin box body -->
<div class="box_seccion">
<div class="barra" align="center">
<?php echo $btnPreciosCondiciones; ?>
<hr>
</div> <!-- Fin barra -->
<div class="barra">
<div class="bloque_7">
<select id="selectFiltro">
<option value="artidart">Artículo</option>
<option value="artnombre">Nombre</option>
<option value="artcodbarra">EAN</option>
</select>
</div>
<div class="bloque_3">
<input id="txtFiltro" onKeyPress="if (event.keyCode==13){ dac_mostrarFiltro(selectFiltro.value, this.value);return false;}" type="search" autofocus placeholder="Buscar..."/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<div id='tablaFiltroArticulos'></div>
</div> <!-- Fin listar -->
</div> <!-- Fin box_seccion -->
<hr>
<script type="text/javascript" src="logica/jquery/jqueryFooter.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#empselect').change(function(){
dac_redirectPaginacion();
});
$('#labselect').change(function(){
dac_redirectPaginacion();
});
$('#actselect').change(function(){
dac_redirectPaginacion();
});
function dac_redirectPaginacion(){
var empresa = $('#empselect').val();
var activos = $('#actselect').val();
var laboratorio = $('#labselect').val();
var redirect = '?empresa='+empresa+'&laboratorio='+laboratorio+'&activos='+activos;
document.location.href=redirect;
}
});
</script>
<file_sep>/condicion/logica/ajax/duplicar.condicion.especial.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="A"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$condIdBonif = (empty($_POST['condid'])) ? 0 : $_POST['condid'];
if($condIdBonif== 0) {
echo "No se pudo cargar la condición comercial."; exit;
}
$dtHoy = new DateTime("now");
$dtManana = clone $dtHoy;
$dtManana->modify("+1 day");
//ULTIMO DÍA del mes de mañana
$dtFin = clone $dtManana;
$dtFin->setDate($dtFin->format('Y'), $dtFin->format('m'), $dtFin->format("t"));
//Se consultarán las condiciones comerciales tipo CONDICIONES ESPECIALES
//donde su FECHA de FIN sea mayor o igual al día de HOY
$condiciones = DataManager::getCondiciones(0, 0, '', '', '', '', '"CondicionEspecial"', '', $dtHoy->format("Y-m-d"));
if (count($condiciones)) {
//--------------------------------------
// Consulta los artículos de la Bonif
$condBonifObject = DataManager::newObjectOfClass('TCondicionComercial', $condIdBonif);
$condBonifFechaInicio = $condBonifObject->__get('FechaInicio');
$fechaBonifInicio = new DateTime($condBonifFechaInicio);
$condBonifFechaFin = $condBonifObject->__get('FechaFin');
$fechaBonifFin = new DateTime($condBonifFechaFin);
if($fechaBonifInicio->format("Y-m-d") <= $dtHoy->format("Y-m-d") || $fechaBonifFin->format("Y-m-d") <= $dtHoy->format("Y-m-d")){
echo "La fecha de Bonificación de referencia NO puede ser menor o igual a la actual."; exit;
}
$articulosBonifCond = DataManager::getCondicionArticulos($condIdBonif);
if (count($articulosBonifCond)) {
foreach ($articulosBonifCond as $k => $detArtBonif) {
$detBonifIdArt = $detArtBonif['cartidart'];
$arrayBonifIdArt[] = $detBonifIdArt;
}
}
//---------------------------------
// Lee cada condición comercial
foreach ($condiciones as $k => $cond) {
$condId = $cond['condid'];
if ($condId) {
$condObject = DataManager::newObjectOfClass('TCondicionComercial', $condId);
$condEmpresa = $condObject->__get('Empresa');
$condLaboratorio= $condObject->__get('Laboratorio');
$condFechaInicio= $condObject->__get('FechaInicio');
$fechaInicio = new DateTime($condFechaInicio);
//Condición Habitual
$condCant = $condObject->__get('Cantidad');
$condB1 = $condObject->__get('Bonif1');
$condB2 = $condObject->__get('Bonif2');
$condD1 = $condObject->__get('Desc1');
$condD2 = $condObject->__get('Desc2');
if($fechaInicio->format("Y-m-d") < $dtHoy->format("Y-m-d")){
$dtFinAntes = clone $fechaBonifInicio;
$dtFinAntes->modify("-1 day");
//----------------
//MODIFICO fecha FIN de condición vigente para que cierre UN DÍA ANTES DEL INICIO DE LA BONIFICACIÓN
$condObject->__set('FechaFin', $dtFinAntes->format("Y-m-d"));
DataManagerHiper::updateSimpleObject($condObject, $condId);
DataManager::updateSimpleObject($condObject);
//----------------
//CLONO EL OBJETO PARA DUPLICAR
$condObjectDup = DataManager::newObjectOfClass('TCondicionComercial');
$condObjectDup->__set('Empresa' , $condEmpresa);
$condObjectDup->__set('Laboratorio' , $condLaboratorio);
$condObjectDup->__set('Cuentas' , $condObject->__get('Cuentas'));
$condObjectDup->__set('Nombre' , $condObject->__get('Nombre'));
$condObjectDup->__set('Tipo' , $condObject->__get('Tipo'));
$condObjectDup->__set('CondicionPago' , $condObject->__get('CondicionPago'));
$condObjectDup->__set('CantidadMinima' , $condObject->__get('CantidadMinima'));
$condObjectDup->__set('MinimoReferencias' , $condObject->__get('MinimoReferencias'));
$condObjectDup->__set('MinimoMonto' , $condObject->__get('MinimoMonto'));
$condObjectDup->__set('Observacion' , $condObject->__get('Observacion'));
$condObjectDup->__set('Cantidad' , $condCant);
$condObjectDup->__set('Bonif1' , $condB1);
$condObjectDup->__set('Bonif2' , $condB2);
$condObjectDup->__set('Desc1' , $condD1);
$condObjectDup->__set('Desc2' , $condD2);
$condObjectDup->__set('FechaInicio' , $condBonifObject->__get('FechaInicio'));
$condObjectDup->__set('FechaFin' , $condBonifObject->__get('FechaFin'));
$condObjectDup->__set('UsrUpdate' , $_SESSION["_usrid"]);
$condObjectDup->__set('LastUpdate' , date("Y-m-d"));
$condObjectDup->__set('Activa' , 1);
$condObjectDup->__set('Lista' , $condObject->__get('Lista'));
$condObjectDup->__set('ID' , $condObjectDup->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDCondDup = DataManager::insertSimpleObject($condObjectDup);
if(!$IDCondDup){
echo "Error en el proceso de grabado de datos."; exit;
}
DataManagerHiper::insertSimpleObject($condObjectDup, $IDCondDup);
//------------------
// Cargo Artículos
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
unset($arrayIdArtDup);
foreach ($articulosCond as $k => $detArt) {
$detId = $detArt['cartid'];
$detIdart = $detArt['cartidart'];
$arrayIdArtDup[] = $detIdart;
//Si el artículo EXISTE en la bonificación, lo duplica.
if(in_array($detIdart, $arrayBonifIdArt)){
//---------------------------------
// Clono Detalle de Artículo
$condArtObjectDup = DataManager::newObjectOfClass('TCondicionComercialArt');
//modifico los datos del duplicado
$condArtObjectDup->__set('Condicion' , $IDCondDup);
$condArtObjectDup->__set('Articulo' , $detIdart);
$condArtObjectDup->__set('Precio' , $detArt['cartprecio']);
$condArtObjectDup->__set('Digitado' , $detArt['cartpreciodigitado']);
$condArtObjectDup->__set('CantidadMinima' , $detArt['cartcantmin']);
$condArtObjectDup->__set('OAM' , $detArt['cartoam']);
$condArtObjectDup->__set('Oferta' , $detArt['cartoferta']);
$condArtObjectDup->__set('Activo' , $detArt['cartactivo']);
$condArtObjectDup->__set('ID' , $condArtObjectDup->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDArt = DataManager::insertSimpleObject($condArtObjectDup);
if(!$IDArt){
echo "Error en el proceso de grabado de datos."; exit;
}
DataManagerHiper::insertSimpleObject($condArtObjectDup, $IDArt);
//-------------------------------------
// Creo Detalle de Bonificaciones
$articuloBonif = DataManager::getCondicionBonificaciones($condId, $detIdart);
if (count($articuloBonif)) {
foreach ($articuloBonif as $j => $artBonif) {
$artBonifId = $artBonif['cbid'];
//---------------------------------
// Duplico Detalle de Artículo
$condArtBonifObjectDup = DataManager::newObjectOfClass('TCondicionComercialBonif');
$condArtBonifObjectDup->__set('Condicion' , $IDCondDup);
$condArtBonifObjectDup->__set('Articulo' , $artBonif['cbidart']);
$condArtBonifObjectDup->__set('Cantidad' , $artBonif['cbcant']);
$condArtBonifObjectDup->__set('Bonif1' , $artBonif['cbbonif1']);
$condArtBonifObjectDup->__set('Bonif2' , $artBonif['cbbonif2']);
$condArtBonifObjectDup->__set('Desc1' , $artBonif['cbdesc1']);
$condArtBonifObjectDup->__set('Desc2' , $artBonif['cbdesc2']);
$condArtBonifObjectDup->__set('Activo' , $artBonif['cbactivo']);
$condArtBonifObjectDup->__set('ID' , $condArtBonifObjectDup->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDBonif = DataManager::insertSimpleObject($condArtBonifObjectDup);
if(!$IDBonif){
echo "Error en el proceso de grabado de datos."; exit;
}
DataManagerHiper::insertSimpleObject($condArtBonifObjectDup, $IDBonif);
}
}
}
}
//Recorro el array de la bonificación
for ($i = 0; $i < count($arrayBonifIdArt); $i++) {
//si el artículo se encuentra en la bonififcación y no en el duplicado, se insertará en la condicion duplicada
if(!in_array($arrayBonifIdArt[$i], $arrayIdArtDup)){
//---------------------------------
// Creo Detalle de Artículo
$artPrecio = DataManager::getArticulo('artprecio', $arrayBonifIdArt[$i], $condEmpresa, $condLaboratorio);
$condArtObject = DataManager::newObjectOfClass('TCondicionComercialArt');
$condArtObject->__set('Condicion' , $IDCondDup);
$condArtObject->__set('Articulo' , $arrayBonifIdArt[$i]);
$condArtObject->__set('Precio' , $artPrecio);
$condArtObject->__set('Activo' , 1);
$condArtObject->__set('Digitado' , '0.000');
$condArtObject->__set('CantidadMinima' , '0');
$condArtObject->__set('OAM' , '');
$condArtObject->__set('Oferta' , '0');
$condArtObject->__set('ID' , $condArtObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDArt = DataManager::insertSimpleObject($condArtObject);
DataManagerHiper::insertSimpleObject($condArtObject, $IDArt);
//-----------------------------------
// Creo Detalle de Bonificaciones // Con la condicion habitual
if(!empty($condCant) && (!empty($condB1) || !empty($condB2) || !empty($condD1) || !empty($condD2))) {
$condArtBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif');
$condArtBonifObject->__set('Condicion' , $IDCondDup);
$condArtBonifObject->__set('Articulo' , $arrayBonifIdArt[$i]);
$condArtBonifObject->__set('Cantidad' , $condCant);
$condArtBonifObject->__set('Bonif1' , $condB1);
$condArtBonifObject->__set('Bonif2' , $condB2);
$condArtBonifObject->__set('Desc1' , $condD1);
$condArtBonifObject->__set('Desc2' , $condD2);
$condArtBonifObject->__set('Activo' , 1);
$condArtBonifObject->__set('ID' , $condArtBonifObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDBonif = DataManager::insertSimpleObject($condArtBonifObject);
if(!$IDBonif){
echo "Error en el proceso de grabado de datos."; exit;
}
DataManagerHiper::insertSimpleObject($condArtBonifObject, $IDBonif);
}
}
}
}
} else {
//CONDICIONES FUTURAS planificadas,
//solo controla si hay artículos nuevos para agregar.
//---------------------
// Cargo Artículos
$articulosCond = DataManager::getCondicionArticulos($condId);
if (count($articulosCond)) {
unset($arrayIdArtDup);
foreach ($articulosCond as $k => $detArt) {
$detId = $detArt['cartid'];
$detIdart = $detArt['cartidart'];
$arrayIdArtDup[] = $detIdart;
}
//Recorro el array de la bonificación
for ($i = 0; $i < count($arrayBonifIdArt); $i++) {
//si el artículo se encuentra en la bonififcaicón y no se encuentra en el duplicado, se insertará
if(!in_array($arrayBonifIdArt[$i], $arrayIdArtDup)){
//-------------------------------
// Creo Detalle de Artículo
$artPrecio = DataManager::getArticulo('artprecio', $arrayBonifIdArt[$i], $condEmpresa, $condLaboratorio);
$condArtObject = DataManager::newObjectOfClass('TCondicionComercialArt');
//modifico los datos del duplicado
$condArtObject->__set('Condicion' , $condId);
$condArtObject->__set('Articulo' , $arrayBonifIdArt[$i]);
$condArtObject->__set('Precio' , $artPrecio);
$condArtObject->__set('Activo' , 1);
$condArtObject->__set('Digitado' , '0.000');
$condArtObject->__set('CantidadMinima' , '0');
$condArtObject->__set('OAM' , '');
$condArtObject->__set('Oferta' , '0');
$condArtObject->__set('ID' , $condArtObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDArt = DataManager::insertSimpleObject($condArtObject);
if(!$IDArt){
echo "Error en el proceso de grabado de datos."; exit;
}
DataManagerHiper::insertSimpleObject($condArtObject, $IDArt);
//**********************************//
// Creo Detalle de Bonificaciones // Con la condición habitual si existiera
if(!empty($condCant) && (!empty($condB1) || !empty($condB2) || !empty($condD1) || !empty($condD2))) {
$condArtBonifObject = DataManager::newObjectOfClass('TCondicionComercialBonif');
$condArtBonifObject->__set('Condicion' , $condId);
$condArtBonifObject->__set('Articulo' , $arrayBonifIdArt[$i]);
$condArtBonifObject->__set('Cantidad' , $condCant);
$condArtBonifObject->__set('Bonif1' , $condB1);
$condArtBonifObject->__set('Bonif2' , $condB2);
$condArtBonifObject->__set('Desc1' , $condD1);
$condArtBonifObject->__set('Desc2' , $condD2);
$condArtBonifObject->__set('Activo' , 1);
$condArtBonifObject->__set('ID' , $condArtBonifObject->__newID());
DataManagerHiper::_getConnection('Hiper');
$IDBonif = DataManager::insertSimpleObject($condArtBonifObject);
if(!$IDBonif){
echo "Error en el proceso de grabado de datos."; exit;
}
DataManagerHiper::insertSimpleObject($condArtBonifObject, $IDBonif);
}
}
}
}
}
// Registro MOVIMIENTO
$movimiento = 'DUPLICA_ID_'.$condId;
dac_registrarMovimiento($movimiento, "INSERT", 'TCondicionComercial', $condId);
} else {
echo "Error al consultar los registros."; exit;
}
}
echo "1"; exit;
} else {
echo "No se encontraron registros para duplicar."; exit;
}
?><file_sep>/listas/logica/update.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$id = (isset($_POST['id'])) ? $_POST['id'] : NULL;
$nombre = (isset($_POST['nombre'])) ? $_POST['nombre'] : NULL;
$catComercial = (isset($_POST['categoriaComer'])) ? $_POST['categoriaComer'] : NULL;
if(empty($nombre)){
echo "Indique un nombre"; exit;
} else {
//Comprobar que nombre de cadena no exista
$cont = 0;
$nombre = mb_strtoupper(trim(str_replace(" ", " ", $nombre)),"UTF-8" );
$listas = DataManager::getListas();
foreach ($listas as $k => $list) {
$listNombre = $list['NombreLT'];
if(!strcasecmp($nombre, $listNombre)) {
$cont++;
}
}
if(empty($id)) {$cont++;}
if($cont > 1){ echo "El nombre ya existe"; exit; }
}
if($catComercial){
$catComercial = implode(",", $catComercial);
}
//-----------
$listObject = ($id) ? DataManager::newObjectOfClass('TListas', $id) : DataManager::newObjectOfClass('TListas');
$listObject->__set('Nombre' , $nombre);
$listObject->__set('CategoriaComercial', $catComercial);
if($id) {
$tipoMov = 'UPDATE';
DataManagerHiper::updateSimpleObject($listObject, $id);
DataManager::updateSimpleObject($listObject);
} else {
$tipoMov = 'INSERT';
$listObject->__set('ID' , $listObject->__newID());
$listObject->__set('Activa' , 0);
DataManagerHiper::_getConnection('Hiper'); //Controla conexión a HiperWin
$id = DataManager::insertSimpleObject($listObject);
DataManagerHiper::insertSimpleObject($listObject, $id);
}
$movimiento = 'ListadePrecios_'.$nombre;
// MOVIMIENTO CADENA
dac_registrarMovimiento($movimiento, $tipoMov, "TListas", $id);
echo 1; exit;
?><file_sep>/pedidos/logica/ajax/getCondicionesPago.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo '<table><tr><td align="center">SU SESION HA EXPIRADO.</td></tr></table>'; exit;
}
$condiciones = (!empty($_POST['condicion'])) ? $_POST['condicion'] : '';
$listaCondiciones = empty($condiciones) ? 0 : explode(",", $condiciones);
//------------------------------//
// Cargo condiciones de pago //
$condicionesPago = DataManager::getCondicionesDePago(0, 100, 1);
if (count($condicionesPago)) {
foreach ($condicionesPago as $k => $cond) {
$idCond = $cond['condid'];
$condCodigo = $cond['IdCondPago'];
$condNombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $cond['condtipo']);
$condDias = "(";
$condDias .= empty($cond['Dias1CP']) ? '0' : $cond['Dias1CP'];
$condDias .= empty($cond['Dias2CP']) ? '' : ', '.$cond['Dias2CP'];
$condDias .= empty($cond['Dias3CP']) ? '' : ', '.$cond['Dias3CP'];
$condDias .= empty($cond['Dias4CP']) ? '' : ', '.$cond['Dias4CP'];
$condDias .= empty($cond['Dias5CP']) ? '' : ', '.$cond['Dias5CP'];
$condDias .= " Días)";
$condDias .= ($cond['Porcentaje1CP'] == '0.00') ? '' : ' '.$cond['Porcentaje1CP'].' %';
$selected = (in_array($condCodigo, $listaCondiciones)) ? 1 : 0 ;
/*if($listaCondiciones) {
for ($i = 0; $i < count($listaCondiciones); $i++) {
if($condCodigo == $listaCondiciones[$i]){
$_datos[] = array(
"condcodigo"=> $condCodigo,
"nombre" => $condNombre,
"dias" => $condDias,
"porc" => $condPorc
);
}
}
} else {*/
$_datos[] = array (
"condcodigo"=> $condCodigo,
"nombre" => $condNombre,
"dias" => $condDias,
"selected" => $selected
);
//}
}
$objJason = json_encode($_datos);
echo $objJason;
} else {
echo "Error al cargar condiciones de pago"; exit;
}
?><file_sep>/cuentas/logica/update.cuenta.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M") {
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$ctaId = (isset($_POST['ctaid'])) ? $_POST['ctaid'] : NULL;
$tipo = (isset($_POST['tiposelect'])) ? $_POST['tiposelect'] : NULL;
$idCuenta = (isset($_POST['idCuenta'])) ? $_POST['idCuenta'] : NULL;
$empresa = (isset($_POST['empselect'])) ? $_POST['empselect'] : NULL;
$estado = (isset($_POST['estado'])) ? $_POST['estado'] : NULL;
$nombre = (isset($_POST['nombre'])) ? $_POST['nombre'] : NULL;
$asignado = (isset($_POST['asignado'])) ? $_POST['asignado'] : NULL;
$zona = (isset($_POST['zona'])) ? $_POST['zona'] : NULL;
$ruteo = (isset($_POST['ruteo'])) ? $_POST['ruteo'] : NULL;
$empleados = (isset($_POST['empleados'])) ? $_POST['empleados'] : NULL;
$cuit = (isset($_POST['cuit'])) ? $_POST['cuit'] : NULL;
$categoriaComercial = (isset($_POST['categoriaComer'])) ? $_POST['categoriaComer']: NULL;
$categoriaIVA = (isset($_POST['categoriaIva'])) ? $_POST['categoriaIva']: NULL;
$condicionPago = (isset($_POST['condicionPago'])) ? $_POST['condicionPago'] : NULL;
$agenteRetPerc = (isset($_POST['agenteRetPerc'])) ? $_POST['agenteRetPerc'] : NULL;
$telefono = (isset($_POST['telefono'])) ? $_POST['telefono'] : NULL;
$direccionEntrega = (isset($_POST['direccionEntrega'])) ? $_POST['direccionEntrega'] : NULL;
$correo = (isset($_POST['correo'])) ? $_POST['correo'] : NULL;
$web = (isset($_POST['web'])) ? $_POST['web'] : NULL;
$observacion = (isset($_POST['observacion'])) ? $_POST['observacion']: NULL;
$imagen1 = (isset($_POST['nombreFrente'])) ? $_POST['nombreFrente']: NULL;
$imagen2 = (isset($_POST['nombreInterior'])) ? $_POST['nombreInterior'] : NULL;
//Domicilio
$provincia = (isset($_POST['provincia'])) ? $_POST['provincia'] : NULL;
$localidad = (isset($_POST['localidad'])) ? $_POST['localidad'] : NULL;
$direccion = (isset($_POST['direccion'])) ? $_POST['direccion'] : NULL;
$nro = (isset($_POST['nro'])) ? $_POST['nro'] : NULL;
$piso = (isset($_POST['piso'])) ? $_POST['piso'] : NULL;
$dpto = (isset($_POST['dpto'])) ? $_POST['dpto'] : NULL;
$cp = (isset($_POST['codigopostal'])) ? $_POST['codigopostal']: NULL;
$longitud = (isset($_POST['longitud'])) ? $_POST['longitud'] : NULL;
$latitud = (isset($_POST['latitud'])) ? $_POST['latitud'] : NULL;
//Retenciones y Percepciones
$categIva = (isset($_POST['categoriaIva'])) ? $_POST['categoriaIva'] : NULL;
$agenteRetPerc = (isset($_POST['agenteRetPerc'])) ? $_POST['agenteRetPerc'] : NULL;
$ctoCompras = (isset($_POST['ctoCompras'])) ? $_POST['ctoCompras'] : NULL;
$ctoImpositivo = (isset($_POST['ctoImpositivo'])) ? $_POST['ctoImpositivo'] : NULL;
$ctoCobranza = (isset($_POST['ctoCobranza'])) ? $_POST['ctoCobranza'] : NULL;
$ctoRecExp = (isset($_POST['ctoRecExp'])) ? $_POST['ctoRecExp'] : NULL;
$cadena = (isset($_POST['cadena'])) ? $_POST['cadena'] : NULL;
$tipoCadena = (isset($_POST['tipoCadena'])) ? $_POST['tipoCadena'] : NULL;
$tipoCadenaNombre = ($tipoCadena == 1) ? 'Sucursal' : '';
$nroIngBrutos = (isset($_POST['nroIngBrutos'])) ? $_POST['nroIngBrutos'] : NULL;
//Arrays
$arrayCtaIdDrog = (isset($_POST['cuentaId'])) ? $_POST['cuentaId'] : NULL;
$arrayCtaCliente = (isset($_POST['cuentaIdTransfer']))? $_POST['cuentaIdTransfer'] : NULL;
$fechaAlta = (isset($_POST['fechaAlta'])) ? $_POST['fechaAlta'] : NULL;
$activa = (isset($_POST['activa'])) ? $_POST['activa'] : NULL;
$lista = (isset($_POST['listaPrecio'])) ? $_POST['listaPrecio'] : NULL;
$listaNombre = DataManager::getLista('NombreLT', 'IdLista', $lista);
//-------------------------------------
// Controles obligatorios para todos
//Un prospecto puede no estar obligado a ingresar los siguientes datos
if($tipo != "PS" && $tipo != "O"){
if(empty($asignado)){ echo "La cuenta debe tener un usuario asignado. "; exit; }
if (!dac_validarCuit($cuit)) { echo "El cuit es incorrecto."; exit; }
$cuit = dac_corregirCuit($cuit);
}
if (empty($empresa)) { echo "No se pudo cargar el dato de empresa"; exit; }
$empresaNombre = DataManager::getEmpresa('empnombre', $empresa);
if (empty($estado)) { echo "Seleccione un estado."; exit; }
if (empty($tipo)) { echo "Seleecione el tipo de cuenta."; exit; }
if(empty($nombre)){ echo "Indique la Razón Social."; exit; }
if(!empty($empleados) && !is_numeric($empleados)){ echo "Indique cantidad de empleados."; exit; }
if(!empty($categoriaIVA)){
$categoriasIva = DataManager::getCategoriasIva(1);
if (count($categoriasIva)) {
foreach ($categoriasIva as $k => $catIva) {
$catIdcat = $catIva["catidcat"];
$catNombre = $catIva["catnombre"];
if($catIdcat == $categoriaIVA){
$catIvaNombre = $catNombre;
}
}
}
}
//La zona debe corresponder a la zona relacionada a la localidad. Si no es la misma deberá solicitarlo luego como excepción para que se modifique o aclararlo en la observación para administración
if(empty($provincia) || empty($localidad) || empty($longitud) || empty($latitud)){
echo "Complete los datos de domicilio."; exit;
} else {
$zonaLocalidad = DataManager::getLocalidad('loczonavendedor', $localidad);
if($zonaLocalidad != $zona){
$nombreLocalidad = DataManager::getLocalidad('locnombre', $localidad);
echo "La zona correspondiente a la localidad $nombreLocalidad es la $zonaLocalidad. En caso de desear una diferente, deberá solicitarlo en la observación para cargar luego como excepción."; exit;
}
}
if(!empty($correo)){
$correo = trim($correo, ' ');
if (!dac_validateMail($correo)) {
echo "El corréo es incorrecto."; exit;
}
}
if(empty($correo) && empty($telefono)){ echo "Debe indicar un correo o un teléfono de contacto."; exit; }
//***************************************//
//Control de cuentas transfers cargados // //relacionadas (para droguerías transfers)
if(!empty($arrayCtaIdDrog)){
if(count($arrayCtaIdDrog)){ //$arrayCtaIdDrog = implode(",", $arrayCtaIdDrog);
for($i = 0; $i < count($arrayCtaIdDrog); $i++){
if (empty($arrayCtaCliente[$i])){
echo "Indique cliente transfer para la cuenta ".$arrayCtaIdDrog[$i]; exit;
}
}
}
//Controla Droguerías duplicadas
if(count($arrayCtaIdDrog) != count(array_unique($arrayCtaIdDrog))){
echo "Hay droguerías duplicadas."; exit;
}
}
$frenteNombre = $_FILES["frente"]["name"];
$frentePeso = $_FILES["frente"]["size"];
$interiorNombre = $_FILES["interior"]["name"];
$interiorPeso = $_FILES["interior"]["size"];
if ($frentePeso != 0){
if($frentePeso > MAX_FILE){
echo "El archivo Frente no debe superar los 4 MB"; exit;
}
}
if ($interiorPeso != 0){
if($interiorPeso > MAX_FILE){
echo "El archivo Interior no debe superar los 4 MB"; exit;
}
}
//control de otros arhivos
$hayArchivos = 0;
if (isset($_FILES['multifile'])) {
$myFiles = $_FILES['multifile'];
$fileCount = count($myFiles["name"]);
if($fileCount > 5){ echo "Demasiados archivos adjuntos"; exit; }
for ($i = 0; $i < $fileCount; $i++) {
if($myFiles['error'][$i] == UPLOAD_ERR_OK){
$hayArchivos = 1;
$nombreOriginal = $myFiles['name'][$i];
$nombreTemporal = $myFiles['tmp_name'][$i];
$peso = $myFiles['size'][$i];
if($peso > MAX_FILE){
echo "El archivo ".$nombreOriginal." no debe superar los ".(MAX_FILE / 1024)." MB"; exit;
}
if(!dac_fileFormatControl($myFiles["type"][$i], 'imagen')){
echo "El archivo ".$nombreOriginal." debe tener formato imagen o pdf."; exit;
}
}
if ($myFiles['error'][$i] != 0 && $myFiles['error'][$i] != 4){
echo 'No se pudo subir el archivo <b>'.$nombreOriginal.'</b> debido al siguiente Error: '.$myFiles['error'][$i];
}
}
}
if($tipo != 'O'){
if (empty($longitud) || empty($latitud)) { echo "Indique el domicilio correcto usando el ícono del mapa para registrar la longitud y latitud que corresponda."; exit; }
if (!empty($nro) && !is_numeric($nro)) { echo "Verifique número en la dirección de la cuenta."; exit; }
}
$provinciaNombre = DataManager::getProvincia('provnombre', $provincia);
$localidadNombre = DataManager::getLocalidad('locnombre', $localidad);
$zonaEntrega = (empty($localidad)) ? 0 : DataManager::getLocalidad('loczonaentrega', $localidad);
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
//---------------------
// TIPO DE CUENTA
$tipoDDBB = dac_consultarTipo($ctaId);
$estadoDDBB = dac_consultarEstado($idCuenta, $empresa);
//Controlo cambio tipo cuenta
dac_controlesCambioTipoCuenta($tipoDDBB, $tipo, $estadoDDBB, $estado);
switch($tipo){
// cliente //
case 'C':
case 'CT':
if($estadoDDBB == 'CambioRazonSocial' || $estadoDDBB == 'CambioDomicilio' || $estadoDDBB == 'SolicitudBaja'){
echo "La cuenta ya no puede ser modificada."; exit;
}
//Controles Generales
if(empty($zona) || $zona==199){ echo "Indique la zona del vendedor."; exit; }
if(empty($ruteo)){ echo "Indique el ruteo."; exit; }
if(empty($lista)){ echo "Indique lista de precios."; exit; }
if(empty($agenteRetPerc)){ echo "Indique si es agente de Retención/Percepción."; exit; }
if(empty($categoriaIVA)){ echo "Indique categoría de iva."; exit; }
if(empty($correo)){
echo "Debe indicar un correo"; exit;
} else {
$correo = trim($correo, ' ');
if (!dac_validateMail($correo)) {
echo "El corréo es incorrecto."; exit;
}
}
if(empty($telefono)){ echo "Debe indicar un teléfono de contacto."; exit; }
if (empty($cp) || !is_numeric($cp)) { echo "Indique código postal."; exit; }
//----------//
// CORREO //
$from = $_SESSION["_usremail"];
$fromName = "Usuario ".$_SESSION["_usrname"];
$cuerpoMail_3 = '
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con la empresa al 4555-3366 de Lunes a Viernes de 10 a 17 horas.
</font>
<div style="color:#000000; font-size:12px;">
<strong>Si no recibe información del alta en 72 horas hábiles, podrá reclamar reenviando éste mail a <EMAIL> </strong></br></br>
</div>
</div>
</td>
</tr>';
switch($estado) {
case 'SolicitudAlta':
$est = 5;
$estadoNombre = 'Solicitud de Alta';
//Busca las categorías de la lista de precios seleccionadas y consotrla que exista la condicion Comercial seleccionada en la cuenta
$categoriasListaPrecios = DataManager::getLista('CategoriaComercial', 'IdLista', $lista);
if(!empty($categoriasListaPrecios)){
$categoriasComerciales = explode(",", $categoriasListaPrecios);
if(!in_array($categoriaComercial, $categoriasComerciales)) {
$categoriaNombre = DataManager::getCategoriaComercial('catnombre', 'catidcat', $categoriaComercial);
echo "La Categoría Comercial '$categoriaComercial - $categoriaNombre' NO corresponde a la Lista de Precios '$listaNombre'"; exit;
}
}
//--------------------------------
if(dac_controlesAlta($cadena, $ctaId, $empresa, $cuit, $estadoDDBB, $zona, $tipoDDBB, $tipo)){
$idCuenta = dac_crearNroCuenta($empresa, $zona);
$fechaAlta = "2001-01-01 00:00:00";
};
$cuerpoMail_2 = '
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Usuario </th>
<td align="left" width="400"> '.utf8_decode($_SESSION["_usrname"]).' </td>
</tr>
<tr>
<th align="left" width="200">Cuenta</th>
<td align="left" width="400">'.$idCuenta.'</td>
</tr>
<tr>
<th align="left" width="200">Zona - Ruteo</th>
<td align="left" width="400">'.$zona." - ".$ruteo.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$_SESSION["_usremail"].'</td>
</tr>
<tr>
<th align="left" width="200">Fecha de pedido</th>
<td align="left" width="400">'.date("d-m-Y H:i:s").'</td>
</tr>
<tr>
<th align="left" width="200">¿Es agente de retención?</th>
<td align="left" width="400">'.$agenteRetPerc.'</td>
</tr>
<tr style="color:#FFFFFF; font-weight:bold;">
<th colspan="2" align="center">
Datos de la Cuenta
</th>
</tr>
<tr>
<th align="left" width="200">Razón Social</th>
<td align="left" width="400">'.$nombre.'</td>
</tr>
<tr>
<th align="left" width="200">Cuit</th>
<td align="left" width="400">'.$cuit.'</td>
</tr>
<tr>
<th align="left" width="200">Categoría Iva</th>
<td align="left" width="400">'.$catIvaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Lista de Precios</th>
<td align="left" width="400">'.$listaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Cadena</th>
<td align="left" width="400">'.$cadena.'</td>
</tr>
<tr>
<th align="left" width="200">Tipo Cadena</th>
<td align="left" width="400">'.$tipoCadenaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Provincia</th>
<td align="left" width="400">'.$provinciaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Localidad</th>
<td align="left" width="400">'.$localidadNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Domicilio</th>
<td align="left" width="400">'.$direccion.' '.$nro.' '.$piso.' '.$dpto.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$correo.'</td>
</tr>
<tr>
<th align="left" width="200">Teléfono</th>
<td align="left" width="400">'.$telefono.'</td>
</tr>
<tr>
<th align="left" width="200">Web</th>
<td align="left" width="400">'.$web.'</td>
</tr>
<tr>
<th align="left" width="200"> Observación </th>
<td align="left" width="400"> '.$observacion.' </td>
</tr>
<tr>
<th colspan="2" align="center">
Datos a Completar
</th>
</tr>
<tr>
<th align="left" width="200">
Habilitación<br />
Director Técnico<br />
Autorización alta
</th>
<td align="left" width="400"></td>
</tr>
</table>
</div>
</td>
</tr>
';
break;
case 'CambioRazonSocial':
$est = 8;
$estadoNombre = 'Cambio de Razón Social';
if(!$hayArchivos){
echo "Debe adjuntar documentación para ".$estadoNombre."."; exit;
}
//La cuenta pasa automáticamente a ZONA INACTIVA
$observacion2 = "BAJA por ".$estado.". del CUIT ".$cuit.". ".$observacion;
$ctaObject = DataManager::newObjectOfClass('TCuenta', $ctaId);
$ctaObject->__set('Estado' , $estado);
$ctaObject->__set('Zona' , 95);
$ctaObject->__set('Observacion' , $observacion2);
$ctaObject->__set('Activa' , 0);
$ctaObject->__set('CUIT' , '');
$ctaObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObject->__set('LastUpdate' , date("Y-m-d H:i:s"));
// Procesar BAJA en HIPERWIN
$ctaObjectHiper = DataManagerHiper::newObjectOfClass('THiperCuenta', $ctaId);
$ctaObjectHiper->__set('Estado' , $estado);
$ctaObjectHiper->__set('Zona' , 95);
$ctaObjectHiper->__set('Observacion', $observacion2);
$ctaObjectHiper->__set('Activa' , 0);
$ctaObjectHiper->__set('CUIT' , '');
$ctaObjectHiper->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObjectHiper->__set('LastUpdate' , date("Y-m-d H:i:s"));
DataManagerHiper::updateSimpleObject($ctaObjectHiper, $ctaId);
DataManager::updateSimpleObject($ctaObject);
//----------------------------
//**********//
// CORREO //
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = $from;
$mail->FromName = $fromName;
$mail->Subject = $estadoNombre." de Cuenta ".$tipo.", ".$nombre.". Guarde este email.";
$headMail = '
<html>
<head>
<title>'.$estadoNombre.' de CUENTA '.$tipo.'</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 580px;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>';
$cuerpoMail_1 = '
<body>
<div align="center">
<table width="580" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Se envían los datos de <strong>'.$estadoNombre.' de la CUENTA '.$tipo.'</strong> correspondiente a:<br/><br/>
<div />
</td >
</tr>
<tr>
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight:bold; background-color:#117db6">
<strong>Datos de la solicitud</strong>
</div>
</td>
</tr>
';
$cuerpoMail_2 = '
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Usuario </th>
<td align="left" width="400"> '.utf8_decode($_SESSION["_usrname"]).' </td>
</tr>
<tr>
<th align="left" width="200">Cuenta</th>
<td align="left" width="400">'.$idCuenta.'</td>
</tr>
<tr>
<th align="left" width="200">Zona - Ruteo</th>
<td align="left" width="400">95 - '.$ruteo.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$_SESSION["_usremail"].'</td>
</tr>
<tr>
<th align="left" width="200">Fecha de pedido</th>
<td align="left" width="400">'.date("d-m-Y H:i:s").'</td>
</tr>
<tr style="color:#FFFFFF; font-weight:bold;">
<th colspan="2" align="center">
Datos de la Cuenta
</th>
</tr>
<tr>
<th align="left" width="200">Nueva Razón Social</th>
<td align="left" width="400">'.$nombre.'</td>
</tr>
<tr>
<th align="left" width="200">Nuevo Cuit</th>
<td align="left" width="400">'.$cuit.'</td>
</tr>
<tr>
<th align="left" width="200"> Observación </th>
<td align="left" width="400"> '.$observacion.' </td>
</tr>
</table>
</div>
</td>
</tr>
';
$pieMail = ' <tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Gracias por confiar en '.$empresaNombre.'<br/>
Le saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
</html>
';
$cuerpoMail2 = $headMail.$cuerpoMail_1.$cuerpoMail_2.$cuerpoMail_3.$pieMail;
$mail->msgHTML($cuerpoMail2);
$mail->AddBCC("<EMAIL>");
$mail->AddBCC("<EMAIL>");
$mail->AddAddress($_SESSION["_usremail"], $estadoNombre.' de la cuenta '.$tipo.". Enviada");
if($mail){
if(!$mail->Send()) {
echo 'Fallo en el envío de notificación por mail'; exit;
}
}
//******************//
// Registro ESTADO //
dac_registrarEstado('TCuenta', $ctaId, $est, $tipo."_".$estado);
//**********************//
// Registro MOVIMIENTO //
$movimiento = 'CUENTA_'.$tipo;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", $ctaId);
$ctaId = 0;
//Luego de modificar la cuenta actual, el envío pasa como Solicitud de alta
$est = 5;
$estado = 'SolicitudAlta';
$estadoNombre = 'Solicitud de Alta';
if(dac_controlesAlta($cadena, $ctaId, $empresa, $cuit, 'Cuenta Nueva', $zona, $tipoDDBB, $tipo)){
$observacion= "ALTA por ".$estado.". de Cuenta ".$idCuenta.". ".$observacion;
$idCuenta = dac_crearNroCuenta($empresa, $zona);
$fechaAlta = "2001-01-01 00:00:00";
};
$cuerpoMail_2 = '
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Usuario </th>
<td align="left" width="400"> '.utf8_decode($_SESSION["_usrname"]).' </td>
</tr>
<tr>
<th align="left" width="200">Cuenta</th>
<td align="left" width="400">'.$idCuenta.'</td>
</tr>
<tr>
<th align="left" width="200">Zona - Ruteo</th>
<td align="left" width="400">'.$zona." - ".$ruteo.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$_SESSION["_usremail"].'</td>
</tr>
<tr>
<th align="left" width="200">Fecha de pedido</th>
<td align="left" width="400">'.date("d-m-Y H:i:s").'</td>
</tr>
<tr>
<th align="left" width="200">¿Es agente de retención?</th>
<td align="left" width="400">'.$agenteRetPerc.'</td>
</tr>
<tr style="color:#FFFFFF; font-weight:bold;">
<th colspan="2" align="center">
Datos de la Cuenta
</th>
</tr>
<tr>
<th align="left" width="200">Razón Social</th>
<td align="left" width="400">'.$nombre.'</td>
</tr>
<tr>
<th align="left" width="200">Cuit</th>
<td align="left" width="400">'.$cuit.'</td>
</tr>
<tr>
<th align="left" width="200">Categoría Iva</th>
<td align="left" width="400">'.$catIvaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Lista de Precios</th>
<td align="left" width="400">'.$listaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Cadena</th>
<td align="left" width="400">'.$cadena.'</td>
</tr>
<tr>
<th align="left" width="200">Tipo Cadena</th>
<td align="left" width="400">'.$tipoCadenaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Provincia</th>
<td align="left" width="400">'.$provinciaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Localidad</th>
<td align="left" width="400">'.$localidadNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Domicilio</th>
<td align="left" width="400">'.$direccion.' '.$nro.' '.$piso.' '.$dpto.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$correo.'</td>
</tr>
<tr>
<th align="left" width="200">Teléfono</th>
<td align="left" width="400">'.$telefono.'</td>
</tr>
<tr>
<th align="left" width="200">Web</th>
<td align="left" width="400">'.$web.'</td>
</tr>
<tr>
<th align="left" width="200"> Observación </th>
<td align="left" width="400"> '.$observacion.' </td>
</tr>
<tr>
<th colspan="2" align="center">
Datos a Completar
</th>
</tr>
<tr>
<th align="left" width="200">
Habilitación<br />
Director Técnico<br />
Autorización alta
</th>
<td align="left" width="400"></td>
</tr>
</table>
</div>
</td>
</tr>
';
break;
case 'CambioDomicilio':
$est = 9;
$estadoNombre = 'Cambio de Domicilio';
if(!$hayArchivos){
echo "Debe adjuntar documentación para ".$estadoNombre."."; exit;
}
//La cuenta pasa automáticamente a ZONA INACTIVA
$observacion2 = "BAJA por ".$estado.". Nueva Cuenta CUIT ".$cuit.". ".$observacion;
$ctaObject = DataManager::newObjectOfClass('TCuenta', $ctaId);
$ctaObject->__set('Estado' , $estado);
$ctaObject->__set('Zona' , 95);
$ctaObject->__set('Observacion' , $observacion2);
$ctaObject->__set('Activa' , 0);
$ctaObject->__set('CUIT' , '');
$ctaObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObject->__set('LastUpdate' , date("Y-m-d H:i:s"));
// Procesar BAJA en HIPERWIN
$ctaObjectHiper = DataManagerHiper::newObjectOfClass('THiperCuenta', $ctaId);
$ctaObjectHiper->__set('Estado' , $estado);
$ctaObjectHiper->__set('Zona' , 95);
$ctaObjectHiper->__set('Observacion', $observacion2);
$ctaObjectHiper->__set('Activa' , 0);
$ctaObjectHiper->__set('CUIT' , '');
$ctaObjectHiper->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObjectHiper->__set('LastUpdate' , date("Y-m-d H:i:s"));
DataManagerHiper::updateSimpleObject($ctaObjectHiper, $ctaId);
DataManager::updateSimpleObject($ctaObject);
//**********//
// CORREO //
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = $from;
$mail->FromName= $fromName;
$mail->Subject = $estadoNombre." de Cuenta ".$tipo.", ".$nombre.". Guarde este email.";
$headMail = '
<html>
<head>
<title>'.$estadoNombre.' de CUENTA '.$tipo.'</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 580px;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>';
$cuerpoMail_1 = '
<body>
<div align="center">
<table width="580" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Se envían los datos de <strong>'.$estadoNombre.' de la CUENTA '.$tipo.'</strong> correspondiente a:<br/><br/>
<div />
</td >
</tr>
<tr>
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight:bold; background-color:#117db6">
<strong>Datos de la solicitud</strong>
</div>
</td>
</tr>
';
$cuerpoMail_2 = '
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Usuario </th>
<td align="left" width="400"> '.utf8_decode($_SESSION["_usrname"]).' </td>
</tr>
<tr>
<th align="left" width="200">Cuenta</th>
<td align="left" width="400">'.$idCuenta.'</td>
</tr>
<tr>
<th align="left" width="200">Zona - Ruteo</th>
<td align="left" width="400">'.$zona." - ".$ruteo.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$_SESSION["_usremail"].'</td>
</tr>
<tr>
<th align="left" width="200">Fecha de pedido</th>
<td align="left" width="400">'.date("d-m-Y H:i:s").'</td>
</tr>
<tr style="color:#FFFFFF; font-weight:bold;">
<th colspan="2" align="center">
Datos de la Cuenta
</th>
</tr>
<tr>
<th align="left" width="200">Razón Social</th>
<td align="left" width="400">'.$nombre.'</td>
</tr>
<tr>
<th align="left" width="200">Cuit</th>
<td align="left" width="400">'.$cuit.'</td>
</tr>
<tr>
<th align="left" width="200">Provincia</th>
<td align="left" width="400">'.$provinciaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Localidad</th>
<td align="left" width="400">'.$localidadNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Domicilio</th>
<td align="left" width="400">'.$direccion.' '.$nro.' '.$piso.' '.$dpto.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$correo.'</td>
</tr>
<tr>
<th align="left" width="200">Teléfono</th>
<td align="left" width="400">'.$telefono.'</td>
</tr>
<tr>
<th align="left" width="200"> Observación </th>
<td align="left" width="400"> '.$observacion.' </td>
</tr>
</table>
</div>
</td>
</tr>
';
$pieMail = ' <tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Gracias por confiar en '.$empresaNombre.'<br/>
Le saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
</html>
';
$cuerpoMail2 = $headMail.$cuerpoMail_1.$cuerpoMail_2.$cuerpoMail_3.$pieMail;
$mail->msgHTML($cuerpoMail2);
$mail->AddBCC("<EMAIL>");
$mail->AddBCC("<EMAIL>");
$mail->AddBCC("<EMAIL>");
$mail->AddAddress($_SESSION["_usremail"], $estadoNombre.' de la cuenta '.$tipo.". Enviada");
if($mail){
if(!$mail->Send()) {
echo 'Fallo en el envío de notificación por mail'; exit;
}
}
//******************//
// Registro ESTADO //
dac_registrarEstado('TCuenta', $ctaId, $est, $tipo."_".$estado);
//*********************//
// Registro MOVIMIENTO //
$movimiento = 'CUENTA_'.$tipo;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", $ctaId);
$ctaId = 0;
//Luego de modificar la cuenta actual, el envío pasa como Solicitud de alta
$est = 5;
$estado = 'SolicitudAlta';
$estadoNombre = 'Solicitud de Alta';
if(dac_controlesAlta($cadena, $ctaId, $empresa, $cuit, 'Cuenta Nueva', $zona, $tipoDDBB, $tipo)){
$observacion= "ALTA por ".$estado.". de Cuenta ".$idCuenta.". ".$observacion;
$idCuenta = dac_crearNroCuenta($empresa, $zona);
$fechaAlta = "2001-01-01 00:00:00";
};
$cuerpoMail_2 = '
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Usuario </th>
<td align="left" width="400"> '.utf8_decode($_SESSION["_usrname"]).' </td>
</tr>
<tr>
<th align="left" width="200">Cuenta</th>
<td align="left" width="400">'.$idCuenta.'</td>
</tr>
<tr>
<th align="left" width="200">Zona - Ruteo</th>
<td align="left" width="400">'.$zona." - ".$ruteo.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$_SESSION["_usremail"].'</td>
</tr>
<tr>
<th align="left" width="200">Fecha de pedido</th>
<td align="left" width="400">'.date("d-m-Y H:i:s").'</td>
</tr>
<tr>
<th align="left" width="200">¿Es agente de retención?</th>
<td align="left" width="400">'.$agenteRetPerc.'</td>
</tr>
<tr style="color:#FFFFFF; font-weight:bold;">
<th colspan="2" align="center">
Datos de la Cuenta
</th>
</tr>
<tr>
<th align="left" width="200">Razón Social</th>
<td align="left" width="400">'.$nombre.'</td>
</tr>
<tr>
<th align="left" width="200">Cuit</th>
<td align="left" width="400">'.$cuit.'</td>
</tr>
<tr>
<th align="left" width="200">Categoría Iva</th>
<td align="left" width="400">'.$catIvaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Lista de Precios</th>
<td align="left" width="400">'.$listaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Cadena</th>
<td align="left" width="400">'.$cadena.'</td>
</tr>
<tr>
<th align="left" width="200">Tipo Cadena</th>
<td align="left" width="400">'.$tipoCadenaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Provincia</th>
<td align="left" width="400">'.$provinciaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Localidad</th>
<td align="left" width="400">'.$localidadNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Domicilio</th>
<td align="left" width="400">'.$direccion.' '.$nro.' '.$piso.' '.$dpto.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$correo.'</td>
</tr>
<tr>
<th align="left" width="200">Teléfono</th>
<td align="left" width="400">'.$telefono.'</td>
</tr>
<tr>
<th align="left" width="200">Web</th>
<td align="left" width="400">'.$web.'</td>
</tr>
<tr>
<th align="left" width="200"> Observación </th>
<td align="left" width="400"> '.$observacion.' </td>
</tr>
<tr>
<th colspan="2" align="center">
Datos a Completar
</th>
</tr>
<tr>
<th align="left" width="200">
Habilitación<br />
Director Técnico<br />
Autorización alta
</th>
<td align="left" width="400"></td>
</tr>
</table>
</div>
</td>
</tr>
';
break;
case 'ModificaDatos':
if(empty($categoriaComercial)){ echo "Indique categoría comercial."; exit; }
$est = 7;
$estadoNombre = 'Modificado de Datos';
//Al modificar datos (pasa a activo)
if (empty($condicionPago)) { echo "Indique una condición de pago."; exit; }
if(dac_controlesModificacion($estadoDDBB, $fechaAlta, $cadena, $empresa, $cuit, $ctaId)){
$fechaAlta = dac_controlesModificacion($estadoDDBB, $fechaAlta, $cadena, $empresa, $cuit, $ctaId);
}
//Busca las categorías de la lista de precios seleccionadas y consotrla que exista la condicion Comercial seleccionada en la cuenta
$categoriasListaPrecios = DataManager::getLista('CategoriaComercial', 'IdLista', $lista);
if(!empty($categoriasListaPrecios)){
$categoriasComerciales = explode(",", $categoriasListaPrecios);
if(!in_array($categoriaComercial, $categoriasComerciales)) {
$categoriaNombre = DataManager::getCategoriaComercial('catnombre', 'catidcat', $categoriaComercial);
echo "La Categoría Comercial '$categoriaComercial - $categoriaNombre' NO corresponde a la Lista de Precios '$listaNombre'";
}
}
//--------------------------------
//**********//
// CORREO //
$from = '<EMAIL>';
$fromName = '<NAME>';
$cuerpoMail_2 = '
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Usuario </th>
<td align="left" width="400"> '.utf8_decode($_SESSION["_usrname"]).' </td>
</tr>
<tr>
<th align="left" width="200">Cuenta</th>
<td align="left" width="400">'.$idCuenta.'</td>
</tr>
<tr>
<th align="left" width="200">Zona - Ruteo</th>
<td align="left" width="400">'.$zona." - ".$ruteo.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$_SESSION["_usremail"].'</td>
</tr>
<tr>
<th align="left" width="200">Fecha de pedido</th>
<td align="left" width="400">'.date("d-m-Y H:i:s").'</td>
</tr>
<tr>
<th align="left" width="200">¿Es agente de retención?</th>
<td align="left" width="400">'.$agenteRetPerc.'</td>
</tr>
<tr style="color:#FFFFFF; font-weight:bold;">
<th colspan="2" align="center">
Datos de la Cuenta
</th>
</tr>
<tr>
<th align="left" width="200">Razón Social</th>
<td align="left" width="400">'.$nombre.'</td>
</tr>
<tr>
<th align="left" width="200">Cuit</th>
<td align="left" width="400">'.$cuit.'</td>
</tr>
<tr>
<th align="left" width="200">Categoría Iva</th>
<td align="left" width="400">'.$catIvaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Cadena</th>
<td align="left" width="400">'.$cadena.'</td>
</tr>
<tr>
<th align="left" width="200">Tipo Cadena</th>
<td align="left" width="400">'.$tipoCadenaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Provincia</th>
<td align="left" width="400">'.$provinciaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Localidad</th>
<td align="left" width="400">'.$localidadNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Domicilio</th>
<td align="left" width="400">'.$direccion.' '.$nro.' '.$piso.' '.$dpto.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$correo.'</td>
</tr>
<tr>
<th align="left" width="200">Teléfono</th>
<td align="left" width="400">'.$telefono.'</td>
</tr>
<tr>
<th align="left" width="200">Web</th>
<td align="left" width="400">'.$web.'</td>
</tr>
<tr>
<th align="left" width="200"> Observación </th>
<td align="left" width="400"> '.$observacion.' </td>
</tr>
<tr>
<th colspan="2" align="center">
Datos a Completar
</th>
</tr>
<tr>
<th align="left" width="200">
Habilitación<br />
Director Técnico<br />
Autorización alta
</th>
<td align="left" width="400"></td>
</tr>
</table>
</div>
</td>
</tr>
';
//**********//
break;
case 'SolicitudBaja':
$est = 10;
$estadoNombre = 'Solicitud de Baja';
if(empty($observacion)){
echo "Debe indicar el motivo de la baja de la cuenta"; exit;
}
//La cuenta pasa automáticamente a ZONA INACTIVA
$observacion2 = "Se da de BAJA por ".$estado.". con CUIT ".$cuit.". ".$observacion;
$ctaObject = DataManager::newObjectOfClass('TCuenta', $ctaId);
$ctaObject->__set('Estado' , $estado);
$ctaObject->__set('Zona' , 95);
$ctaObject->__set('Observacion' , $observacion2);
$ctaObject->__set('Activa' , 0);
$ctaObject->__set('CUIT' , '');
$ctaObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObject->__set('LastUpdate' , date("Y-m-d H:i:s"));
// Procesar BAJA en HIPERWIN
$ctaObjectHiper = DataManagerHiper::newObjectOfClass('THiperCuenta', $ctaId);
$ctaObjectHiper->__set('Estado' , $estado);
$ctaObjectHiper->__set('Zona' , 95);
$ctaObjectHiper->__set('Observacion', $observacion2);
$ctaObjectHiper->__set('Activa' , 0);
$ctaObjectHiper->__set('CUIT' , '');
$ctaObjectHiper->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObjectHiper->__set('LastUpdate' , date("Y-m-d H:i:s"));
DataManagerHiper::updateSimpleObject($ctaObjectHiper, $ctaId);
DataManager::updateSimpleObject($ctaObject);
//----------------------------
$cuerpoMail_2 = '
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Usuario </th>
<td align="left" width="400"> '.utf8_decode($_SESSION["_usrname"]).' </td>
</tr>
<tr>
<th align="left" width="200">Cuenta</th>
<td align="left" width="400">'.$idCuenta.'</td>
</tr>
<tr>
<th align="left" width="200">Zona - Ruteo</th>
<td align="left" width="400">'.$zona." - ".$ruteo.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$_SESSION["_usremail"].'</td>
</tr>
<tr>
<th align="left" width="200">Fecha de pedido</th>
<td align="left" width="400">'.date("d-m-Y H:i:s").'</td>
</tr>
<tr style="color:#FFFFFF; font-weight:bold;">
<th colspan="2" align="center">
Datos de la Cuenta
</th>
</tr>
<tr>
<th align="left" width="200">Razón Social</th>
<td align="left" width="400">'.$nombre.'</td>
</tr>
<tr>
<th align="left" width="200">Cuit</th>
<td align="left" width="400"></td>
</tr>
<tr>
<th align="left" width="200">Provincia</th>
<td align="left" width="400">'.$provinciaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Localidad</th>
<td align="left" width="400">'.$localidadNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Domicilio</th>
<td align="left" width="400">'.$direccion.' '.$nro.' '.$piso.' '.$dpto.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$correo.'</td>
</tr>
<tr>
<th align="left" width="200">Teléfono</th>
<td align="left" width="400">'.$telefono.'</td>
</tr>
<tr>
<th align="left" width="200"> Observación </th>
<td align="left" width="400"> '.$observacion2.' </td>
</tr>
</table>
</div>
</td>
</tr>
';
//******************//
// Registro ESTADO //
dac_registrarEstado('TCuenta', $ctaId, $est, $tipo."_".$estado);
//*********************//
// Registro MOVIMIENTO //
$movimiento = 'CUENTA_'.$tipo;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", $ctaId);
break;
}
//**********//
// CORREO //
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = $from;
$mail->FromName = $fromName;
$mail->Subject = $estadoNombre." de Cuenta ".$tipo.", ".$nombre.". Guarde este email.";
$headMail = '
<html>
<head>
<title>'.$estadoNombre.' de CUENTA '.$tipo.'</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 580px;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>';
$cuerpoMail_1 = '
<body>
<div align="center">
<table width="580" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Se envían los datos de <strong>'.$estadoNombre.' de la CUENTA '.$tipo.'</strong> correspondiente a:<br/><br/>
<div />
</td >
</tr>
<tr>
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight:bold; background-color:#117db6">
<strong>Datos de la solicitud</strong>
</div>
</td>
</tr>
';
$pieMail = ' <tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Gracias por confiar en '.$empresaNombre.'<br/>
Le saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
</html>
';
$cuerpoMail = $headMail.$cuerpoMail_1.$cuerpoMail_2.$cuerpoMail_3.$pieMail;
//Adjunta Archivos
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
if($estado == 'SolicitudAlta' || $estado == 'CambioRazonSocial' || $estado == 'CambioDomicilio'){ //Debe adjuntar documentación
if($hayArchivos){
for ($i = 0; $i < $fileCount; $i++) {
if($myFiles['error'][$i] == UPLOAD_ERR_OK){
$nombreOriginal = $myFiles['name'][$i];
$nombreTemporal = $myFiles['tmp_name'][$i];
$peso = $myFiles['size'][$i];
$mail->AddAttachment($nombreTemporal, $nombreOriginal);
}
if ($myFiles['error'][$i] != 0 && $myFiles['error'][$i] != 4){
echo 'No se pudo subir el archivo <b>'.$nombreOriginal.'</b> debido al siguiente Error: '.$myFiles['error'][$i]; exit;
}
}
} else {
echo "Debe adjuntar documentación para ".$estadoNombre."."; exit;
}
}
}
$mail->msgHTML($cuerpoMail);
$mail->AddBCC("<EMAIL>");
$mail->AddBCC("<EMAIL>");
$mail->AddAddress($_SESSION["_usremail"], $estadoNombre.' de la cuenta '.$tipo.". Enviada");
switch($estado){
case 'SolicitudAlta':
$mail->AddAddress("<EMAIL>");
break;
case 'SolicitudBaja':
$mail->AddBCC("<EMAIL>");
break;
}
break;
//**************//
// TRANSFER //
case 'T':
case 'TT':
//Controles generales
if(empty($zona) || $zona==199){ echo "Indique la zona del vendedor."; exit; }
if(empty($ruteo)){ echo "Indique el ruteo."; exit; }
if (empty($cp) || !is_numeric($cp)) { echo "Indique código postal."; exit; }
//**********//
// CORREO //
$from = $_SESSION["_usremail"];
$fromName = "Usuario ".$_SESSION["_usrname"];
$cuerpoMail_3 = '
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con la empresa al 4555-3366 de Lunes a Viernes de 10 a 17 horas.
</font>
<div style="color:#000000; font-size:12px;">
<strong>Si no recibe información del alta en 24 horas hábiles, podrá reclamar reenviando éste mail a <EMAIL> </strong></br></br>
</div>
</div>
</td>
</tr>
';
switch($estado){
case 'SolicitudAlta':
$est = 5;
$estadoNombre = 'Solicitud de Alta';
if(dac_controlesAlta($cadena, $ctaId, $empresa, $cuit, $estadoDDBB, $zona, $tipoDDBB, $tipo)){
$idCuenta = dac_crearNroCuenta($empresa, $zona);
$fechaAlta = "2001-01-01 00:00:00";
}
break;
case 'CambioRazonSocial':
case 'CambioDomicilio':
echo "Ésta cuenta no requiere ésta solicitud."; exit;
break;
case 'ModificaDatos':
$est = 7;
$estadoNombre = 'Modificado de Datos';
if(dac_controlesModificacion($estadoDDBB, $fechaAlta, $cadena, $empresa, $cuit, $ctaId)){
$fechaAlta = dac_controlesModificacion($estadoDDBB, $fechaAlta, $cadena, $empresa, $cuit, $ctaId);
}
//**********//
// CORREO //
//**********//
$from = '<EMAIL>';
$fromName = '<NAME>';
//**********//
break;
case 'SolicitudBaja':
$est = 10;
$estadoNombre = 'Solicitud de Baja';
if(empty($observacion)){
echo "Debe indicar el motivo de la baja de la cuenta"; exit;
}
//La cuenta pasa automáticamente a ZONA INACTIVA
$observacion2 = "Se da de BAJA por ".$estado.". con CUIT ".$cuit.". ".$observacion;
$ctaObject = DataManager::newObjectOfClass('TCuenta', $ctaId);
$ctaObject->__set('Estado' , $estado);
$ctaObject->__set('Zona' , 95);
$ctaObject->__set('Observacion' , $observacion2);
$ctaObject->__set('Activa' , 0);
$ctaObject->__set('CUIT' , '');
$ctaObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObject->__set('LastUpdate' , date("Y-m-d H:i:s"));
DataManager::updateSimpleObject($ctaObject);
//******************//
// Registro ESTADO //
dac_registrarEstado('TCuenta', $ctaId, $est, $tipo."_".$estado);
//*********************//
// Registro MOVIMIENTO //
$movimiento = 'CUENTA_'.$tipo;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", $ctaId);
break;
}
//**********************//
if(count($arrayCtaIdDrog) < 1){
echo "Debe cargar al menos una droguería con número de cuenta transfer."; exit;
}
//**********//
// CORREO //
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = $from;
$mail->FromName = $fromName;
$mail->Subject = $estadoNombre." de Cuenta ".$tipo.", ".$nombre.". Guarde este email.";
$headMail = '
<html>
<head>
<title>'.$estadoNombre.' de CUENTA '.$tipo.'</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 580px;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>';
$cuerpoMail_1 = '
<body>
<div align="center">
<table width="580" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Se envían los datos de <strong>'.$estadoNombre.' de la CUENTA '.$tipo.'</strong> correspondiente a:<br/><br/>
<div />
</td >
</tr>
<tr>
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight:bold; background-color:#117db6">
<strong>Datos de la solicitud</strong>
</div>
</td>
</tr>
';
$cuerpoMail_2 = '
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Usuario </th>
<td align="left" width="400"> '.utf8_decode($_SESSION["_usrname"]).' </td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$_SESSION["_usremail"].'</td>
</tr>
<tr>
<th align="left" width="200">Fecha de pedido</th>
<td align="left" width="400">'.date("d-m-Y H:i:s").'</td>
</tr>
<tr style="color:#FFFFFF; font-weight:bold;">
<th colspan="2" align="center">
Datos de la Cuenta
</th>
</tr>
<tr>
<th align="left" width="200">Cuenta</th>
<td align="left" width="400">'.$idCuenta.'</td>
</tr>
<tr>
<th align="left" width="200">Zona - Ruteo</th>
<td align="left" width="400">'.$zona." - ".$ruteo.'</td>
</tr>
<tr>
<th align="left" width="200">Razón Social</th>
<td align="left" width="400">'.$nombre.'</td>
</tr>
<tr>
<th align="left" width="200">Cuit</th>
<td align="left" width="400">'.$cuit.'</td>
</tr>
<tr>
<th align="left" width="200">Cadena</th>
<td align="left" width="400">'.$cadena.'</td>
</tr>
<tr>
<th align="left" width="200">Tipo Cadena</th>
<td align="left" width="400">'.$tipoCadenaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Provincia</th>
<td align="left" width="400">'.$provinciaNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Localidad</th>
<td align="left" width="400">'.$localidadNombre.'</td>
</tr>
<tr>
<th align="left" width="200">Domicilio</th>
<td align="left" width="400">'.$direccion.' '.$nro.' '.$piso.' '.$dpto.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$correo.'</td>
</tr>
<tr>
<th align="left" width="200">Teléfono</th>
<td align="left" width="400">'.$telefono.'</td>
</tr>
<tr>
<th align="left" width="200"> Observación </th>
<td align="left" width="400"> '.$observacion.' </td>
</tr>
</table>
</div>
</td>
</tr>
';
$pieMail = ' <tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Gracias por confiar en '.$empresaNombre.'<br/>
Le saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
</html>
';
$cuerpoMail = $headMail.$cuerpoMail_1.$cuerpoMail_2.$cuerpoMail_3.$pieMail;
$mail->msgHTML($cuerpoMail);
$mail->AddBCC("<EMAIL>");
$mail->AddBCC("<EMAIL>");
$mail->AddAddress($_SESSION["_usremail"], $estadoNombre.' de la cuenta '.$tipo.". Enviada");
switch($estado){
case 'SolicitudBaja':
$mail->AddBCC("<EMAIL>");
break;
}
break;
//**************//
// PROSPECTO //
case 'PS':
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
//Controlo campos generales
if(count($arrayCtaIdDrog) > 0){ echo "Un prospecto no puede tener cuentas transfers relacionados."; exit; }
switch($estado){
case 'SolicitudAlta':
//El alta se realiza directa!
$est = 5;
$estadoNombre = 'Alta';
if(dac_controlesAlta($cadena, $ctaId, $empresa, $cuit, $estadoDDBB, $zona, $tipoDDBB, $tipo)){
$fechaAlta = "2001-01-01 00:00:00";
$zona = empty($zona) ? 199 : $zona;
};
//echo "Los prospectos no pueden solicitarse por alta."; exit;
break;
case 'CambioRazonSocial':
case 'CambioDomicilio':
case 'SolicitudBaja':
echo "Ésta cuenta no requiere ésta solicitud."; exit;
break;
case 'ModificaDatos':
$est = 7;
$estadoNombre = 'Modificado de Datos';
//********************//
dac_controlesModificacion($estadoDDBB, $fechaAlta, $cadena, $empresa, $cuit, $ctaId);
break;
}
break;
//**************//
// PROVEEDOR //
//**************//
case 'PV':
echo "No se puede realizar ésta acción."; exit;
break;
//**********//
// OTROS //
//**********//
case 'O':
//Solo deberá ser en casos en que una cuenta NO SEA farmacia.
//Solo losprospectos pueden pasar a estado Otro
if(empty($observacion)){
echo "Indique en observaciones el motivo del tipo de la cuenta."; exit;
}
switch($estado){
case 'SolicitudAlta':
case 'CambioRazonSocial':
case 'CambioDomicilio':
case 'SolicitudBaja':
echo "Ésta cuenta no requiere ésta solicitud."; exit;
break;
case 'ModificaDatos':
$est = 7;
$estadoNombre = 'Modificado de Datos';
break;
}
$activa = 0;
break;
default:
echo "Seleccione un tipo de cuenta."; exit;
break;
}
//-------------------//
// GUARDAR CAMBIOS //
$empleados = empty($empleados) ? 0 : $empleados;
$condicionPago = empty($condicionPago) ? 0 : $condicionPago;
$nro = empty($nro) ? 0 : $nro;
$categoriaComercial = empty($categoriaComercial)? 0 : $categoriaComercial;
$ruteo = empty($ruteo) ? 0 : $ruteo;
$zona = empty($zona) ? 0 : $zona;
$localidad = empty($localidad) ? 0 : $localidad;
$cp = empty($cp) ? 0 : $cp;
$ctaObject = ($ctaId) ? DataManager::newObjectOfClass('TCuenta', $ctaId) : DataManager::newObjectOfClass('TCuenta');
$ctaObject->__set('Empresa' , $empresa);
$ctaObject->__set('Cuenta' , $idCuenta);
$ctaObject->__set('Tipo' , $tipo);
$ctaObject->__set('Estado' , $estado);
$ctaObject->__set('Nombre' , $nombre);
$ctaObject->__set('CUIT' , $cuit);
$ctaObject->__set('NroIngresosBrutos', $nroIngBrutos);
$ctaObject->__set('Zona' , $zona);
$ctaObject->__set('ZonaEntrega' , $zonaEntrega);
$ctaObject->__set('Ruteo' , $ruteo);
$ctaObject->__set('CondicionPago' , $condicionPago);
$ctaObject->__set('CategoriaComercial', $categoriaComercial);
$ctaObject->__set('Empleados' , $empleados);
$ctaObject->__set('CategoriaIVA' , $categoriaIVA);
$ctaObject->__set('RetencPercepIVA' , $agenteRetPerc);
$ctaObject->__set('FechaAlta' , ($fechaAlta) ? $fechaAlta: "2001-01-01 00:00:00");
$ctaObject->__set('Email' , $correo);
$ctaObject->__set('Telefono' , $telefono);
$ctaObject->__set('Web' , $web);
$ctaObject->__set('Observacion' , $observacion);
$ctaObject->__set('UsrAssigned' , $asignado);
$ctaObject->__set('Pais' , 1);
$ctaObject->__set('Provincia' , $provincia);
$ctaObject->__set('Localidad' , $localidad);
$ctaObject->__set('LocalidadNombre' , $localidadNombre);
$ctaObject->__set('Direccion' , $direccion);
$ctaObject->__set('DireccionEntrega', $direccionEntrega);
$ctaObject->__set('Numero' , $nro);
$ctaObject->__set('Piso' , $piso);
$ctaObject->__set('Dpto' , $dpto);
$ctaObject->__set('CP' , $cp);
$ctaObject->__set('Longitud' , $longitud);
$ctaObject->__set('Latitud' , $latitud);
$ctaObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObject->__set('LastUpdate' , date("Y-m-d"));
$ctaObject->__set('Referencias' , 0);
$ctaObject->__set('Imagen1' , $imagen1);
$ctaObject->__set('Imagen2' , $imagen2);
$ctaObject->__set('Bonif1' , 0);
$ctaObject->__set('Bonif2' , 0);
$ctaObject->__set('Bonif3' , 0);
$ctaObject->__set('CuentaContable' , '1.1.3.01.01');
$ctaObject->__set('Credito' , 0);
$ctaObject->__set('NroEmpresa' , 0);
$ctaObject->__set('Lista' , $lista);
//--------------------------------//
// PREPARO CUENTA PARA HiperWin
$ctaObjectHiper = ($ctaId) ? DataManagerHiper::newObjectOfClass('THiperCuenta', $ctaId) : DataManagerHiper::newObjectOfClass('THiperCuenta');
$ctaObjectHiper->__set('Empresa' , $empresa);
$ctaObjectHiper->__set('Cuenta' , $idCuenta);
$ctaObjectHiper->__set('Tipo' , $tipo);
$ctaObjectHiper->__set('Estado' , $estado);
$ctaObjectHiper->__set('Nombre' , strtoupper($nombre) );
$ctaObjectHiper->__set('CUIT' , $cuit);
$ctaObjectHiper->__set('Zona' , $zona);
$ctaObjectHiper->__set('ZonaEntrega' , $zonaEntrega);
$ctaObjectHiper->__set('Pais' , 1);
$ctaObjectHiper->__set('Provincia' , $provincia);
$ctaObjectHiper->__set('Localidad' , $localidad);
$ctaObjectHiper->__set('LocalidadNombre' , $localidadNombre);
$ctaObjectHiper->__set('Direccion' , $direccion);
$direccionCompleta = $direccion.(empty($nro)? '' : ' '.$nro).(empty($piso) ? '' : ' '.$piso).(empty($dpto) ? '' : $dpto);
$ctaObjectHiper->__set('DireccionCompleta' , $direccionCompleta);
$ctaObjectHiper->__set('DireccionEntrega' , $direccionEntrega);
$ctaObjectHiper->__set('Numero' , $nro);
$ctaObjectHiper->__set('Piso' , $piso);
$ctaObjectHiper->__set('Dpto' , $dpto);
$ctaObjectHiper->__set('CP' , $cp);
$ctaObjectHiper->__set('Longitud' , $longitud);
$ctaObjectHiper->__set('Latitud' , $latitud);
$ctaObjectHiper->__set('Ruteo' , $ruteo);
$ctaObjectHiper->__set('CategoriaComercial' , $categoriaComercial);
$ctaObjectHiper->__set('CondicionPago' , $condicionPago);
$ctaObjectHiper->__set('Empleados' , $empleados);
$ctaObjectHiper->__set('CategoriaIVA' , $categoriaIVA);
$ctaObjectHiper->__set('RetencPercepIVA' , $agenteRetPerc);
$ctaObjectHiper->__set('NroIngresosBrutos' , $nroIngBrutos);
$ctaObjectHiper->__set('FechaAlta' , ($fechaAlta) ? $fechaAlta: "2001-01-01 00:00:00");
$ctaObjectHiper->__set('Email' , $correo);
$ctaObjectHiper->__set('Telefono' , $telefono);
$ctaObjectHiper->__set('Web' , $web);
$ctaObjectHiper->__set('Observacion' , $observacion);
$ctaObjectHiper->__set('Imagen1' , $imagen1);
$ctaObjectHiper->__set('Imagen2' , $imagen2);
$ctaObjectHiper->__set('UsrAssigned' , $asignado);
$ctaObjectHiper->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObjectHiper->__set('LastUpdate' , date("Y-m-d"));
$ctaObjectHiper->__set('Referencias' , 0);
$ctaObjectHiper->__set('Bonif1' , 0);
$ctaObjectHiper->__set('Bonif2' , 0);
$ctaObjectHiper->__set('Bonif3' , 0);
$ctaObjectHiper->__set('CuentaContable' , '1.1.3.01.01');
$ctaObjectHiper->__set('Credito' , 0);
$ctaObjectHiper->__set('NroEmpresa' , 0);
$ctaObjectHiper->__set('Lista' , $lista);
if($tipo == "C" || $tipo == "CT") {
if($estado == 'ModificaDatos') {
//Si modifica un usr Vendedor, no se modifican los datos de la cuenta
//Solo se actualizan documentos y cuentas relacionadas
if($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$ctaObjectHiper = DataManagerHiper::newObjectOfClass('THiperCuenta', $ctaId);
$ctaObject = DataManager::newObjectOfClass('TCuenta', $ctaId);
}
}
}
if(!empty($frenteNombre)) {
$ctaObject->__set('Imagen1', $frenteNombre);
$ctaObjectHiper->__set('Imagen1', $frenteNombre);
}
if(!empty($interiorNombre)){
$ctaObject->__set('Imagen2', $interiorNombre);
$ctaObjectHiper->__set('Imagen2', $interiorNombre);
}
if ($ctaId){
//UPDATE
$ctaObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObject->__set('LastUpdate' , date("Y-m-d H:i:s"));
$ctaObjectHiper->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObjectHiper->__set('LastUpdate' , date("Y-m-d H:i:s"));
if($estado != 'SolicitudBaja'){
if($tipo == "C" || $tipo == "CT") {
if($tipoDDBB != "C" && $tipoDDBB != "CT"){
//si la cuenta es cliente pero viene de otro tipoDDBB se crea en hiperwin
$ctaObjectHiper->__set('FechaCompra', date("2001-01-01"));
$ctaObjectHiper->__set('UsrCreated' , $_SESSION["_usrid"]);
$ctaObjectHiper->__set('DateCreated', date("Y-m-d H:i:s"));
$ctaObjectHiper->__set('Activa' , 1);
$ctaObjectHiper->__set('ID' , $ctaId);
$IDHiper = DataManagerHiper::insertSimpleObject($ctaObjectHiper);
if(!$IDHiper){
echo "Error al insertar la cuenta Hiper."; exit;
}
} else { //Si solo es modificacion se hace update
DataManagerHiper::updateSimpleObject($ctaObjectHiper, $ctaId);
}
}
DataManager::updateSimpleObject($ctaObject);
//Registro de cadenas
if($cadena){
$cuentasCadena = [];
$idCtaRel = [];
$cuentas = DataManager::getCuentasCadena($empresa, $cadena);
if (count($cuentas)) {
foreach ($cuentas as $k => $cta) {
$idCtaRel[] = $cta['cadid'];
$cuentasCadena[] = $cta['IdCliente'];
}
}
if(in_array($idCuenta, $cuentasCadena) ){
//UPDATE cadena
$key = array_search($idCuenta, $cuentasCadena);
$cadRelObject = DataManager::newObjectOfClass('TCadenaCuentas', $idCtaRel[$key]);
$cadRelObject->__set('TipoCadena', $tipoCadena);
$ID = $cadRelObject->__get('ID');
DataManagerHiper::updateSimpleObject($cadRelObject, $ID);
DataManager::updateSimpleObject($cadRelObject);
} else {
//INSERT cadena
$cadRelObject = DataManager::newObjectOfClass('TCadenaCuentas');
$cadRelObject->__set('Empresa' , $empresa);
$cadRelObject->__set('Cadena' , $cadena);
$cadRelObject->__set('Cuenta' , $idCuenta);
$cadRelObject->__set('TipoCadena', $tipoCadena);
$cadRelObject->__set('ID' , $cadRelObject->__newID());
DataManagerHiper::_getConnection('Hiper'); //Controla conexión a HiperWin
$IDCuentaRel = DataManager::insertSimpleObject($cadRelObject);
DataManagerHiper::insertSimpleObject($cadRelObject, $IDCuentaRel);
}
}
// MOVIMIENTO //
$movimiento = 'CUENTA_'.$tipo;
$movTipo = 'UPDATE';
}
} else {
//INSERT
$ctaObject->__set('FechaCompra' , date("2001-01-01"));
$ctaObject->__set('UsrCreated' , $_SESSION["_usrid"]);
$ctaObject->__set('DateCreated' , date("Y-m-d H:i:s"));
$ctaObject->__set('ID' , $ctaObject->__newID());
$ctaObjectHiper->__set('FechaCompra', date("2001-01-01"));
$ctaObjectHiper->__set('UsrCreated' , $_SESSION["_usrid"]);
$ctaObjectHiper->__set('DateCreated', date("Y-m-d H:i:s"));
if($tipo != "PS" && $tipo != "T" && $tipo != "TT"){
$ctaObject->__set('Activa' , 0);
$ctaObjectHiper->__set('Activa' , 0);
} else {
$ctaObject->__set('Activa' , 1);
$ctaObjectHiper->__set('Activa' , 1);
}
DataManagerHiper::_getConnection('Hiper'); //Controla conexión a HiperWin
$ID = DataManager::insertSimpleObject($ctaObject);
if(!$ID){
echo "Error al insertar la cuenta."; exit;
}
if($tipo == "C" || $tipo == "CT") {
$ctaObjectHiper->__set('ID' , $ID);
$IDHiper = DataManagerHiper::insertSimpleObject($ctaObjectHiper);
if(!$IDHiper){
echo "Error al insertar la cuenta Hiper."; exit;
}
}
//MOVIMIENTO de CUENTA
$ctaId = $ID;
$movimiento = 'CUENTA_'.$tipo;
$movTipo = 'INSERT';
}
//IMPORTANTE: Send Mail debe estar antes de subir los archivos a la raiz de la web,
//de lo contrario no aparecerán adjuntos en el mail
if($ctaId){
if($mail){
if(!$mail->Send()) {
echo '! Fallo en el envío de notificación por mail'.$mail->ErrorInfo; exit;
}
}
//-----------------------
// Registro MOVIMIENTO
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", $ctaId);
} else {
echo "El registro de datos no se realizó correctamente."; exit;
}
//******************//
// Registro ESTADO //
$tipoEstado = $tipo."_".$estado;
dac_registrarEstado('TCuenta', $ctaId, $est, $tipoEstado);
//******************************//
// UPLOAD de FRENTE E INTERIOR //
$rutaFile = "/pedidos/cuentas/archivos/".$ctaId."/";
if ($frentePeso != 0){
if(dac_fileFormatControl($_FILES["frente"]["type"], 'imagen') && $_FILES["frente"]["type"] != "application/pdf"){
$ext = explode(".", $frenteNombre);
$name = $ext[0];
if(!dac_fileUpload($_FILES["frente"], $rutaFile, $name)){
echo "Error al intentar subir el archivo."; exit;
}
} else {
echo "El archivo frente debe tener formato imagen."; exit;
}
}
if ($interiorPeso != 0){
if(dac_fileFormatControl($_FILES["interior"]["type"], 'imagen') && $_FILES["interior"]["type"] != "application/pdf"){
$ext = explode(".", $interiorNombre);
$name = $ext[0];
if(!dac_fileUpload($_FILES["interior"], $rutaFile, $name)){
echo "Error al intentar subir el archivo."; exit;
}
} else {
echo "El archivo frente debe tener formato imagen."; exit;
}
}
//******************************//
// UPLOAD de OTROS ARCHIVOS //
if (isset($_FILES['multifile'])) {
$myFiles = $_FILES['multifile'];
$fileCount = count($myFiles["name"]);
for ($i = 0; $i < $fileCount; $i++) {
if($myFiles['error'][$i] == UPLOAD_ERR_OK ){
$nombreOriginal = $myFiles['name'][$i];
$temporal = $myFiles['tmp_name'][$i];
$peso = $myFiles['size'][$i];
$destino = $_SERVER['DOCUMENT_ROOT'].$rutaFile;
$info = new SplFileInfo($nombreOriginal);
if(file_exists($destino) || @mkdir($destino, 0777, true)) {
$destino = $destino.'documento'.$i.'F'.date("dmYHms").".".$info->getExtension();
move_uploaded_file($temporal, $destino);
} else {echo "Error al intentar crear el archivo."; exit;}
} else {
if($myFiles['error'][$i] != 0){
switch($myFiles['error'][$i]){
case '0': //UPLOAD_ERR_OK
break;
case '1': //UPLOAD_ERR_INI_SIZE
//El fichero subido excede la directiva upload_max_filesize de php.ini.
break;
case '2': //UPLOAD_ERR_FORM_SIZE
//El fichero subido excede la directiva MAX_FILE_SIZE especificada en el formulario HTML.
break;
case '3': //UPLOAD_ERR_PARTIAL
// El fichero fue sólo parcialmente subido.
break;
case '4': //UPLOAD_ERR_NO_FILE
//No se subió ningún fichero.
break;
case '6': //UPLOAD_ERR_NO_TMP_DIR
//Falta la carpeta temporal. Introducido en PHP 5.0.3.
break;
case '7': //UPLOAD_ERR_CANT_WRITE
//No se pudo escribir el fichero en el disco. Introducido en PHP 5.1.0.
break;
case '8': //UPLOAD_ERR_EXTENSION
//Una extensión de PHP detuvo la subida de ficheros. PHP no proporciona una forma de determinar la extensión que causó la parada de la subida de ficheros; el examen de la lista de extensiones cargadas con phpinfo() puede ayudar. Introducido en PHP 5.2.0.
break;
default:
if ($myFiles['error'][$i] != 4){
echo 'No se pudo subir el archivo <b>'.$nombreOriginal.'</b> debido al siguiente Error: '.$myFiles['error'][$i]; exit;
}
break;
}
}
}
}
}
//******************************//
// UPDATE CUENTAS RELACIONADAS //
if(!empty($arrayCtaIdDrog)){
if(count($arrayCtaIdDrog)){
$cuentasRelacionadas = DataManager::getCuentasRelacionadas($ctaId); //$empresa, $idCuenta
if (count($cuentasRelacionadas)) {
foreach ($cuentasRelacionadas as $k => $ctaRel) {
$ctaRel = $cuentasRelacionadas[$k];
$relId = $ctaRel['ctarelid'];
$relIdDrog = $ctaRel['ctarelidcuentadrog'];
//Creo Array de Droguerias Relacionadas de BBDD
$arrayDrogDDBB[] = $relIdDrog;
if (in_array($relIdDrog, $arrayCtaIdDrog)) {
//UPDATE
$key = array_search($relIdDrog, $arrayCtaIdDrog); //Indice donde se encuentra la cuenta
$ctaRelObject = DataManager::newObjectOfClass('TCuentaRelacionada', $relId);
$ctaRelObject->__set('Transfer' , $arrayCtaCliente[$key]); //nro de cliente para la droguería
DataManager::updateSimpleObject($ctaRelObject);
} else {
//DELETE de cuentas relacionadas
$ctaRelObject = DataManager::newObjectOfClass('TCuentaRelacionada', $relId);
$ctaRelObject->__set('ID', $relId);
DataManager::deleteSimpleObject($ctaRelObject);
}
}
foreach ($arrayCtaIdDrog as $k => $ctaIdDrog) {
if (!in_array($ctaIdDrog, $arrayDrogDDBB)) {
//INSERT
$ctaRelObject = DataManager::newObjectOfClass('TCuentaRelacionada');
$ctaRelObject->__set('Cuenta' , $ctaId);
$ctaRelObject->__set('Drogueria' , $ctaIdDrog);
$ctaRelObject->__set('Transfer' , $arrayCtaCliente[$k]);
$ctaRelObject->__set('ID' , $ctaRelObject->__newID());
$IDRelacion = DataManager::insertSimpleObject($ctaRelObject);
}
}
} else { //INSERT - Si no hay cuentas relacionadas, las crea
foreach ($arrayCtaIdDrog as $k => $ctaIdDrog) {
$ctaRelObject = DataManager::newObjectOfClass('TCuentaRelacionada');
$ctaRelObject->__set('Cuenta' , $ctaId);
$ctaRelObject->__set('Drogueria' , $ctaIdDrog); //nro iddrogueria
$ctaRelObject->__set('Transfer' , $arrayCtaCliente[$k]); //nro cliente transfer
$ctaRelObject->__set('ID' , $ctaRelObject->__newID());
$IDRelacion = DataManager::insertSimpleObject($ctaRelObject);
}
}
}
} else {
//Si no se envían datos de arrya de clientes transfers, consulta si existe para eliminar
if($ctaId){
$cuentasRelacionadas = DataManager::getCuentasRelacionadas($ctaId);
if (count($cuentasRelacionadas)) {
//DELETE de cuentas relacionadas
foreach ($cuentasRelacionadas as $k => $ctaRel) {
$ctaRel = $cuentasRelacionadas[$k];
$relId = $ctaRel['ctarelid'];
$ctaRelObject = DataManager::newObjectOfClass('TCuentaRelacionada', $relId);
$ctaRelObject->__set('ID', $relId);
DataManager::deleteSimpleObject($ctaRelObject);
}
}
}
}
//*************//
echo 1; exit;
//**************//
// FUNCIONES //
//**************//
//Consulto Estado Actual de la cuenta
function dac_consultarEstado($idCuenta, $empresa){
$ctaCtrl = DataManager::getCuenta('ctaidcuenta', 'ctaidcuenta', $idCuenta, $empresa);
if(empty($ctaCtrl)){ return 'Cuenta Nueva'; }
$ctaCtrlEstado = DataManager::getCuenta('ctaestado', 'ctaidcuenta', $idCuenta, $empresa);
if($ctaCtrlEstado){ return $ctaCtrlEstado; }
return false;
}
//Consulto Tipo de cuenta actual en DDBB
function dac_consultarTipo($ctaId){ //$idCuenta, $empresa){
$ctaCtrlTipo = DataManager::getCuenta('ctatipo', 'ctaid', $ctaId);//'ctaidcuenta', $idCuenta, $empresa);
if($ctaCtrlTipo){
return $ctaCtrlTipo;
}
return false;
}
function dac_crearNroCuenta($empresa, $zona){
$nrosCuentas = DataManager::dac_consultarNumerosCuenta($empresa, $zona);
if($nrosCuentas){
//busca el número de cuenta disponible
foreach($nrosCuentas as $k => $nroCta){
$min = 0;
$min = substr($nroCta['ctaidcuenta'], strlen($zona), 3);
$minMas = $min + 1;
if(isset($nrosCuentas[$k+1]['ctaidcuenta'])){
$sig = substr($nrosCuentas[$k+1]['ctaidcuenta'], strlen($zona), 3);
} else {
$sig = $minMas + 1;
}
if($sig != $minMas){
//agregos los ceros necesario a minMas
$ceros = "";
for($i=0; $i < (3 - strlen($minMas)); $i++){
$ceros .= "0";$minMas;
}
$minMas = $ceros.$minMas;
$nvaCuenta = $zona.$minMas."1";
return $nvaCuenta;
}
}
echo "No se pudo crear un número de cuenta. Contacte con el administrador de la web."; exit;
} else {
//Si no se encuentran números de cuentas en la zona, debería crear el primero!
$nvaCuenta = $zona."001"."1";
return $nvaCuenta;
}
}
function dac_existeCuitCuenta($empresa, $cuit, $ctaId){
$cont = 0;
$cuentas = DataManager::getCuentaAll('ctaid', 'ctacuit', $cuit, $empresa);
if(count($cuentas)){
//SI no hay ctaid es que es alta. Si existen cuentas con el cuit es que ya existe
if(empty($ctaId)){ return TRUE; }
//SI hay cuentas con cuits ver si coincide con la cuenta actual si es una sola, si son varias solo vale si es cadena.
foreach ($cuentas as $k => $cuenta) {
$cuentaId = $cuenta['ctaid'];
$ctatipo = DataManager::getCuenta('ctatipo', 'ctaid', $cuentaId, $empresa);
//$ctacadena = DataManager::getCuenta('ctaidcadena', 'ctaid', $cuentaId, $empresa);
$ctacadena = DataManager::getCuentasCadena($empresa, NULL, $cuentaId);
if(($ctatipo == 'C' || $ctatipo == 'CT' || $ctatipo == 'T' || $ctatipo == 'TT' || $ctatipo == 'PS') && empty($ctacadena)) {
if($ctaId != $cuentaId) {
$cont = $cont + 1;
}
}
}
if($cont >= 1) {
return TRUE;
}
}
return FALSE;
}
function dac_controlesCambioTipoCuenta($tipoDDBB, $tipo, $estadoDDBB, $estado){
if($tipoDDBB != $tipo){
switch($tipoDDBB){
case 'C':
case 'CT':
if($tipo != 'C' && $tipo != 'CT'){
echo "Un cliente no puede cambiar tipo de cuenta."; exit;
}
if($estadoDDBB != 'ModificaDatos'){
echo "Para cambiar tipo de cuenta, el estado debe estar en modificación."; exit;
}
break;
case 'T':
if($tipo != 'C' && $tipo != 'CT' && $tipo != 'TT'){
echo "Un transfer solo puede pasar a cliente."; exit;
}
//Presentar como un alta de cliente
if($estado != 'SolicitudAlta'){
echo "Para cambiar tipo de cuenta, primero solicite el alta de la misma."; exit;
}
break;
case 'TT':
if($tipo != 'C' && $tipo != 'CT' && $tipo != 'T'){
echo "Un transfer solo puede pasar a cliente."; exit;
}
//Presentar como un alta de cliente
if($estado != 'SolicitudAlta'){
echo "Para cambiar tipo de cuenta, primero solicite el alta de la misma."; exit;
}
break;
case 'PS':
/* puede pasar a cualquier estado */
// si pasa a C o T deberá se rcomo alta. Si es a Otros, no importa
if($tipo != 'O'){
if($estado != 'SolicitudAlta'){
echo "Para cambiar tipo de cuenta, primero solicite el alta de la misma."; exit;
}
}
break;
case 'O':
echo "La cuenta no puede cambiar de ese estado, consulte con el administrador de la web."; exit;
break;
default:
if($estado != 'SolicitudAlta'){
echo "Debe solicitar el alta de la cuenta."; exit;
}
break;
}
}
}
function dac_controlesAlta($cadena, $ctaId, $empresa, $cuit, $estadoDDBB, $zona, $tipoDDBB, $tipo) {
if(empty($cadena)){
if(dac_existeCuitCuenta($empresa, $cuit, $ctaId)){
//las cuentas con mismo CUIT ¿Están en estado "cambioRazón o cambioDomicilio"?
//Si una no lo está, entonces sale el mensaje "el cuit ya existe".
if($estadoDDBB != 'CambioRazonSocial' && $estadoDDBB != 'CambioDomicilio') {
echo "El cuit ya existe en una cuenta."; exit;
} else {
$estadoDDBB = 'Cuenta Nueva';
}
}
}
if($estadoDDBB == 'Cuenta Nueva'){
return TRUE;
} else {
if($tipoDDBB == $tipo){
echo "La cuenta ya existe, no puede solicitar un alta."; exit;
}
}
return FALSE;
}
function dac_controlesModificacion($estadoDDBB, $fechaAlta, $cadena, $empresa, $cuit, $ctaId){
//controla que el cuit no exista ya como cuenta que no sea prospecto.
if($cuit){
if(empty($cadena)){
if(dac_existeCuitCuenta($empresa, $cuit, $ctaId)){
echo "El cuit ya existe en una cuenta."; exit;
};
}
}
//Si cuenta actual es solicitud de Alta
if($estadoDDBB == 'SolicitudAlta'){ //$estadoCambio = 'ALTA';
if($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo "Debe esperar a que la cuenta esté dada de alta."; exit;
}
//Si estado actual es Alta, se dará de alta la cuenta con los datos que faltan cargar.
$fechaAlta = date("Y-m-d H:i:s");
return $fechaAlta;
} else {
if (empty($fechaAlta) || $fechaAlta == "0000-00-00 00:00:00" || $fechaAlta == "1899-12-30 00:00:00" || $fechaAlta == "1899-01-01 00:00:00" || $fechaAlta == "1899-11-22 00:00:00" || $fechaAlta == "1899-12-23 00:00:00" || $fechaAlta == "1900-01-01 00:00:00") {
if($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$fechaAlta == "2001-01-01 00:00:00";
return $fechaAlta;
} /*else {
echo "Debe colocar una fecha de alta de cuenta correcta."; exit;
}*/
}
}
return FALSE;
}
function dac_registrarEstado($origen, $origenId, $est, $estado) {
$estadoObject = DataManager::newObjectOfClass('TEstado');
$estadoObject->__set('Origen' , $origen);
$estadoObject->__set('IDOrigen' , $origenId);
$estadoObject->__set('Fecha' , date("Y-m-d h:i:s"));
$estadoObject->__set('UsrCreate', $_SESSION["_usrid"]);
$estadoObject->__set('Estado' , $est);
$estadoObject->__set('Nombre' , $estado);
$estadoObject->__set('ID' , $estadoObject->__newID());
$IDEstado = DataManager::insertSimpleObject($estadoObject);
if(!$IDEstado){
echo "Error al intentar registrar el estado de la solicitud. Consulte con el administrador de la web."; exit;
}
}
//**************//
?><file_sep>/cadenas/logica/update.cadena.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$empresa = (isset($_POST['empresa'])) ? $_POST['empresa'] : NULL;
$cadId = (isset($_POST['cadid'])) ? $_POST['cadid'] : NULL;
$cadena = (isset($_POST['cadena'])) ? $_POST['cadena'] : NULL;
$nombre = (isset($_POST['nombre'])) ? strtoupper($_POST['nombre']) : NULL;
$idCuentas = (isset($_POST['cuentaId'])) ? $_POST['cuentaId'] : NULL;
$tiposCadena= (isset($_POST['tipoCadena'])) ? $_POST['tipoCadena'] : NULL;
if(empty($empresa)){
echo "No se registra empresa seleccionada."; exit;
}
if(empty($cadId)){
//Si cadena es vacía, significa que se va a crear una cadena nueva.
$cadena = DataManager::dacLastId('cadenas', 'IdCadena');
if(!$cadena){
echo "No se pudo crear un número de cadena."; exit;
}
}
if(empty($nombre)){
echo "Indique nombre de la cadena."; exit;
} else {
//Comprobar que nombre de cadena no exista
$cont = 0;
$nombre = mb_strtoupper(trim(str_replace(" ", " ", $nombre)),"UTF-8" );
$cadenas = DataManager::getCadenas($empresa);
foreach ($cadenas as $k => $cad) {
$cadNombre = $cad['NombreCadena'];
if(!strcasecmp($nombre, $cadNombre)) {
$cont++;
}
}
if($cadId == 0) {$cont++;}
if($cont > 1){ echo "La cadena ya existe.".$cont; exit; }
}
if(count($idCuentas) < 1) {
echo "Debe relacionar una cuenta."; exit;
} else {
//Controla duplicados
if(count($idCuentas) != count(array_unique($idCuentas))){
echo "Existen registros duplicados."; exit;
}
}
//controlar que CADA cuenta no exista duplicada en cnCadenas
foreach ($idCuentas as $k => $cadIdCuenta) {
$cuentas = DataManager::getCuentasCadena($empresa, NULL, $cadIdCuenta);
if (count($cuentas)) {
foreach ($cuentas as $k => $cta) {
$idCuenta = $cta['IdCliente'];
$idCadena = $cta['IdCadena'];
if($cadena != $idCadena){
echo "La cuenta ".$idCuenta." ya existe registrada en la cadena ".$idCadena; exit;
}
}
}
}
//-------------------//
// GUARDAR CAMBIOS //
$cadObject = ($cadId) ? DataManager::newObjectOfClass('TCadena', $cadId) : DataManager::newObjectOfClass('TCadena');
$cadObject->__set('Empresa' , $empresa);
$cadObject->__set('Cadena' , $cadena);
$cadObject->__set('Nombre' , $nombre);
if($cadId) {
DataManagerHiper::updateSimpleObject($cadObject, $cadId);
DataManager::updateSimpleObject($cadObject);
// MOVIMIENTO de Cuenta
$tipoMov = 'UPDATE';
} else {
$cadObject->__set('ID' , $cadObject->__newID());
DataManagerHiper::_getConnection('Hiper'); //Controla conexión a HiperWin
$ID = DataManager::insertSimpleObject($cadObject);
DataManagerHiper::insertSimpleObject($cadObject, $ID);
//MOVIMIENTO de CUENTA
$cadId = $ID;
$tipoMov = 'INSERT';
}
// MOVIMIENTO de CUENTA
$movimiento = 'ID_'.$cadId."_CADENA_".$cadena;
//------------------------------//
// UPDATE CUENTAS RELACIONADAS //
if(count($idCuentas)){
$cuentas = DataManager::getCuentasCadena($empresa, $cadena);
if (count($cuentas)) {
foreach ($cuentas as $k => $cta) {
$idCtaRel = $cta['cadid'];
$idCuenta = $cta['IdCliente'];
$id = DataManager::getCuenta('ctaid', 'ctaidcuenta', $idCuenta, $empresa);
$nombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $idCuenta, $empresa);
//Creo Array de Cuentas Relacionadas
$arrayCadDDBB[] = $idCuenta;
if (!in_array($idCuenta, $idCuentas)) { //DELETE de cadenas relacionadas
$cadRelObject = DataManager::newObjectOfClass('TCadenaCuentas', $idCtaRel);
$cadRelObject->__set('ID', $idCtaRel);
$ID = $cadRelObject->__get('ID');
DataManagerHiper::deleteSimpleObject($cadRelObject, $ID);
DataManager::deleteSimpleObject($cadRelObject);
} else {
//UPDATE
$cadRelObject = DataManager::newObjectOfClass('TCadenaCuentas', $idCtaRel);
$cadRelObject->__set('TipoCadena', $tiposCadena[$k]);
$ID = $cadRelObject->__get('ID');
DataManagerHiper::updateSimpleObject($cadRelObject, $ID);
DataManager::updateSimpleObject($cadRelObject);
}
}
foreach ($idCuentas as $k => $cadIdCuenta) {
if (!in_array($cadIdCuenta, $arrayCadDDBB)) {
//INSERT
$cadRelObject = DataManager::newObjectOfClass('TCadenaCuentas');
$cadRelObject->__set('Empresa' , $empresa);
$cadRelObject->__set('Cadena' , $cadena);
$cadRelObject->__set('Cuenta' , $cadIdCuenta);
$cadRelObject->__set('TipoCadena', $tiposCadena[$k]);
$cadRelObject->__set('ID' , $cadRelObject->__newID());
DataManagerHiper::_getConnection('Hiper'); //Controla conexión a HiperWin
$IDCuentaRel = DataManager::insertSimpleObject($cadRelObject);
DataManagerHiper::insertSimpleObject($cadRelObject, $IDCuentaRel);
}
}
} else { //INSERT - Si no hay cuentas relacionadas, las crea
foreach ($idCuentas as $k => $cadIdCuenta) {
//INSERT
$cadRelObject = DataManager::newObjectOfClass('TCadenaCuentas');
$cadRelObject->__set('Empresa' , $empresa);
$cadRelObject->__set('Cadena' , $cadena);
$cadRelObject->__set('Cuenta' , $cadIdCuenta);
$cadRelObject->__set('TipoCadena', $tiposCadena[$k]);
$cadRelObject->__set('ID' , $cadRelObject->__newID());
DataManagerHiper::_getConnection('Hiper'); //Controla conexión a HiperWin
$IDCuentaRel = DataManager::insertSimpleObject($cadRelObject);
DataManagerHiper::insertSimpleObject($cadRelObject, $IDCuentaRel);
}
}
} else { echo "No se registran cuentas relacionadas para editar"; exit; }
//-------------------//
// MOVIMIENTO CADENA //
dac_registrarMovimiento($movimiento, $tipoMov, "TCadena", $cadId);
echo 1; exit;
?><file_sep>/informes/logica/exportar.tablatransfer.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
//*******************************************
$fechaDesde = (isset($_POST['fechaDesde'])) ? $_POST['fechaDesde'] : NULL;
$fechaHasta = (isset($_POST['fechaHasta'])) ? $_POST['fechaHasta'] : NULL;
//*******************************************
if(empty($fechaDesde) || empty($fechaHasta)){
echo "Debe completar las fechas de exportación"; exit;
}
$fechaInicio = new DateTime(dac_invertirFecha($fechaDesde));
$fechaFin = new DateTime(dac_invertirFecha($fechaHasta));
$fechaFin->modify("+1 day");
//*************************************************
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=TablaTransfers-".date('d-m-y').".xls");
?>
<HTML LANG="es">
<TITLE>::. Exportacion de Datos (Tabla Transfers) .::</TITLE>
<head></head>
<body>
<table border="0">
<thead>
<tr>
<td scope="col" >ptid</td>
<td scope="col" >ptidpedido</td>
<td scope="col" >ptidvendedor</td>
<td scope="col" >ptparaidusr</td>
<td scope="col" >ptiddrogueria</td>
<td scope="col" >ptnroclidrog</td>
<td scope="col" >ptidclineo</td>
<td scope="col" >ptclirs</td>
<td scope="col" >ptclicuit</td>
<td scope="col" >ptdomicilio</td>
<td scope="col" >ptcontacto</td>
<td scope="col" >ptidart</td>
<td scope="col" >ptunidades</td>
<td scope="col" >ptprecio</td>
<td scope="col" >ptdescuento</td>
<td scope="col" >ptcondpago</td>
<td scope="col" >ptfechapedido</td>
<td scope="col" >ptidadmin</td>
<td scope="col" >ptnombreadmin</td>
<td scope="col" >ptfechaexp</td>
<td scope="col" >ptliquidado</td>
<td scope="col" >ptactivo</td>
</tr>
</thead>
<?php
$transfers = DataManager::getTransfersPedido(0, $fechaInicio->format("Y-m-d"), $fechaFin->format("Y-m-d"));
//DataManager::getTransfers2(0, $fechaInicio->format("Y-m-d"), $fechaFin->format("Y-m-d"));
if($transfers){
foreach ($transfers as $k => $transfer) {
$ptid = $transfer["ptid"];
$ptidpedido = $transfer["ptidpedido"];
$ptidvendedor = $transfer["ptidvendedor"];
$ptparaidusr = $transfer["ptparaidusr"];
$ptiddrogueria = $transfer["ptiddrogueria"];
$ptnroclidrog = $transfer["ptnroclidrog"];
$ptidclineo = $transfer["ptidclineo"];
$ptclirs = $transfer["ptclirs"];
$ptclicuit = $transfer["ptclicuit"];
$ptdomicilio = $transfer["ptdomicilio"];
$ptcontacto = $transfer["ptcontacto"];
$ptidart = $transfer["ptidart"];
$ptunidades = $transfer["ptunidades"];
$ptprecio = $transfer["ptprecio"];
$ptdescuento = $transfer["ptdescuento"];
$ptcondpago = $transfer["ptcondpago"];
$ptfechapedido = $transfer["ptfechapedido"];
$ptidadmin = $transfer["ptidadmin"];
$ptnombreadmin = $transfer["ptnombreadmin"];
$ptfechaexp = $transfer["ptfechaexp"];
$ptliquidado = $transfer["ptliquidado"];
$ptactivo = $transfer["ptactivo"];
echo sprintf("<tr align=\"left\">");
echo sprintf("<td >%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td >%s</td><td >%s</td><td >%s</td><td >%s</td>", $ptid, $ptidpedido, $ptidvendedor, $ptparaidusr, $ptiddrogueria, $ptnroclidrog, $ptidclineo, $ptclirs, $ptclicuit, $ptdomicilio, $ptcontacto, $ptidart, $ptunidades, $ptprecio, $ptdescuento, $ptcondpago, $ptfechapedido, $ptidadmin, $ptnombreadmin, $ptfechaexp, $ptliquidado, $ptactivo);
echo sprintf("</tr>");
}
}
?>
</table>
</body>
</html>
<file_sep>/noticias/ver.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_idnt = empty($_REQUEST['idnt']) ? 0 : $_REQUEST['idnt'];
$_sms = empty($_GET['sms']) ? 0 : $_GET['sms'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/noticias/': $_REQUEST['backURL'];
if ($_idnt) {
$_noticia = DataManager::newObjectOfClass('TNoticia', $_idnt);
$_ntitulo = $_noticia->__get('Titulo');
$_nfecha = $_noticia->__get('Fecha');
$_f = explode(" ", $_nfecha);
list($ano, $mes, $dia) = explode("-", $_f[0]);
$_nfecha = $dia."-".$mes."-".$ano;
$_nnoticia = $_noticia->__get('Descripcion');
$_nlink = $_noticia->__get('Link');
} ?>
<!DOCTYPE html>
<html>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = '';
$_subsection = '';
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav> <!-- fin menu -->
<main class="cuerpo">
<?php if($_idnt) { ?>
<div class="boxbody_noti_select">
<article>
<header>Noticia Seleccionada</header>
<section><titulo><?php echo $_ntitulo; ?></titulo> </section>
<section><subtitulo><?php echo $_nfecha; ?></subtitulo></section>
<section><subtitulo><?php if($_nlink != ""){ echo "Link --> "; ?><a href="<?php echo $_nlink; ?>"/> <?php echo $_ntitulo; ?> </a> <?php }?></subtitulo></section>
<section><body><?php echo @$_nnoticia; ?> </body></section>
</article>
</div> <!-- boxbody -->
<?php } ?>
<?php
$_total = DataManager::getNumeroFilasTotales('TNoticia', 0);
$_noticiastodas = DataManager::getNoticias();
for( $k=0; $k < $_total; $k++ ){
$_noticiat = $_noticiastodas[$k];
$fecha = explode(" ", $_noticiat["ntfecha"]);
list($ano, $mes, $dia) = explode ("-", $fecha[0]);
$_fecha = $dia."-".$mes."-".$ano;
$_titulo = $_noticiat["nttitulo"];
$_nlink = $_noticiat["ntlink"];
$_descripcion = $_noticiat["ntdescripcion"];
?>
<div class="boxbody_noti">
<article>
<section><titulo><?php echo $_titulo; ?></titulo></section>
<section><subtitulo><?php echo $_fecha; ?></subtitulo></section>
<section><subtitulo><?php if($_nlink != ""){ echo "Link --> "; ?><a href="<?php echo $_nlink; ?>"/> <?php echo $_titulo; ?> </a> <?php }?></subtitulo></section>
<section><body><?php echo $_descripcion; ?></body></section>
</article>
</div>
<?php
} ?>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/relevamiento/logica/update.relevamiento.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_relid = (isset($_POST['relid'])) ? $_POST['relid'] : NULL;
$_nro = (isset($_POST['nro'])) ? $_POST['nro'] : NULL;
$_orden = (isset($_POST['orden'])) ? $_POST['orden'] : NULL;
$_tipo = (isset($_POST['tipo'])) ? $_POST['tipo'] : NULL;
$_pregunta = (isset($_POST['pregunta'])) ? $_POST['pregunta'] : NULL;
$_nulo = (isset($_POST['nulo'])) ? $_POST['nulo'] : NULL;
$_nulo = ($_nulo == 'on') ? 1 : 0;
if (empty($_nro) || !is_numeric($_nro)) {
echo "Ingrese un número de Relevamiento"; exit;
}
if (empty($_orden) || !is_numeric($_orden)) {
echo "Ingrese orden de aparición de la pregunta"; exit;
}
if (empty($_tipo)) {
echo "Indique un tipo de respuesta"; exit;
}
if (empty($_pregunta)) {
echo "Ingrese una pregunta"; exit;
}
//**************************//
// Acciones Guardar //
//**************************//
$_relobject = ($_relid) ? DataManager::newObjectOfClass('TRelevamiento', $_relid) : DataManager::newObjectOfClass('TRelevamiento');
$_relobject->__set('Relevamiento' , $_nro);
$_relobject->__set('Tipo' , $_tipo);
$_relobject->__set('Orden' , $_orden);
$_relobject->__set('Nulo' , $_nulo);
$_relobject->__set('Pregunta' , $_pregunta);
$_relobject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$_relobject->__set('LastUpdate' , date("Y-m-d"));
if ($_relid) {
//Modifica Cliente
DataManager::updateSimpleObject($_relobject);
} else {
$_relobject->__set('ID' , $_relobject->__newID());
$_relobject->__set('Activo' , 1);
$ID = DataManager::insertSimpleObject($_relobject);
}
echo "1"; exit;
?><file_sep>/rendicion/detalle_rendicion.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/rendicion/': $_REQUEST['backURL'];
$error = 0;
$_msg = "";
$_usrname = "";
$_rendiciones = 0;
$_rendActiva = 0;
$_rendDepositoVend = 0;
$_rendRetencionVend = 0;
if ($_SESSION["_usrrol"]=="V"){
$_nro_rendicion = empty($_REQUEST['nro_rendicion']) ? 1 : $_REQUEST['nro_rendicion'];
$_usrid = $_SESSION["_usrid"];
$_usrname = $_SESSION["_usrname"];
} else {
$_nro_rendicion = empty($_POST['nro_anular']) ? 0 : $_POST['nro_anular'];
$_usrid = empty($_POST['vendedor']) ? 0 : $_POST['vendedor'];
/****************/
/* CONTROLES */
/****************/
if($_usrid == 'Vendedor...'){
$_msg = "No seleccionó ningún vendedor </br>";
$error = 1;
//header('Location:' . $backURL);
} else {
//Nombre Vendedor
$_nombreVen = DataManager::getUsuario('unombre', $_usrid);
/*$_Vendedor = DataManager::getVendedor( 1, $_usrid );
foreach ($_Vendedor as $k => $_Ven){
//$_Ven = $_Vendedor[$k];
$_nombreVen = $_Ven['unombre'];
}*/
$_usrname = "Consulta de Administración </br> Vendedor: ".$_nombreVen;
}
if($_nro_rendicion == 0){
$_msg = "No indicó ninguna rendición </br>";
}
/***************/
}
if($error == 0) {
//Consulto si la rendición fue enviada (activa)
$_rendiciones = DataManager::getRendicion($_usrid, $_nro_rendicion, '1');
if (count($_rendiciones)){
$_rendActiva = 1; //rendición activa
}
}
$_button_print = sprintf( "<a id=\"imprime\" title=\"Imprimir Rendición\" onclick=\"javascript:dac_imprimirMuestra('rendicion')\">%s</a>", "<img class=\"icon-print\"/>");
?>
<!DOCTYPE html>
<html >
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<div id="rendicion" style="margin:20px;" align="center"> <?php
$_rendicion = array();
if($error == 0){
$_rendicion = DataManager::getDetalleRendicion($_usrid, $_nro_rendicion);
}
if (count($_rendicion) > 0) { ?>
<div id="muestra-rendicion" align="center">
<table id="tabla_rendicion" border="1" class="display">
<thead>
<tr align="left">
<th colspan="7" align="center"><?php echo $_usrname;?></th>
<th colspan="7" align="center"> <?php
echo "Rendición N: ".$_nro_rendicion; ?>
</th>
<th colspan="5" align="center"> <?php
echo $_button_print;
if($_rendActiva == 0) { ?>
<div style="float:right; padding:20px;">RENDICIÓN YA ENVIADA</div> <?php
} ?>
</th>
</tr>
<tr align="center" style="font-weight:bold; background-color:#d9ebf4; color:#2D567F" height="40px">
<td colspan="3" align="center" style="background-color:#d9ebf4; color:#2D567F" >DATOS CLIENTE</td>
<td colspan="2" align="center" style="background-color:#d9ebf4; color:#2D567F" >RECIBO</td>
<td colspan="2" align="center" style="background-color:#d9ebf4; color:#2D567F" >FACTURA</td>
<td colspan="3" align="center" style="background-color:#d9ebf4; color:#2D567F" >IMPORTE</td>
<td colspan="3" align="center" style="background-color:#d9ebf4; color:#2D567F" >FORMA DE PAGO</td>
<td colspan="4" align="center" style="background-color:#d9ebf4; color:#2D567F" >PAGO POR BANCO</td>
<td colspan="2" align="center" style="background-color:#d9ebf4; color:#2D567F" >OTROS</td>
</tr>
<tr style="font-weight:bold; background-color:#EAEAEA" height="30px"> <!-- Títulos de las Columnas -->
<td align="center" hidden>Idrend</td>
<td align="center" >Código</td>
<td align="center" >Nombre</td>
<td align="center" >Zona</td>
<td align="center" >Tal</td>
<td align="center" >Nro</td>
<td align="center" >Nro</td>
<td align="center" >Fecha</td>
<td align="center" >Bruto</td>
<td align="center" >Dto</td>
<td align="center" >Neto</td>
<td align="center" >Efectivo</td>
<td align="center" >Transf</td>
<td align="center" >Retención</td>
<td align="center" >Banco</td>
<td align="center" >Número</td>
<td align="center" >Fecha</td>
<td align="center" >Importe</td>
<td align="center" >Observación</td>
<td align="center" >Diferencia</td>
</tr>
</thead>
<tbody> <?php
//SACAMOS LOS REGISTROS DE LA TABLA
$total_efectivo = 0;
$id_anterior = 0;
$id_cheque_anterior = 0;
$id_cheque = array();
$idfact_anterior = 0;
$ocultar = 0;
$total_transfer = 0;
$total_retencion = 0;
$total_diferencia = 0;
$total_importe = 0;
foreach ($_rendicion as $k => $_rend){
//$_rend = $_rendicion[$k];
$_rendID = $_rend['IDR'];
$_rendCodigo = $_rend['Codigo'];
$_rendNombre = ($_rendCodigo == 0) ? "" : $_rend['Nombre'];
$_rendZona = $_rend['Zona'];
$_rendTal = $_rend['Tal'];
$_rendIDRecibo = $_rend['IDRecibo'];
$_rendRnro = $_rend['RNro'];
$_rendFnro = $_rend['FNro'];
$_rendFactFecha = $_rend['FFecha'];
$_rendBruto = $_rend['Bruto'];
$_rendDto = ($_rend['Dto'] == '0') ? '' : $_rend['Dto'];
$_rendNeto = $_rend['Neto'];
$_rendEfectivo = ($_rend['Efectivo'] == '0.00') ? '' : $_rend['Efectivo'];
$_rendTransf = ($_rend['Transf'] == '0.00') ? '' : $_rend['Transf'];
$_rendRetencion = ($_rend['Retencion'] == '0.00') ? '' : $_rend['Retencion'];
$_rendIDCheque = $_rend['IDCheque'];
$_rendChequeBanco = $_rend['Banco'];
$_rendChequeNro = $_rend['Numero'];
$_rendChequefecha = $_rend['Fecha'];
$_rendChequeImporte = ($_rend['Importe'] == '0.00') ? '' : $_rend['Importe'];
$_rendObservacion = $_rend['Observacion'];
$_rendDiferencia = ($_rend['Diferencia'] == '0.00') ? '' : $_rend['Diferencia'];
$_rendDepositoVend = ($_rend['Deposito'] == '0.00') ? '' : $_rend['Deposito'];
$_rendRetencionVend = ($_rend['RetencionVend']== '0.00') ? '' : $_rend['RetencionVend'];
$_estilo = ((($_rendRnro % 2) == 0)? "par" : "impar");
//**************************************************//
//Controlo si repite registros de cheques y facturas//
//**************************************************//
if ($id_anterior == $_rendIDRecibo){
//********************//
// Al hacer el cambio a CUENTAS (que usa clientes en cero)
// debo discriminar los registros con nro cuenta cero y sin observación de ANULADO
//********************//
if($_rendCodigo == 0 && $_rendObservacion == "ANULADO") { } else {
//Busco cheque repetidos en la misma rendición para NO mostrarlos
for($j = 0; $j < (count($id_cheque)); $j++){
if($id_cheque[$j] == $_rendIDCheque){ $ocultar = 1;}
}
if ($ocultar == 1 && $_rendIDCheque != ""){
if ($idfact_anterior != $_rendFnro){
//CASO = 3; //CASO "C" VARIAS facturas - UN CHEQUE.
?><tr id="<?php echo $_rendIDRecibo; ?>" class="<?php echo $_estilo; ?>" onclick="dac_SelectFilaToDelete(<?php echo $_rendIDRecibo; ?>, <?php echo $_rendRnro; ?>)"> <?php
?> <td hidden> <?php echo $_rendID; ?> </td>
<td> <?php echo $_rendCodigo ; ?> </td>
<td> <?php echo $_rendNombre; ?> </td>
<td> <?php echo $_rendZona; ?> </td>
<td> <?php echo $_rendTal; ?> </td>
<td> <?php echo $_rendRnro; ?> </td>
<td> <?php echo $_rendFnro; ?> </td>
<td> <?php echo $_rendFactFecha; ?> </td>
<td align="right"> <?php echo $_rendBruto; ?> </td>
<td align="center"> <?php echo $_rendDto; ?> </td>
<td> <?php echo $_rendNeto; ?> </td>
<td align="right"> <?php echo $_rendEfectivo; ?> </td>
<td align="right"> <?php echo $_rendTransf; ?> </td>
<td align="right"> <?php echo $_rendRetencion; ?> </td>
<td hidden> <?php echo $_rendIDCheque; ?> </td>
<td></td> <td></td> <td></td> <td></td> <td></td> <td></td>
<?php
//******************************//
// CALCULOS PARA LOS TOTALES //
//******************************//
$total_efectivo = $total_efectivo + floatval($_rendEfectivo);
$total_transfer = $total_transfer + floatval($_rendTransf);
$total_retencion = $total_retencion + floatval($_rendRetencion);
//$total_diferencia = $total_diferencia + floatval($_rendDiferencia);
}/* else {
//caso en que no debe mostrarse la fila por ser repetida
}*/
} else {
if ($idfact_anterior == $_rendFnro){
//CASO = 2; //CASO "B". VARIOS CHEQUES - UNA facturas.
?><tr id="<?php echo $_rendIDRecibo; ?>" class="<?php echo $_estilo; ?>" onclick="dac_SelectFilaToDelete(<?php echo $_rendIDRecibo; ?> , <?php echo $_rendRnro; ?>)"> <?php
?> <td hidden> <?php echo $_rendID; ?> </td>
<td></td> <td><?php //echo $_rendNombre; ?></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td>
<td hidden> <?php echo $_rendIDCheque; ?> </td>
<td> <?php echo $_rendChequeBanco; ?> </td>
<td> <?php echo $_rendChequeNro; ?> </td>
<td> <?php echo $_rendChequefecha; ?> </td>
<td align="right"> <?php echo $_rendChequeImporte; ?> </td>
<td></td> <td></td> <?php
} else {
//CASO = 1; //CASO "A" SIN CHEQUES - VARIAS facturas.
?><tr id="<?php echo $_rendIDRecibo; ?>" class="<?php echo $_estilo; ?>" onclick="dac_SelectFilaToDelete(<?php echo $_rendIDRecibo; ?>, <?php echo $_rendRnro; ?>)"> <?php
?> <td hidden> <?php echo $_rendID; ?> </td>
<td> <?php //echo $_rendCodigo ; ?> </td>
<td> <?php //echo $_rendNombre; ?> </td>
<td> <?php //echo $_rendZona; ?> </td>
<td> <?php echo $_rendTal; ?> </td>
<td> <?php echo $_rendRnro; ?> </td>
<td> <?php echo $_rendFnro; ?> </td>
<td> <?php echo $_rendFactFecha; ?> </td>
<td align="right"> <?php echo $_rendBruto; ?> </td>
<td align="center"> <?php echo $_rendDto; ?> </td>
<td align="right"> <?php echo $_rendNeto; ?> </td>
<td align="right"> <?php echo $_rendEfectivo; ?> </td>
<td align="right"> <?php echo $_rendTransf; ?> </td>
<td align="right"> <?php echo $_rendRetencion; ?> </td>
<td hidden> <?php echo $_rendIDCheque; ?> </td>
<td> <?php echo $_rendChequeBanco; ?> </td>
<td> <?php echo $_rendChequeNro; ?> </td>
<td> <?php echo $_rendChequefecha; ?> </td>
<td align="right"> <?php echo $_rendChequeImporte; ?> </td>
<td></td> <td></td> <?php
//**********************************
// CALCULOS PARA LOS TOTALES
//**********************************
$total_efectivo = $total_efectivo + floatval($_rendEfectivo);
$total_transfer = $total_transfer + floatval($_rendTransf);
$total_retencion = $total_retencion + floatval($_rendRetencion);
}
}
} //fin if anulado
} else {
//***********************************
//si cambia el nro de cheque resetea id_cheque y completa toda la fila de datos
//**********************************
unset($id_cheque);
$id_cheque = array();
?>
<tr id="<?php echo $_rendIDRecibo; ?>" class="<?php echo $_estilo; ?>" onclick="dac_SelectFilaToDelete(<?php echo $_rendIDRecibo; ?>, <?php echo $_rendRnro; ?>)">
<td hidden> <?php echo $_rendID; ?> </td>
<td> <?php echo $_rendCodigo ; ?> </td>
<td> <?php echo $_rendNombre; ?> </td>
<td> <?php echo $_rendZona; ?> </td>
<td> <?php echo $_rendTal; ?> </td>
<td> <?php echo $_rendRnro; ?> </td>
<td> <?php echo $_rendFnro; ?> </td>
<td> <?php echo $_rendFactFecha; ?> </td>
<td align="right"> <?php echo $_rendBruto; ?> </td>
<td align="center"> <?php echo $_rendDto; ?> </td>
<td align="right"> <?php echo $_rendNeto; ?> </td>
<td align="right"> <?php echo $_rendEfectivo; ?> </td>
<td align="right"> <?php echo $_rendTransf; ?> </td>
<td align="right"> <?php echo $_rendRetencion; ?> </td>
<td hidden> <?php echo $_rendIDCheque; ?> </td>
<td> <?php echo $_rendChequeBanco; ?> </td>
<td> <?php echo $_rendChequeNro; ?> </td>
<td> <?php echo $_rendChequefecha; ?> </td>
<td align="right"> <?php echo $_rendChequeImporte; ?> </td>
<td> <?php echo $_rendObservacion; ?> </td>
<td align="right"> <?php echo $_rendDiferencia; ?></td> <?php
//**********************************
// CALCULOS PARA LOS TOTALES
//**********************************
$total_efectivo = $total_efectivo + floatval($_rendEfectivo);
$total_transfer = $total_transfer + floatval($_rendTransf);
$total_retencion = $total_retencion + floatval($_rendRetencion);
$total_diferencia = $total_diferencia + floatval($_rendDiferencia);
} ?>
</tr><?php
//**********************************
//CALCULOS PARA TOTALES IMPORTE. Sin discriminar si hay varios cheques
//**********************************
if ($id_cheque_anterior != $_rendIDCheque){
//controla que el cheque no pertenezca a varias facturas
for($j = 0; $j < (count($id_cheque)); $j++){
if($id_cheque[$j] == $_rendIDCheque){ $ocultar = 1; }
}
if ($ocultar != 1){
$total_importe = $total_importe + floatval($_rendChequeImporte);
}
}
//**********************************
if ($_rendIDCheque != ""){
if ($ocultar != 1){$id_cheque[] = $_rendIDCheque;}
}
$ocultar = 0;
$idfact_anterior = $_rendFnro;
$id_anterior = $_rendIDRecibo; //Cierrre de calculo de TOTALES
$id_cheque_anterior = $_rendIDCheque;
} //FIN del FOR Rendicion ?>
</tbody>
<tfoot>
<tr>
<th colspan="10" align="right" style="height:40px; background-color:#d9ebf4; color:#2D567F;">TOTALES</th>
<th align="right" style="width:60px; text-align:right; height:40px; font-weight:bold;" ><?php
if ($total_efectivo != 0) {
$total = $total_efectivo;
$total_efectivo = $total_efectivo - (floatval($_rendRetencionVend) + floatval($_rendDepositoVend)); ?>
<?php echo number_format(round($total_efectivo,2),2);
}?>
</th>
<th align="right" style="font-weight:bold;"><?php if ($total_transfer != 0) {echo "$".$total_transfer;} ?></th>
<th align="right" style="font-weight:bold;"><?php if ($total_retencion != 0) {echo "$".$total_retencion;} ?></th>
<th colspan="3" style="background-color:#d9ebf4;"></th>
<th align="right"><?php if ($total_importe != 0) {echo "$".$total_importe;} ?></th>
<th style="background-color:#d9ebf4;"></th>
<th align="right"><?php if ($total_diferencia != 0) {echo "$".$total_diferencia;} ?></th>
</tr>
<tr>
<th colspan="19" style="height:20px; "></th>
</tr>
<tr >
<th colspan="13" align="right" style="background-color:#d9ebf4; color:#2D567F;">
<label>Boleta de Depósito: </label>
</th>
<th style="height:40px; font-weight:bold; text-align:center;">
<?php echo $_rendDepositoVend; ?>
</th>
<th align="right" style="background-color:#d9ebf4; color:#2D567F;">
<label>Retención: </label>
</th>
<th style="height:40px; font-weight:bold; text-align:center;">
<?php echo $_rendRetencionVend; ?>
</th>
<th colspan="3" style="background-color:#d9ebf4;">
</th>
</tr>
</tfoot>
</table>
</div> <!-- FIN muestra-rendicion --> <?php
} else { ?>
<div align="center">
<table id="tabla_rendicion" border="1" class="display">
<thead>
<tr align="left">
<th colspan="7" align="center"><?php echo $_usrname;?></th>
<th colspan="6" align="center"> <?php
echo "Rendición N: ".$_nro_rendicion; ?>
</th>
<th colspan="6" align="center"> <?php
echo "No existen datos en la rendición indicada. </br>";
echo $_msg;?>
</th>
</tr>
<thead>
</table>
</div> <?php
}?>
</div><!-- FIN RENDICIÓN -->
</body>
</html>
<file_sep>/js/ajax/getArticulos.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$laboratorio = (isset($_POST['idlab'])) ? $_POST['idlab'] : NULL;
$empresa = (isset($_POST['idemp'])) ? $_POST['idemp'] : NULL;
if (!empty($laboratorio)) {
$articulos = DataManager::getArticulos(0, 1000, 1, 1, $laboratorio, $empresa);
if (count($articulos)) {
echo '<table id="tblArticulos" border="0" align="center" style=\"table-layout:fixed\">';
echo '<thead><tr align="left"><th>Id</th><th>Nombre</th><th>Precio</th></tr></thead>';
echo '<tbody>';
foreach ($articulos as $k => $art) {
$art = $articulos[$k];
$id = $art['artid'];
$idArt = $art['artidart'];
$nombre = $art["artnombre"];
$precio = str_replace('"', '', json_encode($art["artprecio"])); $art["artprecio"];
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr id=art".$id." class=".$clase." onclick=\"javascript:dac_cargarArticuloCondicion('$id', '$idArt', '$nombre', '$precio', '$_b1', '$_b2', '$_desc1', '$_desc2', '$_cantmin')\"><td>".$idArt."</td><td>".$nombre."</td><td>".$precio."</td></tr>";
}
echo '</tbody></table>';
} else {
echo '<table border="0" align="center"><tr><td >No hay artículos activos. </td></tr></table>';
}
} else {
echo '<table border="0" align="center"><tr><td >Error al seleccionar el laboratorio </td></tr></table>';
}
?><file_sep>/planificacion/detalle_planificacion.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_fecha_planif = empty($_REQUEST['fecha_planif']) ? date("d-m-Y") : $_REQUEST['fecha_planif'];
$_button_print = sprintf( "<a id=\"imprime\" title=\"Imprimir Planificación\" onclick=\"javascript:dac_imprimirMuestra('muestra_planif')\">%s</a>", "<img class=\"icon-print\"/>");
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
?>
<!DOCTYPE html>
<html >
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "planificacion";
$_subsection = "mis_pedidos";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav> <!-- fin menu -->
<main class="cuerpo">
<div class="cbte">
<div id="muestra_planif">
<div class="cbte_header">
<div class="cbte_boxheader" style="text-align: left;
float: left; max-width: 400px; min-width: 300px;">
<?php echo $cabeceraPedido; ?>
</div>
<div class="cbte_boxheader" style="text-align: left;
float: left; max-width: 400px; min-width: 300px;" >
<h2 style="font-size: 18px;">PLANIFICACIÓN (<?php echo $_fecha_planif; ?>)</br>
<?php echo $_SESSION["_usrname"]; ?></h2>
</div>
</div>
<?php
$_planificacion = DataManager::getDetallePlanificacion($_fecha_planif, $_SESSION["_usrid"]);
if (count($_planificacion)){ ?>
<div class="cbte_boxcontent2">
<table class="datatab_detalle" width="100%" style="border:2px solid #999;">
<thead>
<tr align="left">
<th scope="col" width="8%" height="30" style="border-left: 1px solid #999; text-align: center;">Cliente</th>
<th scope="col" width="10%" style="border-left: 1px solid #999; text-align: center;">Nombre</th>
<th scope="col" width="10%" style="border-left: 1px solid #999; text-align: center;">Domicilio</th>
<th scope="col" width="10%" style="border-left: 1px solid #999; text-align: center;">Acción</th>
<th scope="col" width="13%" style="border-left: 1px solid #999; text-align: center;">Trabaja con...</th>
<th scope="col" width="39%" style="border-left: 1px solid #999; text-align: center;">Observación</th>
<th scope="col" width="10%" style="border-left: 1px solid #999; text-align: center;">Sello</th>
</tr>
</thead>
<?php
foreach ($_planificacion as $k => $_planif){
$_planif = $_planificacion[$k];
$_planifcliente = $_planif["planifidcliente"];
$_planifnombre = $_planif["planifclinombre"];
$_planifdir = $_planif["planifclidireccion"];
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"100\" align=\"center\" style=\"border:1px solid #999; border-right: none;\" >%s</td><td style=\"border:1px solid #999; border-right: none;\">%s</td><td style=\"border:1px solid #999; border-right: none;\">%s</td><td style=\"border:1px solid #999; border-right: none;\">%s</td><td style=\"border:1px solid #999; border-right: none;\">%s</td><td style=\"border:1px solid #999; border-right: none;\">%s</td><td style=\"border:1px solid #999; border-right: none;\">%s</td>", $_planifcliente, $_planifnombre, $_planifdir, '','','','');
echo sprintf("</tr>");
} ?>
<tr height="30" align="right">
<td colspan="7" style="border:none; padding-right:150px;"> Firma Vendedor: </td>
</tr>
<tr height="30" bordercolor="#FFFFFF">
<td colspan="7" style="border:none;"></td>
</tr>
</table>
</div> <!-- cbte_boxcontent2 --> <?php
} ?>
<div class="cbte_boxcontent2" align="center">
<?php echo $piePedido; ?>
</div> <!-- cbte_boxcontent2 -->
</div> <!-- muestra -->
<div class="cbte_boxcontent2" align="center">
<?php echo $_button_print; ?>
</div> <!-- cbte_boxcontent2 -->
</div> <!-- cbte -->
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/login/registrarme/index.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/detect.Browser.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php");
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/funciones.comunes.php");
?>
<!DOCTYPE html >
<html lang='es'>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php"; ?>
<script type="text/javascript">
$(document).ready(function() {
$("#emailconfirm").bind('paste', function(e) {
e.preventDefault();
});
});
</script>
</head>
<body>
<main class="cuerpo">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/login/registrarme/registrarme.php"); ?>
</main> <!-- fin cuerpo -->
</body>
</html><file_sep>/condicionpago/lista.php
<?php
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/condicionpago/': $_REQUEST['backURL'];
$btnNuevo = sprintf( "<a href=\"editar.php\" title=\"Nuevo\"><img class=\"icon-new\"/></a>");
$btnNuevo2 = sprintf( "<a href=\"editar_transfer.php\" title=\"Nuevo\"><img class=\"icon-new\"/></a>");
$_LPP = 25;
$_total = DataManager::getNumeroFilasTotales('TCondicionPago', 0);
$_paginas = ceil($_total/$_LPP);
$_pag = isset($_REQUEST['pag']) ? min(max(1,$_REQUEST['pag']),$_paginas) : 1;
$_GOFirst = sprintf("<a class=\"icon-go-first\" href=\"%s?pag=%d\"></a>", $backURL, 1);
$_GOPrev = sprintf("<a class=\"icon-go-previous\" href=\"%s?pag=%d\"</a>", $backURL, $_pag-1);
$_GONext = sprintf("<a class=\"icon-go-next\" href=\"%s?pag=%d\"></a>", $backURL, $_pag+1);
$_GOLast = sprintf("<a class=\"icon-go-last\" href=\"%s?pag=%d\"></a>", $backURL, $_paginas);
$_total = DataManager::getNumeroFilasTotales('TCondiciontransfer', 0);
$_paginas2 = ceil($_total/$_LPP);
$_pag2 = isset($_REQUEST['pag2']) ? min(max(1,$_REQUEST['pag2']),$_paginas2) : 1;
$_GOFirst2 = sprintf("<a class=\"icon-go-first\" href=\"%s?pag2=%d\"></a>", $backURL, 1);
$_GOPrev2 = sprintf("<a class=\"icon-go-previous\" href=\"%s?pag2=%d\"></a>", $backURL, $_pag2-1);
$_GONext2 = sprintf("<a class=\"icon-go-next\" href=\"%s?pag2=%d\"></a>", $backURL, $_pag2+1);
$_GOLast2 = sprintf("<a class=\"icon-go-last\" href=\"%s?pa2g=%d\"></a>", $backURL, $_paginas2);
?>
<div class="box_body"> <!-- datos -->
<div class="barra">
<div class="bloque_5">
<h1>Condiciones de Pago (Neo-farma)</h1>
</div>
<div class="bloque_5">
<?php echo $btnNuevo; ?>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<table id="tblcondiciones">
<thead>
<tr>
<td scope="col" width="15%">Código</td>
<td scope="col" width="35%">Nombre</td>
<td scope="col" width="20%">Días</td>
<td scope="col" width="20%" align="center">%</td>
<td scope="colgroup" colspan="3" width="30%" align="center">Acciones</td>
</tr>
</thead> <?php
$_condiciones = DataManager::getCondicionesDePago($_pag, $_LPP);
$_max = count($_condiciones);
for( $k=0; $k < $_LPP; $k++ ){
if ($k < $_max){
$_condicion = $_condiciones[$k];
$_id = $_condicion['condid'];
$_codigo = $_condicion['IdCondPago'];
$_nombre = DataManager::getCondicionDePagoTipos('Descripcion', 'ID', $_condicion['condtipo']);
$_dias = "(";
$_dias .= empty($_condicion['Dias1CP']) ? '0' : $_condicion['Dias1CP'];
$_dias .= empty($_condicion['Dias2CP']) ? '' : ', '.$_condicion['Dias2CP'];
$_dias .= empty($_condicion['Dias3CP']) ? '' : ', '.$_condicion['Dias3CP'];
$_dias .= empty($_condicion['Dias4CP']) ? '' : ', '.$_condicion['Dias4CP'];
$_dias .= empty($_condicion['Dias5CP']) ? '' : ', '.$_condicion['Dias5CP'];
$_dias .= " Días) ";
$_dias .= ($_condicion['Porcentaje1CP'] == '0.00') ? '' : ' '.$_condicion['Porcentaje1CP'].' %';
$_porc = ($_condicion['Porcentaje1CP']== '0.00') ? '' : $_condicion['Porcentaje1CP'];
$_status = ($_condicion['condactiva']) ? "<img class=\"icon-status-active\"/>" : "<img class=\"icon-status-inactive\"/>";
$_editar = sprintf( "<a href=\"editar.php?condid=%d&backURL=%s\" title=\"Editar\">%s</a>", $_condicion['condid'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit\"/>");
$_borrar = sprintf( "<a href=\"logica/changestatus.php?condid=%d&backURL=%s&pag=%s\" title=\"Cambiar Estado\">%s</a>", $_condicion['condid'], $_SERVER['PHP_SELF'], $_pag, $_status);
$_eliminar = sprintf ("<a href=\"logica/eliminar.condicion.php?condid=%d&backURL=%s&pag=%s\" title=\"Eliminar\" onclick=\"javascript:return confirm('¿Está Seguro que desea ELIMINAR LA CONDICIÓN?')\"> <img class=\"icon-delete\"/></a>", $_condicion['condid'], $_SERVER['PHP_SELF'], $_pag, "eliminar");
} else {
$_codigo = " ";
$_nombre = " ";
$_dias = " ";
$_porc = " ";
$_editar = " ";
$_borrar = " ";
$_eliminar = " ";
}
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_codigo, $_nombre, $_dias, $_porc, $_editar, $_borrar, $_eliminar);
echo sprintf("</tr>");
} ?>
</table>
</div>
<?php
if ( $_paginas > 1 ) {
$_First = ($_pag > 1) ? $_GOFirst : " ";
$_Prev = ($_pag > 1) ? $_GOPrev : " ";
$_Last = ($_pag < $_paginas) ? $_GOLast : " ";
$_Next = ($_pag < $_paginas) ? $_GONext : " ";
echo("<table class=\"paginador\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
echo sprintf("<td height=\"16\">Mostrando página %d de %d</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td>", $_pag, $_paginas, $_First, $_Prev, $_Next, $_Last);
echo("</tr></table>");
} ?>
</div>
<div class="box_seccion">
<div class="barra">
<div class="bloque_5">
<h1>Condiciones de Pago Transfer</h1>
</div>
<div class="bloque_5">
<?php echo $btnNuevo2; ?>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<table id="tblcondiciones">
<thead>
<tr>
<td scope="col" width="15%">Código</td>
<td scope="col" width="35%">Nombre</td>
<td scope="col" width="20%">Días</td>
<td scope="col" width="20%" align="center">%</td>
<td scope="colgroup" colspan="3" width="30%" align="center">Acciones</td>
</tr>
</thead>
<?php
$_condicionestransfer = DataManager::getCondicionesDePagoTransfer($_pag2, $_LPP);
$_max = count($_condicionestransfer);
for( $k=0; $k < $_LPP; $k++ ){
if ($k < $_max){
$_condiciontrans = $_condicionestransfer[$k];
$_id = $_condiciontrans['condid'];
$_codigo = $_condiciontrans['condcodigo'];
$_nombre = $_condiciontrans['condnombre'];
$_dias = $_condiciontrans['conddias'];
$_porc = $_condiciontrans['condporcentaje'];
$_status2 = ($_condiciontrans['condactiva']) ? "<img class=\"icon-status-active\" />" : "<img class=\"icon-status-inactive\"/>";
$_editar2 = sprintf( "<a href=\"editar_transfer.php?condid=%d&backURL=%s\" title=\"editar condicion transfer\">%s</a>", $_condiciontrans['condid'], $_SERVER['PHP_SELF'], "<img class=\"icon-edit\" />");
$_borrar2 = sprintf( "<a href=\"logica/changestatus.transfer.php?condid=%d&backURL=%s&pag2=%s\" title=\"Cambiar Estado\">%s</a>", $_condiciontrans['condid'], $_SERVER['PHP_SELF'], $_pag2, $_status2);
} else {
$_codigo = " ";
$_nombre = " ";
$_dias = " ";
$_porc = " ";
$_editar2 = " ";
$_borrar2 = " ";
}
echo sprintf("<tr class=\"%s\">", ((($k % 2) == 0)? "par" : "impar"));
echo sprintf("<td height=\"15\">%s</td><td>%s</td><td>%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td align=\"center\">%s</td>", $_codigo, $_nombre, $_dias, $_porc, $_editar2, $_borrar2);
echo sprintf("</tr>");
}
?>
</table>
</div>
<?php
if ( $_paginas2 > 1 ) {
$_First2 = ($_pag2 > 1) ? $_GOFirst2 : " ";
$_Prev2 = ($_pag2 > 1) ? $_GOPrev2 : " ";
$_Last2 = ($_pag2 < $_paginas2) ? $_GOLast2 : " ";
$_Next2 = ($_pag2 < $_paginas2) ? $_GONext2 : " ";
echo("<table class=\"paginador\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
echo sprintf("<td height=\"16\">Mostrando página %d de %d</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td><td width=\"25\">%s</td>", $_pag2, $_paginas2, $_First2, $_Prev2, $_Next2, $_Last2);
echo("</tr></table>");
} ?>
</div> <file_sep>/informes/logica/import.tableFile.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/PHPExcel/PHPDacExcel.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$tipo = (isset($_POST['tipo'])) ? $_POST['tipo'] : NULL;
if(empty($tipo)){
echo "Indique el tipo de informes a importar.";
} else {
$ruta = $_SERVER['DOCUMENT_ROOT'].'/pedidos/informes/';
$mensage = '';
if ($_FILES){
foreach ($_FILES as $key){
if($key['error'] == UPLOAD_ERR_OK ){
$fileTemp = $key['tmp_name'];
$fileSize = $key['size'];
if($fileSize > 800000){
echo "El archivo no debe superar los 800000 bytes"; exit;
}
//Convierto el excel en un array de arrays
$arrayXLS = PHPDacExcel::xls2array($fileTemp);
//consulta cantidad de columnas del XLS
$namesXLS = array_keys($arrayXLS[0]);
//consulta cantidad de columnas según la base de datos (y los nombres de columnas de la tabla)
$schemaDDBB = DataManager::informationSchema("'".$tipo."'");
switch($tipo){
case "abm":
$tableName = "TAbm";
break;
}
//consulto los nombre de la clase tabla
$objectColumnas = DataManager::newObjectOfClass($tableName);
$namesClass = $objectColumnas->__getClassVars();
if(count($namesXLS) != count($namesClass) || $tipo != $schemaDDBB[0]['TABLE_NAME']) {
echo 'Está intentando importar un archivo con diferente cantidad de campos o nombre de tablas'; exit;
} else {
foreach ($arrayXLS as $j => $registroXLS) {
if($j != 0) {
//saca el ID de cada registro
$idXLS = $registroXLS[$namesXLS[0]];
//Consulto por registro
$object = DataManager::newObjectOfClass($tableName, $idXLS);
$ID = $object->__get('ID');
foreach ($namesClass as $q => $cname){
$object->__set($cname, $registroXLS[$q]);
}
if($ID){ //Update
$ID = DataManager::updateSimpleObject($object);
} else { //Insert
$ID = DataManager::insertSimpleObject($object);
}
}
}
}
}
if ($key['error']==''){
$mensage .= $NombreOriginal.' --> Subido correctamente. </br>';
}
if ($key['error']!=''){//Si existio algún error retornamos un el error por cada archivo.
$mensage .= '-> Error al subir archivo '.$NombreOriginal.' debido a: \n'.$key['error'];
}
}
} else {
echo 'Debe seleccionar algún archivo.';
}
echo $mensage;
}
?><file_sep>/noticias/editar.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_idnt = empty($_REQUEST['idnt']) ? 0 : $_REQUEST['idnt'];
$_sms = empty($_GET['sms']) ? 0 : $_GET['sms'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/noticias/': $_REQUEST['backURL'];
if ($_sms){
$_ntitulo = $_SESSION['s_titulo'];
$_nfecha = $_SESSION['s_fecha'];
$_ndescripcion = $_SESSION['s_descripcion'];
$_nnoticia = $_SESSION['s_noticia'];
switch ($_sms) {
case 1: $_info = "Debe completar el campo del titulo."; break;
case 2: $_info = "La fecha es incorrecta."; break;
case 3: $_info = "El campo noticia debe completarse."; break;
}
} else {
if ($_idnt) {
$_noticia = DataManager::newObjectOfClass('TNoticia', $_idnt);
$_ntitulo = $_noticia->__get('Titulo');
$_nfecha = $_noticia->__get('Fecha');
$_f = explode(" ", $_nfecha);
list($ano, $mes, $dia) = explode("-", $_f[0]);
$_nfecha = $dia."-".$mes."-".$ano;
$_nnoticia = $_noticia->__get('Descripcion');
$_nlink = $_noticia->__get('Link');
} else {
$_ntitulo = "";
$_nfecha = "";
$_nnoticia = "";
$_nlink = "";
}
}
$_button = sprintf("<input type=\"submit\" id=\"btsend\" name=\"_accion\" value=\"Enviar\"/>");
$_action = sprintf("logica/update.noticia.php?idnt=%d", $_idnt);
?>
<!DOCTYPE html>
<html>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php";?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = 'noticias';
$_subsection = 'nueva_noticia';
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav> <!-- fin menu -->
<main class="cuerpo">
<div class="box_body">
<form name="fm_noticia" method="post" action="<?php echo $_action;?>">
<fieldset>
<legend>Noticia</legend>
<div class="bloque_1">
<?php
if ($_sms) {
echo sprintf("<p style=\"background-color:#fcf5f4;color:#ba140c;border:2px solid #ba140c;font-weight:bold;padding:4px;\">%s</p>", $_info);
} ?>
</div>
<div class="bloque_5">
<label for="ntitulo">Titulo *</label>
<input type="text" id="ntitulo" name="ntitulo" maxlength="80" value="<?php echo @$_ntitulo; ?>"/>
</div>
<div class="bloque_5">
<label for="nfecha">Fecha *</label>
<input type="text" name="nfecha" id="nfecha" maxlength="10" value="<?php echo @$_nfecha; ?>" readonly/>
</div>
<div class="bloque_1">
<label for="nnoticia">Noticia *</label>
<textarea id="nnoticia" name="nnoticia" value="<?php echo @$_nnoticia; ?>"/></textarea>
</div>
<div class="bloque_1">
<label for="nlink">Link</label>
<input type="text" id="nlink" name="nlink" maxlength="80" value="<?php echo @$_nlink; ?>"/>
</div>
<input type="hidden" name="idnt" value="<?php echo @$_idnt;?>"/>
<div class="bloque_8">
<label for="_accion"> </label> <?php echo $_button; ?>
</div>
</fieldset>
</form>
</div> <!-- boxbody -->
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html>
<!-- Scripts para calendario -->
<script type="text/javascript">
new JsDatePick({
useMode:2,
target:"nfecha",
dateFormat:"%d-%M-%Y"
});
</script><file_sep>/cuentas/lista.php
<?php
$empresa = isset($_REQUEST['empresa']) ? $_REQUEST['empresa'] : 1;
$tipo = isset($_REQUEST['tipo']) ? $_REQUEST['tipo'] : 'C';
$usrZonas = isset($_SESSION["_usrzonas"]) ? $_SESSION["_usrzonas"]: '';
?>
<script language="javascript" type="text/javascript">
// Select Cuentas //
function dac_selectCuentas(pag, rows, empresa, activos, tipo) {
$.ajax({
type : 'POST',
cache: false,
url : '/pedidos/cuentas/logica/ajax/getCuenta.php',
data: { pag : pag,
rows : rows,
empresa : empresa,
activos : activos,
tipo : tipo
},
beforeSend : function () {
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
if (resultado){
var tabla = resultado;
document.getElementById('tablaCuentas').innerHTML = tabla;
$('#box_cargando').css({'display':'none'});
} else {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
},
});
}
</script>
<div class="box_body"> <?php
$btnNuevo = sprintf( "<a href=\"editar.php\" title=\"Nuevo\"><img class=\"icon-new\"/></a>");
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/cuentas/' : $_REQUEST['backURL'];
$_LPP = 500;
$_total = count(DataManager::getCuentas(0, 0, $empresa, '', "'".$tipo."'", $usrZonas));
$_paginas = ceil($_total/$_LPP);
$_pag = isset($_REQUEST['pag']) ? min(max(1,$_REQUEST['pag']),$_paginas) : 1;
$_GOFirst = sprintf("<a class=\"icon-go-first\" href=\"%s?pag=%d&empresa=%d&tipo=%s\"></a>", $backURL, 1 , $empresa, $tipo);
$_GOPrev3 = sprintf("<a href=\"%s?pag=%d&empresa=%d&tipo=%s\">%s</a>", $backURL, $_pag-3 , $empresa, $tipo, $_pag-3);
$_GOPrev2 = sprintf("<a href=\"%s?pag=%d&empresa=%d&tipo=%s\">%s</a>", $backURL, $_pag-2 , $empresa, $tipo, $_pag-2);
$_GOPrev = sprintf("<a class=\"icon-go-previous\" href=\"%s?pag=%d&empresa=%d&tipo=%s\"></a>", $backURL, $_pag-1 , $empresa, $tipo);
$_GOActual = sprintf("%s", $_pag);
$_GONext = sprintf("<a class=\"icon-go-next\" href=\"%s?pag=%d&empresa=%d&tipo=%s\"></a>", $backURL, $_pag+1 , $empresa, $tipo);
$_GONext2 = sprintf("<a href=\"%s?pag=%d&empresa=%d&tipo=%s\">%s</a>", $backURL, $_pag+2 , $empresa, $tipo, $_pag+2);
$_GONext3 = sprintf("<a href=\"%s?pag=%d&empresa=%d&tipo=%s\">%s</a>", $backURL, $_pag+3 , $empresa, $tipo, $_pag+3);
$_GOLast = sprintf("<a class=\"icon-go-last\" href=\"%s?pag=%d&empresa=%d&tipo=%s\"></a>", $backURL, $_paginas, $empresa, $tipo);
?>
<fieldset id='box_cargando' class="msg_informacion">
<div id="msg_cargando"></div>
</fieldset>
<fieldset id='box_error' class="msg_error">
<div id="msg_error"></div>
</fieldset>
<fieldset id='box_confirmacion' class="msg_confirmacion">
<div id="msg_confirmacion"></div>
</fieldset>
<div class="barra">
<div class="bloque_7">
<input id="txtBuscar" type="search" autofocus placeholder="Buscar por Página"/>
<input id="txtBuscarEn" type="text" value="tblCuentas" hidden/>
</div>
<div class="bloque_7">
<select id="empselect" name="empselect" onchange="javascript:dac_selectCuentas(<?php echo $_pag; ?>, <?php echo $_LPP; ?>, empselect.value, '', tiposelect.value);"><?php
$empresas = DataManager::getEmpresas(1);
if (count($empresas)) {
foreach ($empresas as $k => $emp) {
$idemp = $emp["empid"];
$nombreEmp = $emp["empnombre"];
?><option id="<?php echo $idemp; ?>" value="<?php echo $idemp; ?>" <?php if ($empresa == $idemp){ echo "selected"; } ?> ><?php echo $nombreEmp; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<select id="tiposelect" name="tiposelect" onchange="javascript:dac_selectCuentas(<?php echo $_pag; ?>, <?php echo $_LPP; ?>, empselect.value, '', tiposelect.value);"/> <?php
$tiposCuenta = DataManager::getTiposCuenta(1);
if (count($tiposCuenta)) {
foreach ($tiposCuenta as $k => $tipoCta) {
$ctaTipoId = $tipoCta["ctatipoid"];
$ctaTipo = $tipoCta["ctatipo"];
$ctaTipoNombre = $tipoCta["ctatiponombre"];
?><option id="<?php echo $ctaTipoId; ?>" value="<?php echo $ctaTipo; ?>" <?php if ($tipo == $ctaTipo){ echo "selected"; } ?>><?php echo $ctaTipoNombre; ?></option><?php
}
} ?>
</select>
</div>
<div class="bloque_7">
<?php echo $btnNuevo ?>
</div>
<?php
echo "<script>";
echo "javascript:dac_selectCuentas($_pag, $_LPP, empselect.value, '', tiposelect.value)";
echo "</script>";
?>
<hr>
</div> <!-- Fin barra -->
<div class="lista_super">
<div id='tablaCuentas'></div>
</div> <!-- Fin listar -->
<?php
if ( $_paginas > 1 ) {
$_First = ($_pag > 1) ? $_GOFirst : " ";
$_Prev = ($_pag > 1) ? $_GOPrev : " ";
$_Last = ($_pag < $_paginas) ? $_GOLast : " ";
$_Next = ($_pag < $_paginas) ? $_GONext : " ";
$_Prev2 = $_Next2 = $_Prev3 = $_Next3 = '';
$_Actual= $_GOActual;
if ( $_paginas > 4 ) {
$_Prev2 = ($_pag > 2) ? $_GOPrev2 : " ";
$_Next2 = ($_pag < $_paginas-2) ? $_GONext2 : " ";
}
if ( $_paginas > 6 ) {
$_Prev3 = ($_pag > 3) ? $_GOPrev3 : " ";
$_Next3 = ($_pag < $_paginas-3) ? $_GONext3 : " ";
}
echo("<table class=\"paginador\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
echo sprintf("<td height=\"16\">Mostrando página %d de %d</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td><td width=\"20\">%s</td>", $_pag, $_paginas, $_First, $_Prev3, $_Prev2, $_Prev, $_Actual, $_Next, $_Next2, $_Next3, $_Last);
echo("</tr></table>");
} ?>
</div> <!-- Fin box body -->
<div class="box_seccion">
<div id="container"></div>
<div class="barra">
<div class="bloque_7">
<a title="Agenda" href="/pedidos/agenda/" target="_blank"> <img class="icon-calendar"/></a>
</div>
<div class="bloque_7">
<select id="selectFiltro">
<option value="ctaidcuenta">Cuenta</option>
<option value="ctanombre">Nombre</option>
<option value="ctacuit">Cuit</option>
</select>
</div>
<div class="bloque_5">
<input id="txtFiltro" onKeyPress="if (event.keyCode==13){ dac_mostrarFiltro(selectFiltro.value, this.value);return false;}" type="search" autofocus placeholder="Buscar..."/>
</div>
<hr>
</div> <!-- Fin barra -->
<div class="lista">
<div id='tablaFiltroCuentas'></div>
</div> <!-- Fin listar -->
<?php
$cuentasPendientes = DataManager::getCuentas(0, 0, $empresa, NULL, "'C', 'CT'", $usrZonas, 3, 'SolicitudAlta');
if (count($cuentasPendientes)) { ?>
<div class="barra" style="background-color: #E49044;">
<h1><strong>Existen Clientes con Solicitudes de Alta Pendientes</strong></h1>
<hr>
</div>
<div class="lista">
<?php
echo "<table id=\"tblFiltroCuentas\" style=\"table-layout:fixed;\">";
echo "<thead><tr align=\"left\"><th>Emp</th><th>Cuenta</th><th>Nombre</th><th>Ult Fecha</th></tr></thead>";
echo "<tbody>";
foreach ($cuentasPendientes as $k => $cuentaP) {
$id = $cuentaP['ctaid'];
$idCuenta = $cuentaP['ctaidcuenta'];
$fechaUpd = $cuentaP['ctaupdate'];
$idEmpresa = $cuentaP['ctaidempresa'];
$nombre = $cuentaP['ctanombre'];
$_editar = sprintf( "onclick=\"window.open('editar.php?ctaid=%d')\" style=\"cursor:pointer;\"",$id);
((($k % 2) == 0)? $clase="par" : $clase="impar");
echo "<tr class=".$clase.">";
echo "<td ".$_editar.">".$empresa."</td><td ".$_editar.">".$idCuenta."</td><td ".$_editar.">".$nombre."</td><td ".$_editar.">".$fechaUpd."</td>";
echo "</tr>";
}
echo "</tbody></table>";?>
</div> <!-- Fin listar --> <?php
} ?>
</div> <!-- Fin box_seccion -->
<hr>
<?php
//----------------------------------------
$cantPS = DataManager::getCount("SELECT COUNT(*) FROM cuenta WHERE ctatipo='PS'");
$cantC = DataManager::getCount("SELECT COUNT(*) FROM cuenta WHERE (ctatipo='C' OR ctatipo='CT') AND ctaactiva='1' AND ctazona<>'95' AND (ctaidempresa='1' OR ctaidempresa='3')");
$cantCI = DataManager::getCount("SELECT COUNT(*) FROM cuenta WHERE (ctatipo='C' OR ctatipo='CT') AND ctaactiva='0' AND ctazona<>'95' AND (ctaidempresa='1' OR ctaidempresa='3')");
$cantT = DataManager::getCount("SELECT COUNT(*) FROM cuenta WHERE (ctatipo='T' OR ctatipo='TT') AND ctazona<>'95' AND (ctaidempresa='1' OR ctaidempresa='3')");
$total = $cantPS + $cantC + $cantCI + $cantT;
$cantPS = round((($cantPS*100)/$total), 2);
$cantC = round((($cantC*100)/$total), 2);
$cantCI = round((($cantCI*100)/$total), 2);
$cantT = round((($cantT*100)/$total), 2);
//------------------------------------------
?>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#empselect').change(function(){
dac_redirectPaginacion();
});
$('#tiposelect').change(function(){
dac_redirectPaginacion();
});
function dac_redirectPaginacion(){
var empresa = $('#empselect').val();
var tipo = $('#tiposelect').val();
var redirect = '?empresa='+empresa+'&tipo='+tipo;
document.location.href=redirect;
}
});
function dac_mostrarFiltro(tipo, filtro){
$.ajax({
type : 'POST',
cache : false,
url : '/pedidos/cuentas/logica/ajax/getFiltroCuentas.php',
data : {
tipo : tipo,
filtro : filtro
},
beforeSend : function () {
$('#box_error').css({'display':'none'});
$('#box_cargando').css({'display':'block'});
$("#msg_cargando").html('<img class="icon-loading"/>Cargando... espere por favor!');
},
success : function (resultado) {
if (resultado){
var tabla = resultado;
document.getElementById('tablaFiltroCuentas').innerHTML = tabla;
$('#box_cargando').css({'display':'none'});
} else {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
}
},
error: function () {
$('#box_cargando').css({'display':'none'});
$('#box_error').css({'display':'block'});
$("#msg_error").html("Error al consultar los registros.");
},
});
}
</script>
<script language="javascript" type="text/javascript">
$(function () {
Highcharts.chart('container', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Cuentas'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
// color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: 'Brands',
colorByPoint: true,
data: [{
name: 'Prospecto',
y: <?php echo $cantPS; ?>,
sliced: true,
selected: true,
}, {
name: 'Cliente',
y: <?php echo $cantC; ?>
}, {
name: '<NAME>',
y: <?php echo $cantCI; ?>
}, {
name: 'Transfer',
y: <?php echo $cantT; ?>
}]
}]
});
});
</script>
<file_sep>/includes/class.dm.hiper.php
<?php
require_once('class.Database.php');
require_once('classHiper/class.cuenta.php');
require_once('classHiper/class.articulo.php');
class DataManagerHiper {
//-----------------------------------------------------------------------------
// FUNCIONES GENERICAS
//-----------------------------------------------------------------------------
public static function _getConnection() {
static $hDB;
try {
$hDB = Database::instanceHiper();
} catch (Exception $e) {
die("Imposible conexion con BBDD<BR>");
}
return $hDB;
}
public static function newObjectOfClass($_class=null, $_id=NULL, $_idTwo=NULL, $_idThree=NULL) {
$_object = null;
if (!empty($_class)) {
if (class_exists($_class)) {
if(empty($_idTwo)){
$_object = new $_class($_id);
}elseif(empty($_idThree)){
$_object = new $_class($_id, $_idTwo);
} else {
$_object = new $_class($_id, $_idTwo, $_idThree);
}
}
}
return $_object;
}
public static function loadFromDatabase($_object=null, $_id=NULL, $_idTwo=NULL, $_idThree=NULL) {
if (!empty($_object)) {
if(empty($_idTwo) || is_null($_idTwo)){
$_sql = sprintf("SELECT TOP 1 * FROM %s WHERE %s='%d'", $_object->__getTableName(), $_object->__getFieldID(), $_id);
}elseif(empty($_idThree) || is_null($_idThree)){
$_sql = sprintf("SELECT TOP 1 * FROM %s WHERE %s='%d' AND %s='%d'", $_object->__getTableName(), $_object->__getFieldID(), $_id, $_object->__getFieldIDTwo(), $_idTwo);
} else {
$_sql = sprintf("SELECT TOP 1 * FROM %s WHERE %s='%d' AND %s='%d' AND %s='%d'", $_object->__getTableName(), $_object->__getFieldID(), $_id, $_object->__getFieldIDTwo(), $_idTwo, $_object->__getFieldIDThree(), $_idTThree);
}
$hDB = DataManagerHiper::_getConnection();
try {
$data = $hDB->getAll($_sql);
} catch (Exception $e) {
die("error ejecutando $_sql<br>");
}
return $data;
}
return null;
}
// SIMPLE OBJECT
// CLASES DERIVADAS DE PropertyObject y que tengan propiedad == ID
//
public static function updateSimpleObject($_object, $_ID=NULL) { //, $_fieldTwo=NULL, $_fieldThree=NULL
$hDB = DataManagerHiper::_getConnection();
$_rows = 0;
$_fields = $_object->__getUpdated();
if (count($_fields) > 0) {
$hDB->startTransaction();
try {
//$_ID = $_object->__get('ID');
$_fieldID = $_object->__getFieldName('ID');
/*if(empty($_fieldTwo) || is_null($_fieldTwo)){
$sWhere = "$_fieldID";
}elseif(empty($_fieldThree) || is_null($_fieldThree)){
$sWhere = "$_fieldID AND $_fieldTwo";
} else {
$sWhere = "$_fieldID AND $_fieldTwo AND $_fieldThree";
} */
//$_rows = $hDB->update($_object->__getTableName(), $_fields, "$_fieldID=$_ID");
$_rows = $hDB->update($_object->__getTableName(), $_fields, "$_fieldID=$_ID"); //$sWhere
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transacción abortada. ERR=" . $e->getMessage();
}
}
return $_rows;
}
public static function deleteSimpleObject($_object, $_ID=NULL) { //, $_fieldTwo=NULL, $_fieldThree=NULL
$hDB = DataManagerHiper::_getConnection();
$hDB->startTransaction();
$_rows = 0;
try {
//$_ID = $_object->__get('ID');
$_fieldID = $_object->__getFieldName('ID');
/*
if(empty($_fieldTwo)){
$sWhere = "$_fieldID";
}elseif(empty($_fieldThree)){
$sWhere = "$_fieldID AND $_fieldTwo";
} else {
$sWhere = "$_fieldID AND $_fieldTwo AND $_fieldThree";
}*/
$_theSQL = sprintf("DELETE FROM %s WHERE %s=%s", $_object->__getTableName(), $_fieldID, $_ID);
//$_theSQL = sprintf("DELETE FROM %s WHERE %s", $_object->__getTableName(), $sWhere);
$_rows = $hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_rows;
}
public static function insertSimpleObject($_object) {
$hDB = DataManagerHiper::_getConnection();
$hDB->startTransaction();
$_ID = 0;
try {
$_ID = $hDB->insert($_object->__getTableName(), $_object->__getData());
$hDB->commit();
//$_object->__set('ID', $_ID); // Para que el objeto quede consistente con la BD
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_ID;
}
//------------------------------
// FUNCIONES SIN USO DE CLASES
//------------------------------
/*public static function deletefromtabla($_tabla, $_fieldID, $_ID) {
$hDB = DataManagerHiper::_getConnection();
$hDB->startTransaction();
$_rows = 0;
try {
$_theSQL = sprintf("DELETE FROM %s WHERE %s=%s", $_tabla, $_fieldID, $_ID);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_rows;
}*/
/*public static function insertfromtabla($_tabla, $_fieldID, $_ID, $_values) {
$hDB = DataManagerHiper::_getConnection();
$hDB->startTransaction();
try {
$_theSQL = sprintf("INSERT INTO %s (%s) VALUES (%s, %s)", $_tabla, $_fieldID, $_ID, $_values);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_ID;
}*/
//---------------------------------------------------------
//Para INSERTAR DATOS en tablas que no tienen Campo UNIQUE
//---------------------------------------------------------
/*
public static function insertToTable($_tabla, $_fieldID, $_values, $_ID=0) {
$hDB = DataManagerHiper::_getConnection();
$hDB->startTransaction();
try {
$_theSQL = sprintf("INSERT INTO %s (%s) VALUES (%s)", $_tabla, $_fieldID, $_values);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_ID;
}
*/
public static function updateToTable($_tabla, $_fieldID, $_condition="TRUE") {
$hDB = DataManagerHiper::_getConnection();
$hDB->startTransaction();
$_rows = 0;
if($_fieldID){
try {
$_theSQL = sprintf("UPDATE %s SET %s WHERE %s", $_tabla, $_fieldID, $_condition);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
}
return $_rows;
}
/*
public static function deleteToTable($_tabla, $_campos = NULL) {
if (empty($_campos) || is_null($_campos)){ $_condicionWhere = "TRUE";
} else {$_condicionWhere = $_campos;}
$hDB = DataManagerHiper::_getConnection();
try {
$_theSQL = sprintf("DELETE FROM %s WHERE (%s)", $_tabla, $_condicionWhere);
$hDB->select($_theSQL);
$hDB->commit();
} catch (Exception $e) {
$hDB->abort();
print "Transaccion abortada. ERR=" . $e->getMessage();
}
return $_ID;
}*/
//----------------------------------------------------------------------------
// RESTO DE FUNCIONES
//----------------------------------------------------------------------------
//------------------
// Tabla Conddompra
//------------------
public static function getCondCompra( $empresa = NULL, $laboratorio = NULL, $idArt = NULL) {
$hDB = DataManagerHiper::_getConnection('Hiper');
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmp = "idEmpresa LIKE '%'";
} else {$_condicionEmp = "idEmpresa=".$empresa;}
if ((empty($laboratorio) && $laboratorio != 0) || is_null($laboratorio)){ $_condicionLab = "idLab LIKE '%'";
} else {$_condicionLab = "idLab=".$laboratorio;}
if ((empty($idArt) && $idArt != 0) || is_null($idArt)){ $_condicionArt = "idArt LIKE '%'";
} else {$_condicionArt = "idArt=".$idArt;}
$sql = "SELECT * FROM CondCompra WHERE ($_condicionEmp) AND ($_condicionLab) AND ($_condicionArt) ORDER BY idArt ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//------------------
// Tabla EquivUnid
//------------------
public static function getEquivUnid( $empresa = NULL, $laboratorio = NULL, $idArt = NULL) {
$hDB = DataManagerHiper::_getConnection('Hiper');
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmp = "idEmpresa LIKE '%'";
} else {$_condicionEmp = "idEmpresa=".$empresa;}
if ((empty($laboratorio) && $laboratorio != 0) || is_null($laboratorio)){ $_condicionLab = "idLab LIKE '%'";
} else {$_condicionLab = "idLab=".$laboratorio;}
if ((empty($idArt) && $idArt != 0) || is_null($idArt)){ $_condicionArt = "idArt LIKE '%'";
} else {$_condicionArt = "idArt=".$idArt;}
$sql = "SELECT * FROM EquivUnid WHERE ($_condicionEmp) AND ($_condicionLab) AND ($_condicionArt) ORDER BY idArt ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
//------------------
// Tabla Empresas
//------------------
public static function getEmpresas( $empresa = NULL ) {
$hDB = DataManagerHiper::_getConnection('Hiper');
if ((empty($empresa) && $empresa != 0) || is_null($empresa)){ $_condicionEmp = "IdEmpresa LIKE '%'";
} else {$_condicionEmp = "IdEmpresa=".$empresa;}
$sql = "SELECT * FROM Empresas WHERE ($_condicionEmp) ORDER BY IdEmpresa ASC";
try {
$data = $hDB->getAll($sql);
} catch (Exception $e) {
die("error ejecutando $sql<br>");
}
return $data;
}
} ?><file_sep>/pedidos/logica/ajax/update.pedidoCadena.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$usrAsignado = (isset($_POST['pwusrasignado']))? $_POST['pwusrasignado'] : NULL;
$empresa = (isset($_POST['empselect'])) ? $_POST['empselect'] : NULL;
$laboratorio = (isset($_POST['labselect'])) ? $_POST['labselect'] : NULL;
$condPago = (isset($_POST['condselect'])) ? $_POST['condselect'] : NULL;
$idCondComercial=(isset($_POST['pwidcondcomercial']))? $_POST['pwidcondcomercial'] : NULL;
//Arrays
$idCuentas = (isset($_POST['pwidcta'])) ? $_POST['pwidcta'] : NULL;
$nroOrdenes = (isset($_POST['pworden'])) ? $_POST['pworden'] : NULL;
//Control de archivo por orden de compra
$filesPesos = $_FILES["file"]["size"];
$filesTypes = $_FILES["file"]["type"];
$filesNombres = $_FILES["file"]["name"];
$filesTempName = $_FILES["file"]["tmp_name"];
$observaciones=(isset($_POST['pwobservacion'])) ? $_POST['pwobservacion'] : NULL;
$articulosIdArtS=(isset($_POST['pwidart'])) ? unserialize(stripslashes($_POST['pwidart'])) : NULL;
$articulosCantS = (isset($_POST['pwcant'])) ? unserialize(stripslashes($_POST['pwcant'])) : NULL;
$articulosB1S = (isset($_POST['pwbonif1'])) ? unserialize(stripslashes($_POST['pwbonif1'])) : NULL;
$articulosB2S = (isset($_POST['pwbonif2'])) ? unserialize(stripslashes($_POST['pwbonif2'])) : NULL;
$articulosD1S = (isset($_POST['pwdesc1'])) ? unserialize(stripslashes($_POST['pwdesc1'])) : NULL;
$articulosD2S = (isset($_POST['pwdesc2'])) ? unserialize(stripslashes($_POST['pwdesc2'])) : NULL;
$tipoPedido = (isset($_POST['pwtipo'])) ? $_POST['pwtipo'] : NULL;
//Controlo cuentas repetidas
if(count($idCuentas) != count(array_unique($idCuentas))){
echo "Existen cuentas duplicadas."; exit;
}
if(count($idCuentas) <= 1) {
echo "El pedido debe contener al menos 2 cuentas de tipo cadena."; exit;
}
$cantidades = [];
$bonificados = [];
foreach ($idCuentas as $k => $idCuenta) {
//Arrays por número de cuenta
$articulosIdArt = (isset($_POST['pwidart'.$idCuenta])) ? $_POST['pwidart'.$idCuenta] : NULL;
$articulosCant = (isset($_POST['pwcant'.$idCuenta])) ? $_POST['pwcant'.$idCuenta] : NULL;
$articulosB1 = (isset($_POST['pwbonif1'.$idCuenta])) ? $_POST['pwbonif1'.$idCuenta] : NULL;
if(empty($articulosCant)) {
echo "Indique una cantidad en el artículo ".$articulosIdArt[$k]." de la cuenta ".$idCuenta; exit;
}
//Controlo artículos duplicados
if(count($articulosIdArt) != count(array_unique($articulosIdArt))){
echo "Existen artículos duplicados en la cuenta ".$idCuenta; exit;
}
//Recorro los artículos
foreach ($articulosIdArt as $j => $artIdArt) {
//sumos Cantidades por Artículo
if(empty($articulosCant[$j])){
echo "Indique una cantidad en el artículo ".$artIdArt." de la cuenta ".$idCuenta; exit;
}
$cantidades[$artIdArt] = isset($cantidades[$artIdArt]) ? ($cantidades[$artIdArt] + $articulosCant[$j]) : $articulosCant[$j];
//Sumo Bonificados por Artículo
$articuloBonif = ($articulosB1[$j]) ? $articulosB1[$j] : 0;
$bonificados[$artIdArt] = isset($bonificados[$artIdArt]) ? ($bonificados[$artIdArt] + $articuloBonif ) : $articuloBonif;
}
}
foreach ($articulosIdArtS as $k => $artIdArt) {
if($articulosCantS[$k] != $cantidades[$artIdArt]){
echo "Las $articulosCantS[$k] unidades pedidas del artículo ".$artIdArt." no coindiden con las $cantidades[$artIdArt] cargadas."; exit;
}
//Si hay bonificación, calculos las unidades totales a bonificar.
if(!empty($articulosB2S[$k]) && !empty($articulosB1S[$k])){
$totalBonificables = ($articulosCantS[$k] / $articulosB2S[$k]) * ($articulosB1S[$k] - $articulosB2S[$k]);
if($totalBonificables != $bonificados[$artIdArt]) {
echo "Las $totalBonificables unidades bonificadas del artículo ".$artIdArt." no coindiden con las $bonificados[$artIdArt] cargadas."; exit;
}
}
}
foreach ($idCuentas as $k => $idCuenta) {
unset($articulosIdArt);
unset($articulosCant);
unset($articulosB1);
unset($articulosB2);
//Control de adjuntos Cadenas
$nroOrden = $nroOrdenes[$k];
$filePeso = $filesPesos[$k];
$fileType = $filesTypes[$k];
$fileNombre = $filesNombres[$k];
$fileTempName = $filesTempName[$k];
if ($filePeso != 0){
if($filePeso > MAX_FILE){
echo "El archivo de la cuenta ".$idCuenta." no debe superar los 4MB"; exit;
}
if(!dac_fileFormatControl($fileType, 'imagen')){
echo "El archivo de la cuenta ".$idCuenta." debe tener formato imagen."; exit;
}
}
$observacion = $observaciones[$k];
$articulosIdArt = (isset($_POST['pwidart'.$idCuenta])) ? $_POST['pwidart'.$idCuenta] : NULL;
$articulosCant = (isset($_POST['pwcant'.$idCuenta])) ? $_POST['pwcant'.$idCuenta] : NULL;
$articulosPrecio= (isset($_POST['pwprecioart'.$idCuenta]))? $_POST['pwprecioart'.$idCuenta] : NULL;
$pwbonif1 = (isset($_POST['pwbonif1'.$idCuenta])) ? $_POST['pwbonif1'.$idCuenta] : NULL;
foreach($articulosCant as $j => $artCant){
if(!empty($pwbonif1[$j])){
$articulosB1[] = $articulosCant[$j] + $pwbonif1[$j];
$articulosB2[] = $articulosCant[$j];
} else {
$articulosB1[] = '';
$articulosB2[] = '';
}
}
$articulosD1 = (isset($_POST['pwdesc1'.$idCuenta])) ? $_POST['pwdesc1'.$idCuenta] : NULL;
$articulosD2 = (isset($_POST['pwdesc2'.$idCuenta])) ? $_POST['pwdesc2'.$idCuenta] : NULL;
$idPropuesta = 0;
$estado = 0;
$observacion = "Pedido CADENA. ".$observacion;
//********************//
// Generar Pedido
require($_SERVER['DOCUMENT_ROOT']."/pedidos/pedidos/logica/ajax/generarPedido.php" );
}
echo "1"; exit;
?><file_sep>/transfer/logica/enviar.pedido.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
} ?>
<!DOCTYPE html>
<html lang='es'>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php"; ?>
</head>
<body>
<header class="cabecera">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/header.inc.php"); ?>
</header><!-- cabecera -->
<nav class="menuprincipal"> <?php
$_section = "pedidos";
$_subsection= "mis_transfers";
include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/menu.inc.php"); ?>
</nav> <!-- fin menu -->
<main class="cuerpo"><?php
//Recorro por destino de correo//
$drogueriaDestinos = DataManager::getDrogueriaTransferTipo(1);
if ($drogueriaDestinos) {
foreach ($drogueriaDestinos as $k => $drogDestino) {
$destCorreo = $drogDestino["drogtcorreotransfer"];
$destTipo = $drogDestino["drogttipotransfer"];
$destCuenta = $drogDestino["drogtcliid"];
$destIdEmpresa = $drogDestino["drogtidemp"];
$destNombre = DataManager::getCuenta('ctanombre', 'ctaidcuenta', $destCuenta, $destIdEmpresa);
$idLoc = DataManager::getCuenta('ctaidloc', 'ctaidcuenta', $destCuenta, $destIdEmpresa);
$destLocalidad = DataManager::getLocalidad('locnombre', $idLoc);
$transfer = 0;
$posicion = 0;
switch($destTipo){ //Aca puede que valga solo con tipo A B C y D
case 'A': /*delsud*/
$titulosColumnas = array('IDTransfer', 'NroClienteDrog', 'RazónSocial', 'Cuit', 'Domicilio', 'Contacto', 'EAN', 'Descripción', 'Unidades', 'Descuento', 'Plazo', 'Fecha'); $posicion = 7; break;
case 'B': /*monroe*/
$titulosColumnas = array('IDTransfer', 'NroClienteDrog', 'RazónSocial', 'Cuit', 'Domicilio', 'Contacto', 'EAN', 'Descripción', 'Unidades', 'Descuento', 'Fecha'); $posicion = 7; break;
case 'C': /*suizo*/
$titulosColumnas = array('IDTransfer', 'NroClienteDrog', 'RazónSocial', 'EAN', 'Descripción', 'Unidades', 'Bonificadas', 'Descuento', 'Cuit', 'Fecha'); $posicion = 4; break;
case 'D': /*OTROS - Kellerof - cofarmen - delLitoral - SUR - PICO*/
$titulosColumnas = array('IDTransfer', 'NroClienteDrog', 'RazónSocial', 'Cuit', 'EAN', 'Descripción', 'Unidades', 'Descuento', 'CondPago', 'Fecha'); $posicion = 5; break;
default: $transfer = 1; break;
}
if ($transfer == 0){
//Selecciono Droguerías por $destCorreo
$droguerias = DataManager::getDrogueria( NULL, NULL, NULL, $destCorreo );
if ($droguerias) {
$pedido = 0;
foreach ($droguerias as $x => $drog) {
$drogCorreo = $drog["drogtcorreotransfer"];
$drogCuenta = $drog["drogtcliid"];
//Busco pedidos de cada droguería con el mismo mail
$transfersRecientes = DataManager::getTransfersPedido(1, NULL, NULL, $drogCuenta, NULL, NULL);
if (count($transfersRecientes)){
if ($pedido == 0) { //carga en el primer pedido que ecuentra
$pedido = 1; ?>
<table id="tblExport<?php echo $destCuenta;?>" border="1">
<tr>
<td colspan="2" align="center">PEDIDO TRANSFER (<?php echo date('d-m-y'); ?>)</td>
<td colspan="<?php echo (count($titulosColumnas)-6);?>" align="center"><?php echo $destNombre; if($destTipo == 'A'){ echo " - ".$destLocalidad;} ?></td>
<td colspan="4" align="right"><?php echo $destCorreo;?></td>
</tr>
<tr> <?php
for ($x=0; $x<count($titulosColumnas); $x++){
echo "<td>".$titulosColumnas[$x]."</td>";
}?>
</tr> <?php
}
foreach($transfersRecientes as $y => $transRec){
$idPedido = $transRec["ptid"];
$nroPedido = $transRec["ptidpedido"];
$nroCliDrog = $transRec["ptnroclidrog"];
$ptIdCuenta = $transRec["ptidclineo"];
$ptCuentaRS = $transRec["ptclirs"];
$ptCuentaCuit = $transRec["ptclicuit"];
$ptDomicilio = $transRec["ptdomicilio"];
$ptContacto = $transRec["ptcontacto"];
$ptIdArt = $transRec["ptidart"];
$idCondPago = $transRec["ptcondpago"];
$condPlazo = DataManager::getCondicionDePagoTransfer('conddias', 'condid', $idCondPago);
$condPlazo = ($condPlazo == 0) ? 'HABITUAL' : $condPlazo;
$articulo = DataManager::getFieldArticulo("artidart", $ptIdArt);
$ean = $articulo['0']["artcodbarra"];
$descripcion = $articulo['0']['artnombre'];
$ptUnidades = $transRec["ptunidades"];
$ptDescuento = $transRec["ptdescuento"];
$ptFechaPedido = substr($transRec["ptfechapedido"], 0, 10);
$ptUnidades = $transRec["ptunidades"];
switch($destTipo){
case 'A': /*delsud*/
$datosColumnas = array($nroPedido, $nroCliDrog, $ptCuentaRS, $ptCuentaCuit, $ptDomicilio, $ptContacto, $ean, $descripcion, $ptUnidades, $ptDescuento, $condPlazo, $ptFechaPedido); break;
case 'B': /*monroe*/
$datosColumnas = array($nroPedido, $nroCliDrog, $ptCuentaRS, $ptCuentaCuit, $ptDomicilio, $ptContacto, $ean, $descripcion, $ptUnidades, $ptDescuento, $ptFechaPedido); break;
case 'C': /*suizo*/
$datosColumnas = array($nroPedido, $nroCliDrog, $ptCuentaRS, $ean, $descripcion, $ptUnidades, '0', $ptDescuento, $ptCuentaCuit, $ptFechaPedido); break;
case 'D': /*OTRAS*/
$datosColumnas = array($nroPedido, $nroCliDrog, $ptCuentaRS, $ptCuentaCuit, $ean, $descripcion, $ptUnidades, $ptDescuento, $condPlazo, $ptFechaPedido); break;
default: break;
} ?>
<tr> <?php
for ($x=0;$x<count($datosColumnas); $x++){
if($x == ($posicion-1)){
echo '<td align=left style="mso-style-parent:style0; mso-number-format:\@">'.$datosColumnas[$x].'</td>';
} else{ echo '<td align=left>'.$datosColumnas[$x].'</td>'; }
} ?>
</tr> <?php
// Al Registrar el pedido, lo desactivo (por enviado)
if ($idPedido) {
$ptObject = DataManager::newObjectOfClass('TPedidostransfer', $idPedido);
$_status = ($ptObject->__get('Activo')) ? 0 : 1;
$ptObject->__set('IDAdmin' , $_SESSION["_usrid"]);
$ptObject->__set('IDNombreAdmin' , $_SESSION["_usrname"]);
$ptObject->__set('FechaExportado' , date('Y-m-d H:i:s'));
$ptObject->__set('Activo' , '0');
$ID = DataManager::updateSimpleObject($ptObject);
}
} //fin foreach
} //fin if
} //fin foreach
if ($pedido == 1){ ?>
</table>
</br></br>
<?php
echo "<script>";
echo "exportTableToExcel('tblExport".$destCuenta."', 'Transfers-".date("d-m-Y")."-".$destNombre."')";
echo "</script>";
}
} //fin if
} else { echo "Una de las droguerias no tiene bien definido su tipo."; }//fin if transfer
} //fin for
} else {
echo "No se encuentran DROGUERIAS ACTIVAS.";
} ?>
</main> <!-- fin cuerpo -->
<footer class="pie">
<?php include($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/footer.inc.php"); ?>
</footer> <!-- fin pie -->
</body>
</html><file_sep>/cuentas/logica/changestatus.php
<?php
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.hiper.php");
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo 'SU SESION HA EXPIRADO.'; exit;
}
$pag = empty($_REQUEST['pag']) ? 0 : $_REQUEST['pag'];
$ctaId = empty($_REQUEST['id']) ? 0 : $_REQUEST['id'];
if ($ctaId) {
$ctaObject = DataManager::newObjectOfClass('TCuenta', $ctaId);
//**************************//
// Consulto Datos Cuenta // --> envía mail de notificación
$cuenta = $ctaObject->__get('Cuenta');
$tipo = $ctaObject->__get('Tipo');
$empresa = $ctaObject->__get('Empresa');
$zona = $ctaObject->__get('Zona');
$ruteo = $ctaObject->__get('Ruteo');
$nombre = $ctaObject->__get('Nombre');
$cuit = $ctaObject->__get('CUIT');
$provincia = $ctaObject->__get('Provincia');
$localidad = $ctaObject->__get('Localidad');
$direccion = $ctaObject->__get('Direccion')." ".$ctaObject->__get('Numero')." ".$ctaObject->__get('Piso')." ".$ctaObject->__get('Dpto');
$idLocalidad= $ctaObject->__get('Localidad');
$correo = $ctaObject->__get('Email');
$telefono = $ctaObject->__get('Telefono');
$observacion= $ctaObject->__get('Observacion');
$empresaNombre = DataManager::getEmpresa('empnombre', $empresa);
$provinciaNombre = DataManager::getProvincia('provnombre', $provincia);
$localidadNombre = DataManager::getLocalidad('locnombre', $localidad);
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
if($_SESSION["_usrrol"] != "V"){
//**********************************//
// UPDATE de datos de la cuenta //
$_status = ($ctaObject->__get('Activa')) ? 0 : 1;
$ctaObject->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObject->__set('LastUpdate' , date("Y-m-d H:m:s"));
$ctaObject->__set('Activa' , $_status);
DataManager::updateSimpleObject($ctaObject);
//si es Cliente, que lo cambie en hiperwin
if($tipo == "C" || $tipo == "CT") {
$ctaObjectHiper = DataManagerHiper::newObjectOfClass('THiperCuenta', $ctaId);
$ctaObjectHiper->__set('UsrUpdate' , $_SESSION["_usrid"]);
$ctaObjectHiper->__set('LastUpdate' , date("Y-m-d H:m:s"));
$ctaObjectHiper->__set('Activa' , $_status);
DataManagerHiper::updateSimpleObject($ctaObjectHiper, $ctaId);
}
//**************************//
// Consulto Datos Cuenta // --> envía mail de notificación
$estado = ($ctaObject->__get('Activa')) ? "ACTIVADA" : "DESACTIVADA";
//********//
// CORREO //
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = "<EMAIL>"; // Dirección de correo del remitente
$mail->FromName = "Comunicado Web"; // Nombre del remitente
$mail->Subject = "Constancia de Reactivacion de Cuenta"; //"Asunto del correo";
$cuerpoMail = '
<html>
<head>
<title>Solicitud de REACTIVACION de CUENTA '.$tipo.'</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 580px;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>
<body>
<div align="center">
<table width="580" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
La <strong>SOLICITUD de REACTIVACIÓN de CUENTA '.$tipo.'</strong> ha sido <strong>'.$estado.'</strong><br/><br/>
<div />
</td >
</tr>
<tr>
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight:bold; background-color:#117db6">
<strong>Datos de solicitud</strong>
</div>
</td>
</tr>
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Usuario </th>
<td align="left" width="400"> '.$_SESSION["_usrname"].' </td>
</tr>
<tr>
<th align="left" width="200">Zona - Ruteo</th>
<td align="left" width="400">'.$zona." - ".$ruteo.'</td>
</tr>
<tr>
<th align="left" width="200">Fecha </th>
<td align="left" width="400">'.date("d-m-Y H:i:s").'</td>
</tr>
<tr>
<th align="left" width="200">Cuenta</th>
<td align="left" width="400">'.$cuenta.'</td>
</tr>
<tr>
<th align="left" width="200">Razón Social</th>
<td align="left" width="400">'.$nombre.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$correo.'</td>
</tr>
<tr>
<th align="left" width="200">Teléfono</th>
<td align="left" width="400">'.$telefono.'</td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con la empresa al 4555-3366 de Lunes a Viernes de 10 a 17 horas.
</font>
<div style="color:#000000; font-size:12px;">
<strong>Si no recibe información del reactivación en 24 horas hábiles, podrá reclamar reenviando éste mail a <EMAIL> </strong></a></br></br>
</div>
</div>
</td>
</tr>
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Gracias por confiar en '.$empresaNombre.'<br/>
Le saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
</html>
';
$mail->msgHTML($cuerpoMail);
//**********************//
// REGISTRO DE ESTADOS // de Cuenta
//**********************//
$estadoNombre = ($ctaObject->__get('Activa')) ? "Desactiva" : "Reactiva";
$origen = 'TCuenta';
$origenId = $ctaId;
$mail->AddBCC("infoweb<EMAIL>"); //AddBCC Copia Oculta
$mail->AddAddress($_SESSION["_usremail"], $estadoNombre.' de la cuenta '.$tipo.". Enviada");
//**********************//
// Registro MOVIMIENTO //
//**********************//
$movimiento = 'CUENTA_'.$ctaId;
$movTipo = 'UPDATE';
dac_registrarMovimiento($movimiento, $movTipo, "TCuenta", $ctaId);
} else {
//SOLICITUD DE REACTIVACIÓN
//**************************//
// Consulto Datos Cuenta // --> envía mail de notificación
//**************************//
if(!$ctaObject->__get('Activa')){
$fechaActual = new DateTime();
$fechaAtras = clone $fechaActual;
$fechaAtras->modify("-1 year");
$fechaCompra = new DateTime($ctaObject->__get('FechaCompra'));
if($tipo == "PS"){
echo "Un prospecto solo se activa en un cambio de tipo de cuenta."; exit;
}
//Si la última compra es de más de un año, no se podrá solicita ni Activar la cuenta. Solo desactivar
if($fechaCompra < $fechaAtras && $fechaCompra->format('Y-m-d') <> '2001-01-01') {
echo "La cuenta lleva más de un año sin registrar compras. Solicite reactivar enviando la documentación que corresponda."; exit; //$fechaAtras->format("Y-m-d H:i:s")
}
$estado = ($ctaObject->__get('Activa')) ? "ACTIVADA" : "DESACTIVADA";
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = $_SESSION["_usrmail"]; // Dirección de correo del remitente
$mail->FromName = $_SESSION["_usrname"]; // Nombre del remitente
$mail->Subject = "Solicitud de Reactivacion de Cuenta"; //"Asunto del correo";
$cuerpoMail = '
<html>
<head>
<title>Solicitud de REACTIVACION de CUENTA '.$tipo.'</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 580px;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>
<body>
<div align="center">
<table width="580" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
La <strong>SOLICITUD de REACTIVACIÓN de CUENTA '.$tipo.'</strong> ha sido <strong>ENVIADA</strong><br/><br/>
<div />
</td >
</tr>
<tr>
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight:bold; background-color:#117db6">
<strong>Datos de solicitud</strong>
</div>
</td>
</tr>
<tr>
<td valign="top">
<div class="texto">
<table width="580px" style="border:1px solid #117db6">
<tr>
<th align="left" width="200"> Usuario </th>
<td align="left" width="400"> '.$_SESSION["_usrname"].' </td>
</tr>
<tr>
<th align="left" width="200">Zona - Ruteo</th>
<td align="left" width="400">'.$zona." - ".$ruteo.'</td>
</tr>
<tr>
<th align="left" width="200">Fecha </th>
<td align="left" width="400">'.date("d-m-Y H:i:s").'</td>
</tr>
<tr>
<th align="left" width="200">Cuenta</th>
<td align="left" width="400">'.$cuenta.'</td>
</tr>
<tr>
<th align="left" width="200">Razón Social</th>
<td align="left" width="400">'.$nombre.'</td>
</tr>
<tr>
<th align="left" width="200">E-mail</th>
<td align="left" width="400">'.$correo.'</td>
</tr>
<tr>
<th align="left" width="200">Teléfono</th>
<td align="left" width="400">'.$telefono.'</td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con la empresa al 4555-3366 de Lunes a Viernes de 10 a 17 horas.
</font>
<div style="color:#000000; font-size:12px;">
<strong>Si no recibe información de reactivación en 24 horas hábiles, podrá reclamar reenviando éste mail a <EMAIL> </strong></a></br></br>
</div>
</div>
</td>
</tr>
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Gracias por confiar en '.$empresaNombre.'<br/>
Le saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
</html>
';
$mail->AddBCC("<EMAIL>"); //AddBCC Copia Oculta
$mail->AddAddress($_SESSION["_usremail"], $estadoNombre.' de la cuenta '.$tipo.". Enviada");
$mail->msgHTML($cuerpoMail);
//**********************//
// REGISTRO DE ESTADOS // de Cuenta
//**********************//
$estadoNombre = ($ctaObject->__get('Activa')) ? "Desactiva" : "Reactiva";
$origen = 'TCuenta';
$origenId = $ctaId;
} else {
echo "La cuenta se encuentra activa"; exit;
}
}
if(!$mail->Send()) {
echo "Hubo un Error en el envío de mails para notificar cambios."; exit;
}
//******************//
// Registro ESTADO //
//******************//
$estadoObject = DataManager::newObjectOfClass('TEstado');
$estadoObject->__set('Origen' , $origen);
$estadoObject->__set('IDOrigen' , $origenId);
$estadoObject->__set('Fecha' , date("Y-m-d h:i:s"));
$estadoObject->__set('UsrCreate', $_SESSION["_usrid"]);
$estadoObject->__set('Estado' , 0);
$estadoObject->__set('Nombre' , $estadoNombre);
$estadoObject->__set('ID' , $estadoObject->__newID());
$IDEstado = DataManager::insertSimpleObject($estadoObject);
if(!$IDEstado){
echo "Error al intentar registrar el estado de la solicitud. Consulte con el administrador de la web."; exit;
}
} else {
echo "No se pudo cambiar el estado de la cuenta."; exit;
}
echo "1";
?><file_sep>/transfer/logica/ajax/cargar.abm.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M" && $_SESSION["_usrrol"]!="G"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/transfer/': $_REQUEST['backURL'];
$_drogid = (isset($_POST['drogid'])) ? $_POST['drogid'] : NULL;
$idCuenta = DataManager::getCuenta('ctaidcuenta', 'ctaid', $_drogid);
$_artid = (isset($_POST['artid'])) ? $_POST['artid'] : NULL;
//----------------
//Controlo campos
if (empty($_drogid) || empty($_artid)){ echo "1"; exit; }
//---------------------------------------
//Consulto el ABM actual de la droguería
$_abms = DataManager::getDetalleAbm(date("m"), date("Y"), $idCuenta, 'TL');
if (count($_abms)>0) {
foreach ($_abms as $k => $_abm){
$_abmDrog = $_abm['abmdrogid'];
$_abmArtid = $_abm['abmartid'];
$_abmDesc = $_abm['abmdesc'];
if ($_abmArtid == $_artid && $_abmDrog == $idCuenta) {
echo $_abmDesc; exit;
}
}
}
echo "1"; exit;
?><file_sep>/transfer/gestion/liquidacion/logica/changestatus.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="G" && $_SESSION["_usrrol"]!= "M"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
echo $_SESSION["_usrol"];
header("Location: $_nextURL");
exit;
}
$_nropedido = empty($_REQUEST['nropedido']) ? 0 : $_REQUEST['nropedido'];
$_status = empty($_REQUEST['status']) ? 0 : $_REQUEST['status'];
$backURL = empty($_REQUEST['backURL']) ? '/pedidos/transfer/gestion/liquidacion/' : $_REQUEST['backURL'];
$_detalles = DataManager::getTransfersPedido(NULL, NULL, NULL, NULL, NULL, NULL, $_nropedido); //DataManager::getDetallePedidoTransfer($_nropedido);
if ($_detalles) {
for( $k=0; $k < count($_detalles); $k++ ){
$_detalle = $_detalles[$k];
$_ptid = $_detalle['ptid'];
$_ptliquidado = $_detalle['ptliquidado'];
if ($_ptliquidado == $_status){
$_cliobject = DataManager::newObjectOfClass('TPedidostransfer', $_ptid);
$_cliobject->__set('Liquidado', 'LT');
$ID = DataManager::updateSimpleObject($_cliobject);
}
}
}
header('Location: '.$backURL);
?><file_sep>/includes/class/class.liquidacion.php
<?php
require_once('class.PropertyObject.php');
class TLiquidacion extends PropertyObject { //Para Liquidación Transfer
protected $_tablename = 'liquidacion';
protected $_fieldid = 'liqid';
protected $_fieldactivo = 'liqactiva';
protected $_timestamp = 0;
protected $_id = 0;
public function __construct($_id=NULL) {
$this->_timestamp = time();
$this->_id = $_id;
if ($_id) {
$arData = DataManager::loadFromDatabase($this, $_id);
parent::__construct($arData);
}
$this->propertyTable['ID'] = 'liqid';
$this->propertyTable['Drogueria'] = 'liqdrogid';
$this->propertyTable['Tipo'] = 'liqtipo';
$this->propertyTable['Fecha'] = 'liqfecha';
$this->propertyTable['Transfer'] = 'liqnrotransfer';
$this->propertyTable['FechaFact'] = 'liqfechafact';
$this->propertyTable['NroFact'] = 'liqnrofact';
$this->propertyTable['EAN'] = 'liqean';
$this->propertyTable['Cantidad'] = 'liqcant';
$this->propertyTable['Unitario'] = 'liqunitario';
$this->propertyTable['Descuento'] = 'liqdescuento';
$this->propertyTable['ImporteNC'] = 'liqimportenc';
$this->propertyTable['Cliente'] = 'liqcliente';
$this->propertyTable['RasonSocial'] = 'liqrs';
$this->propertyTable['Cuit'] = 'liqcuit';
$this->propertyTable['UsrUpdate'] = 'liqusrupdate';
$this->propertyTable['LastUpdate'] = 'liqupdate';
$this->propertyTable['Activa'] = 'liqactiva';
}
function __toString() {
$_classname = get_class($this);
echo "<h2>=== $_classname ===</h2><br/>";
echo "ID=" . $this->_id . "<br/>";
echo "tabla=" . $this->_tablename . "<br/>";
echo "timestamp=" . date('Y-m-d H:i:s',$this->_timestamp) . "<br/>";
foreach ($this->propertyTable as $k => $v) {
echo $k . '=>' . $this->__get($k) . '<br>';
}
}
public function __getTableName() {
return $this->_tablename;
}
public function __getFieldID() {
return $this->_fieldid;
}
public function __getFieldActivo() {
return $this->_fieldactivo;
}
public function __newID() {
return ('#'.$this->_fieldid);
}
public function __validate() {
return true;
}
}
?><file_sep>/legal/terminos/index.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/detect.Browser.php");
?>
<!DOCTYPE html>
<html lang='es'>
<head>
<?php require $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/metas.inc.php"; ?>
</head>
<body>
<main class="cuerpo">
<div id="box_down">
<div id="logoneo" align="center">
<?php
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
echo $cabeceraPedido;
?>
</div><!-- logo Neofarma -->
<?php include "terminos.php"; ?>
</div> <!-- cuerpo -->
</main> <!-- fin cuerpo -->
</body>
</html><file_sep>/rendicion/logica/ajax/delete.recibo.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
$_rendid = empty($_REQUEST['rendid']) ? 0 : $_REQUEST['rendid'];
$_recid = empty($_REQUEST['recid']) ? 0 : $_REQUEST['recid'];
if($_rendid == 0 || $_recid == 0){
echo "Debe seleccionar un recibo para eliminar"; exit;
}
$_cantRecibos = 0;
$_cantCheques = 0;
$_cantFacturas = 0;
//Elimina registros según tenga o no tenga cheques y/o factura
$_cantRecibos = DataManager::getContarRecibos($_rendid); // Cuenta los recibos por rendicion
$_cantFacturas = DataManager::getContarFacturas($_recid);
$_cantCheques = DataManager::getContarCheques($_recid);
// Busco los recibos segun su talonario
$_reciboobject = DataManager::newObjectOfClass('TRecibos', $_recid);
$_nroTal = $_reciboobject->__get('Talonario');
$_Recibos = DataManager::getRecibos($_nroTal);
if($_cantFacturas == 0){
//Eliminar recibos ANULADOS
$_factResult = DataManager::deleteReciboSinFantura($_recid);
} else {
if($_cantCheques == 0){
//Eliminar recibos Sin cheques
$_chequeResult = DataManager::deleteReciboSinCheque($_recid);
} else {
//Eliminar recibos Con cheques
//$_chequeResult = DataManager::deleteReciboConCheque($_recid);
$facturasIdResult = DataManager::getFacturasRecibo($_recid);
foreach ($facturasIdResult as $k => $factID) {
$_facturaResult = DataManager::deleteChequesFactura($factID['factid']);
}
$_chequeResult = DataManager::deleteReciboSinCheque($_recid);
}
}
// Si al eliminar, la cantidad de recibos es 1. Debería eliminar también la rendición.
if($_cantRecibos == 1){
$_rendicionResult = DataManager::deleteRendicion($_rendid);
}
if(count($_Recibos) == 1) {
DataManager::deletefromtabla('talonario_idusr', 'nrotalonario', $_nroTal);
}
echo "1";
?><file_sep>/rendicion/logica/ajax/buscar.recibo.php
<?php
session_start();
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/class.dm.php" );
if ($_SESSION["_usrrol"]!="A" && $_SESSION["_usrrol"]!="V" && $_SESSION["_usrrol"]!="M"){
echo 'SU SESION HA EXPIRADO.'; exit;
}
//*************************************************
$_nrotalonario = (isset($_REQUEST['nrotalonario'])) ? $_REQUEST['nrotalonario'] : NULL;
$_nrorecibo = (isset($_REQUEST['nrorecibo'])) ? $_REQUEST['nrorecibo'] : NULL;
$salir = 0;
//*************************************************
if((empty($_nrotalonario) or !is_numeric($_nrotalonario)) and $salir == 0){
echo "Debe completar el número de talonario correctamente.\n"; $salir = 1; exit;
}
if((empty($_nrorecibo) or !is_numeric($_nrorecibo)) and $salir == 0){
echo "Debe completar el número de recibo correctamente.\n"; $salir = 1; exit;
}
//*************************************************
if($salir == 0){
//BUSCA EL talonario DE talonario_idusr
$_talorarios = DataManager::getBuscarTalonario($_nrotalonario);
if(count($_talorarios)){
foreach ($_talorarios as $k => $_talonario){
$_talonario = $_talorarios[$k];
$_usuario = $_talonario["idusr"];
if ($_usuario != $_SESSION["_usrid"]){
echo "El número de talonario corresponde a otro Vendedor"; exit;
}
}
//******************//
// CONTROL //
//******************//
//Controlo que el Talonario y Recibo no esté ya cargado en la tabla
$_recibos = DataManager::getRecibos($_nrotalonario, $_nrorecibo);
if(count($_recibos)){ echo "Este recibo ya existe. Intente nuevamente"; exit;
} else {
//Si no existe, veo si puede cargarlo en la rendicion actual
//BUSCA el nro MAX de Recibo del Talonario indicado
/*$_max_recibo = DataManager::getMaxRecibo($_nrotalonario);
$_nro_siguiente = $_max_recibo + 1;
if (($_nrorecibo <= $_max_recibo || $_nrorecibo > $_nro_siguiente)){ //¿¿¿¿ && $max_rec != 0 ???
echo "El número de recibo [ $_nrorecibo ] no es válido. Debe ser $_nro_siguiente."; exit;
} */
//CONTROLA que el Recibo > Menor Nro Recibo && Recibo < (Menor Nro Recibo + 24)
$_min_recibo = DataManager::getMinRecibo($_nrotalonario);
if($_min_recibo){
//si la consulta es != nula (existe algún recibo)
$_max_recibo = $_min_recibo + 25;
if (($_nrorecibo < $_min_recibo || $_nrorecibo > $_max_recibo)){
//Si está dentro del rango
echo "El número de recibo [ $_nrorecibo ] no es válido. Debe estar entre ".($_min_recibo + 1)." y $_max_recibo."; exit;
}
}
}
} else { echo "1"; } //NO EXISTE EL TALONARIO POR LO CUAL ANTES DEBE CREARLO
}
?>
<file_sep>/informes/logica/subir.informes.php
<?php
$tipo = (isset($_POST['tipo'])) ? $_POST['tipo'] : NULL;
if(empty($tipo)){
echo "Indique el tipo de informes a subir.";
} else {
$ruta = $_SERVER['DOCUMENT_ROOT'].'/pedidos/informes/'.$tipo.'/';
$mensage = '';
if ($_FILES){
foreach ($_FILES as $key){
if($key['error'] == UPLOAD_ERR_OK ){
//$partido = explode(".", $_FILES["inf_archivo"]["name"]);
// $extension = end($partido);
//$nombre_archivo = $_tipo_informe.".".$extension;
$NombreOriginal = $key['name']; //Obtenemos el nombre original del archivo
$temporal = $key['tmp_name'];
$destino = $ruta.$NombreOriginal;
move_uploaded_file($temporal, $destino);
}
if ($key['error']==''){
$mensage .= $NombreOriginal.' --> Subido correctamente. </br>';
}
if ($key['error']!=''){//Si existio algún error retornamos un el error por cada archivo.
$mensage .= '-> Error al subir archivo '.$NombreOriginal.' debido a: \n'.$key['error'];
}
}
} else {
echo 'Debe seleccionar algún archivo para enviar.';
}
echo $mensage;
}
?><file_sep>/proveedores/pagos/solicitarfecha/logica/upload.php
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/start.php");
if ($_SESSION["_usrrol"]!="P"){
$_nextURL = sprintf("%s", "/pedidos/login/index.php");
header("Location: $_nextURL");
exit;
}
$_nrofact = (isset($_POST['nrofact'])) ? $_POST['nrofact'] : NULL;
$_ID = $_SESSION["_usrid"];
$_proveedor = DataManager::getProveedor('provid', $_ID, $_SESSION["_usridemp"]);
$empresa = $_proveedor['0']['providempresa'];
$_nombreprov = $_proveedor['0']['provnombre'];
$_telefono = $_proveedor['0']['provtelefono'];
$_empresas = DataManager::getEmpresas(1);
if (count($_empresas)) {
foreach ($_empresas as $k => $_emp) {
if ($empresa == $_emp["empid"]){
$_nombreemp = $_emp["empnombre"];
}
}
}
//*****************************************
// Consulto Email de contacto Cobranzas
//*****************************************
$_contactos = DataManager::getContactosPorCuenta( $_idorigen, $_origen, 1);
if (count($_contactos)) {
foreach ($_contactos as $k => $_cont){
$_ctoid = $_cont["ctoid"];
$_sector = $_cont["ctosector"];
$_sectores = DataManager::getSectores(1);
if($_sectores){
foreach ($_sectores as $k => $_sect) {
$_sectid = $_sect['sectid'];
$_sectnombre = $_sect['sectnombre'];
if($_sect['sectnombre'] == 'Cobranzas'){
$_telefono = $_cont["ctotelefono"]." Int: ".$_cont["ctointerno"];
$_email = $_cont["ctocorreo"];
}
}
}
}
} else {
//**************************//
// Uso Email del usuario //, si no tiene, indico en el mail que hay que notificar por teléfono
//**************************//
$_email = (empty($_SESSION["_usremail"])) ? 0 : $_SESSION["_usremail"];
}
//*****************************************
$_SESSION['nrofact'] = $_nrofact;
//*****************************************
if(empty($_nrofact)) {
$_goURL = "../index.php?sms=1";
header('Location:' . $_goURL);
exit;
}
//******************//
// control arhivo //
//******************//
$archivo_nombre = $_FILES["archivo"]["name"];
$archivo_peso = $_FILES["archivo"]["size"];
$archivo_temporal = $_FILES["archivo"]["tmp_name"];
if ($archivo_peso == 0){
$archivo_nombre = "Sin archivo adjunto";
}
//*********************************//
// Armado del CORREO para el envío //
//*********************************//
require_once( $_SERVER['DOCUMENT_ROOT']."/pedidos/includes/mailConfig.php" );
$mail->From = "<EMAIL>"; //mail de solicitante ¿o de quien envía el mail?
$mail->FromName = "InfoWeb GEZZI"; //"Vendedor: ".$_SESSION["_usrname"];
$mail->Subject = "Solicitud de Fecha de Pago para ".$_nombreemp.", guarde este email.";
if ($archivo_peso !=0) {
$mail->AddAttachment($archivo_temporal, $archivo_nombre);
}
//header And footer
include_once($_SERVER['DOCUMENT_ROOT']."/pedidos/includes/headersAndFooters.php");
$_total = '
<html>
<head>
<title>Notificación de Solicitud</title>
<style type="text/css">
body {
text-align: center;
}
.texto {
float: left;
height: auto;
width: 90%;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
text-align: left;
border-top-width: 0px;
border-bottom-width: 0px;
border-top-style: none;
border-right-style: none;
border-left-style: none;
border-right-width: 0px;
border-left-width: 0px;
border-bottom-style: none;
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 0px;
}
.saludo {
width: 350px;
float: none;
margin-right: 0px;
margin-left: 25px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #409FCB;
height: 35px;
font-family: Arial, Helvetica, sans-serif;
padding: 0px;
text-align: left;
margin-top: 15px;
font-size: 12px;
</style>
</head>
<body>
<div align="center">
<table width="600" border="0" cellspacing="1">
<tr>
<td>'.$cabecera.'</td>
</tr>
<tr>
<td>
<div class="texto">
Se enviaron los datos de <strong>SOLICITUD DE FECHA DE PAGO</strong> de manera satisfactoria.<br />
Recuerde que podrá solicitar su fecha de pago pasados cinco días hábiles de entregada la factura. Ésta se tramitará de Lunes a Miercoles de 09:30 a 12:00 hs.<br />
<div />
</td >
</tr>
<tr bgcolor="#597D92">
<td>
<div class="texto" style="color:#FFFFFF; font-size:14; font-weight: bold;">
<strong>Estos son sus datos de solicitud</strong>
</div>
</td>
</tr>
<tr>
<td height="95" valign="top">
<div class="texto">
<table width="600px" style="border:1px solid #597D92">
<tr>
<th rowspan="2" align="left" width="100">
Proveedor: <br />
Nro. de Factura:<br />
Correo:<br />
Teléfono:<br />
Archivo:
</th>
<th rowspan="2" align="left" width="250">
'.$_nombreprov.'<br />
'.$_nrofact.'<br />
'.$_email.'<br />
'.$_telefono.'<br />
'.$archivo_nombre.'
</th>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div class="texto">
<font color="#999999" size="2" face="Geneva, Arial, Helvetica, sans-serif">
Por cualquier consulta, póngase en contacto con la empresa al 4555-3366 de Lunes a Viernes de 10 a 17 horas.
</font>
<div style="color:#000000; font-size:12px;">
<strong>Le enviaremos un email o teléfono notificando la fecha de pago, al contacto de su cuenta de usuario.</strong></a></br></br>
</div>
</div>
</td>
</tr>
<tr align="center" class="saludo">
<td valign="top">
<div class="saludo">
Gracias por confiar en '.$_nombreemp.'<br/>
Le Saludamos atentamente,
</div>
</td>
</tr>
<tr>
<td valign="top">'.$pie.'</td>
</tr>
</table>
<div />
</body>
';
$mail->msgHTML($_total);
$mail->AddAddress($_email, 'InfoWeb GEZZI');
$mail->AddBCC("<EMAIL>", 'InfoWeb GEZZI');
$mail->AddBCC("<EMAIL>");
//*********************************//
if(!$mail->Send()) {
//Si el envío falla, que mande otro mail indicando que la solicittud no fue correctamente enviada?=?
//echo 'Fallo en el envío';
$_goURL = "../index.php?sms=5";
header('Location:' . $_goURL);
exit;
}
//**********************************//
// Envío el archivo al servidor //
//**********************************//
if ($archivo_peso != 0){
if($archivo_peso > (2048*2048)) {
$_goURL = "../index.php?sms=2";
header('Location:' . $_goURL);
exit;
} else {
//******************//
// datos del arhivo //
//******************//
# definimos la carpeta destino
$_destino = "../archivos/proveedor/".$_ID."/";
if($_FILES["archivo"]["type"]=="image/jpeg" || $_FILES["archivo"]["type"]=="image/pjpeg" || $_FILES["archivo"]["type"]=="image/gif" || $_FILES["archivo"]["type"]=="image/png" || $_FILES["archivo"]["type"]=="application/pdf") {
# Si exsite la carpeta o se ha creado
if(file_exists($_destino) || @mkdir($_destino, 0777, true)) {
$origen = $archivo_temporal;
$info = new SplFileInfo($archivo_nombre);
$destino = $_destino.'documentoF'.date("dmYHms").".".$info->getExtension(); //nombre del archivo
# movemos el archivo
if(@move_uploaded_file($archivo_temporal, $destino)) {
//echo "<br>".$_FILES["archivo".$i]["name"]." movido correctamente";
}else{
//echo "<br>No se ha podido mover el archivo: ".$_FILES["archivo".$i]["name"];
$_goURL = "../index.php?sms=4";
header('Location:' . $_goURL);
exit;
}
}else {
//echo "<br>No se ha podido crear la carpeta: up/".$user;
$_goURL = "../index.php?sms=4";
header('Location:' . $_goURL);
exit;
}
} else {
//el archivo debe ser pdf o imagen
$_goURL = "../index.php?sms=3";
header('Location:' . $_goURL);
exit;
}
}
}
/****************************************/
unset($_SESSION['nrofact']);
/****************************************/
$_goURL = "../index.php?sms=6";
header('Location:'.$_goURL);
exit;
?>
<file_sep>/rendicion/logica/jquery/jquery.rendicion.js
//Cargas a Inicio de Rendición
$(document).ready(function() {
abrirVentana();
});
function abrirVentana() {
//******************************************//
$('#open_talonario').click(function(){
$('#popup-flotante').fadeIn('slow');
$('#popup-talonario').fadeIn('slow');
$('#popup-talonario').css({
'left': ($(window).width() / 2 - $(window).width() / 2) + 'px',
'top': ($(window).height() / 2 - $(window).height() / 2) + 'px'
});
$('.popup-overlay').fadeIn('slow');
$('.popup-overlay').height($(window).height());
return false;
});
$('#close-talonario').click(function(){
$('#popup-flotante').fadeOut('slow');
$('#popup-talonario').fadeOut('slow');
$('.popup-overlay').fadeOut('slow');
$('#fm_nvo_recibo')[0].reset();
$('#close-recibo').click();
return false;
});
//**********************************//
$('#open-recibo').click(function(){
$('#popup-recibo').fadeIn('slow');
$('.popup-overlay2').fadeIn('slow');
$('.popup-overlay2').height($(window).height());
return false;
});
$('#close-recibo').click(function(){
$('#popup-recibo').fadeOut('slow');
$('.popup-overlay2').fadeOut('slow');
return false;
});
//******************************************//
}
| 57b8a08fb431e79492fa8667c85c21f78844a7c7 | [
"JavaScript",
"Markdown",
"PHP"
] | 322 | JavaScript | daciocco/Neo-farma | f016982dbb0d7a1a12af4d53a3cf64da4f9c0157 | f83c72180c9a952c7f2332845a7d654401646131 | |
refs/heads/main | <repo_name>DavidBartTobi/Algebra-Tools<file_sep>/inverse_Matrix.py
from tkinter import ttk
from tkinter import *
from tkinter import messagebox
from utilities import gui_utilities, coordinate_Entry, errors
import inverse_Entry
import numpy as np
from numpy.linalg import inv
from itertools import cycle
class InverseMatrix:
def __init__(self, top, dimension):
self.top = top
self.dimension = dimension
self.entries = [[],[],[],[],[],[]]
self.colors = cycle(["#add8e6", '#ffcccb', '#90ee90'])
gui_utilities.Window_Style(self.top, "מטריצה הפכית", "285x328")
self.dimension_status6 = 'normal'
self.dimension_status5 = 'normal'
self.dimension_status4 = 'normal'
self.dimension_status3 = 'normal'
if dimension<6:
self.dimension_status6 = 'disabled'
if dimension<5:
self.dimension_status5 = 'disabled'
if dimension<4:
self.dimension_status4 = 'disabled'
if dimension<3:
self.dimension_status3 = 'disabled'
self.background_label = Label(self.top, width=40, height=20, bg=gui_utilities.Main_Theme_Color())
self.background_label.grid(row=1, column=0, rowspan=8, columnspan=6, sticky=W + N + E + S)
coordinate_Entry.Coordinate_Entry(self.top, self.entries, self.dimension_status3, self.dimension_status4,
self.dimension_status5, self.dimension_status6)
self.confirm_button = ttk.Button(self.top, text="אישור", command=self.Get_Inverse, width=5,
cursor='hand2')
self.confirm_button.grid(row=7, column=0, pady=(20, 10), padx=(53, 0), columnspan=3)
self.clear_button = ttk.Button(self.top, text=" נקה", command=self.Clear_Entries, width=5,
cursor='hand2')
self.clear_button.grid(row=7, column=3, pady=(20, 10), padx=(0, 53), columnspan=3)
self.dimension_button = ttk.Button(self.top, text=" שנה גודל מטריצה", command=self.Change_Dimension,
cursor='hand2', width=20)
self.dimension_button.grid(row=8, column=0, pady=(10, 20), columnspan=6)
self.top.bind('<Return>', lambda func: self.Get_Inverse())
self.entries[0][0].focus_force()
def Get_Inverse(self):
vectors = []
for i in range(self.dimension):
vectors.append([])
for j in range(self.dimension):
if len(self.entries[i][j].get()) == 0:
errors.Empty_Error()
self.top.lift()
self.entries[i][j].focus_force()
return
try:
vectors[i].append(float(self.entries[i][j].get()))
except:
errors.Instance_Error("מספר")
self.top.lift()
self.entries[i][j].focus_force()
return
self.Clear_Entries()
np_vectors = np.array(vectors)
try:
inverse = inv(np_vectors)
inverse = inverse.round(self.dimension)
color = next(self.colors)
for i in range(self.dimension):
for j in range(self.dimension):
if float(inverse[i][j]).is_integer():
self.entries[i][j].insert(0, int(float(inverse[i][j])))
else:
self.entries[i][j].insert(0, float(inverse[i][j]))
self.entries[i][j].configure(bg=color)
for i in range(len(vectors)):
for j in range(len(vectors)):
if float(vectors[i][j]).is_integer():
vectors[i][j] = int(float(inverse[i][j]))
else:
vectors[i][j] = float(inverse[i][j])
except:
messagebox.showerror("Error", f"The matrix is NOT invertible.")
self.top.destroy()
def Clear_Entries(self):
for row in self.entries:
for entry in row:
entry.delete(0, END)
self.entries[0][0].focus_force()
def Change_Dimension(self):
top = Toplevel()
inverse_Entry.InverseEntry(top)
self.top.destroy()
<file_sep>/utilities/coordinate_Entry.py
from tkinter import *
def Coordinate_Entry(top, entries, dimension_status3, dimension_status4, dimension_status5, dimension_status6):
entries[0].append(Entry(top, width=3, justify='center', state='normal'))
entries[0][0].grid(row=1, column=0, pady=15, padx=(10, 0))
entries[0].append(Entry(top, width=3, justify='center', state='normal'))
entries[0][1].grid(row=1, column=1, pady=15)
entries[0].append(Entry(top, width=3, justify='center', state=dimension_status3, disabledbackground='gray'))
entries[0][2].grid(row=1, column=2, pady=15)
entries[0].append(Entry(top, width=3, justify='center', state=dimension_status4, disabledbackground='gray'))
entries[0][3].grid(row=1, column=3, pady=15)
entries[0].append(Entry(top, width=3, justify='center', state=dimension_status5, disabledbackground='gray'))
entries[0][4].grid(row=1, column=4, pady=15)
entries[0].append(Entry(top, width=3, justify='center', state=dimension_status6, disabledbackground='gray'))
entries[0][5].grid(row=1, column=5, pady=15, padx=(0, 10))
entries[1].append(Entry(top, width=3, justify='center', state='normal'))
entries[1][0].grid(row=2, column=0, padx=(10, 0))
entries[1].append(Entry(top, width=3, justify='center', state='normal'))
entries[1][1].grid(row=2, column=1)
entries[1].append(Entry(top, width=3, justify='center', state=dimension_status3, disabledbackground='gray'))
entries[1][2].grid(row=2, column=2)
entries[1].append(Entry(top, width=3, justify='center', state=dimension_status4, disabledbackground='gray'))
entries[1][3].grid(row=2, column=3)
entries[1].append(Entry(top, width=3, justify='center', state=dimension_status5, disabledbackground='gray'))
entries[1][4].grid(row=2, column=4)
entries[1].append(Entry(top, width=3, justify='center', state=dimension_status6, disabledbackground='gray'))
entries[1][5].grid(row=2, column=5, padx=(0 ,10))
entries[2].append(Entry(top, width=3, justify='center', state=dimension_status3, disabledbackground='gray'))
entries[2][0].grid(row=3, column=0, pady=(15,0), padx=(10, 0))
entries[2].append(Entry(top, width=3, justify='center', state=dimension_status3, disabledbackground='gray'))
entries[2][1].grid(row=3, column=1, pady=(15,0))
entries[2].append(Entry(top, width=3, justify='center', state=dimension_status3, disabledbackground='gray'))
entries[2][2].grid(row=3, column=2, pady=(15,0))
entries[2].append(Entry(top, width=3, justify='center', state=dimension_status4, disabledbackground='gray'))
entries[2][3].grid(row=3, column=3, pady=(15,0))
entries[2].append(Entry(top, width=3, justify='center', state=dimension_status5, disabledbackground='gray'))
entries[2][4].grid(row=3, column=4, pady=(15,0))
entries[2].append(Entry(top, width=3, justify='center', state=dimension_status6, disabledbackground='gray'))
entries[2][5].grid(row=3, column=5, pady=(15,0), padx=(0, 10))
entries[3].append(Entry(top, width=3, justify='center', state=dimension_status4, disabledbackground='gray'))
entries[3][0].grid(row=4, column=0, pady=(15,0), padx=(10, 0))
entries[3].append(Entry(top, width=3, justify='center', state=dimension_status4, disabledbackground='gray'))
entries[3][1].grid(row=4, column=1, pady=(15,0))
entries[3].append(Entry(top, width=3, justify='center', state=dimension_status4, disabledbackground='gray'))
entries[3][2].grid(row=4, column=2, pady=(15,0))
entries[3].append(Entry(top, width=3, justify='center', state=dimension_status4, disabledbackground='gray'))
entries[3][3].grid(row=4, column=3, pady=(15,0))
entries[3].append(Entry(top, width=3, justify='center', state=dimension_status5, disabledbackground='gray'))
entries[3][4].grid(row=4, column=4, pady=(15,0))
entries[3].append(Entry(top, width=3, justify='center', state=dimension_status6, disabledbackground='gray'))
entries[3][5].grid(row=4, column=5, pady=(15,0), padx=(0, 10))
entries[4].append(Entry(top, width=3, justify='center', state=dimension_status5, disabledbackground='gray'))
entries[4][0].grid(row=5, column=0, pady=(15,0), padx=(10, 0))
entries[4].append(Entry(top, width=3, justify='center', state=dimension_status5, disabledbackground='gray'))
entries[4][1].grid(row=5, column=1, pady=(15,0))
entries[4].append(Entry(top, width=3, justify='center', state=dimension_status5, disabledbackground='gray'))
entries[4][2].grid(row=5, column=2, pady=(15,0))
entries[4].append(Entry(top, width=3, justify='center', state=dimension_status5, disabledbackground='gray'))
entries[4][3].grid(row=5, column=3, pady=(15,0))
entries[4].append(Entry(top, width=3, justify='center', state=dimension_status5, disabledbackground='gray'))
entries[4][4].grid(row=5, column=4, pady=(15,0))
entries[4].append(Entry(top, width=3, justify='center', state=dimension_status6, disabledbackground='gray'))
entries[4][5].grid(row=5, column=5, pady=(15,0), padx=(0, 10))
entries[5].append(Entry(top, width=3, justify='center', state=dimension_status6, disabledbackground='gray'))
entries[5][0].grid(row=6, column=0, pady=(15,0), padx=(10, 0))
entries[5].append(Entry(top, width=3, justify='center', state=dimension_status6, disabledbackground='gray'))
entries[5][1].grid(row=6, column=1, pady=(15,0))
entries[5].append(Entry(top, width=3, justify='center', state=dimension_status6, disabledbackground='gray'))
entries[5][2].grid(row=6, column=2, pady=(15,0))
entries[5].append(Entry(top, width=3, justify='center', state=dimension_status6, disabledbackground='gray'))
entries[5][3].grid(row=6, column=3, pady=(15,0))
entries[5].append(Entry(top, width=3, justify='center', state=dimension_status6, disabledbackground='gray'))
entries[5][4].grid(row=6, column=4, pady=(15,0))
entries[5].append(Entry(top, width=3, justify='center', state=dimension_status6, disabledbackground='gray'))
entries[5][5].grid(row=6, column=5, pady=(15,0), padx=(0, 10))<file_sep>/axis_2d.py
import matplotlib.pyplot as plt
from itertools import cycle
import numpy as np
class Axis_2D:
def __init__(self, x_vectors, y_vectors, max_vector):
X = x_vectors
Y = y_vectors
# Creating the subplots and projecting the vectors
fig, ax = plt.subplots()
colors = cycle('grbcmy')
for i in range(len(x_vectors)):
current = next(colors)
ax.quiver([0], [0], X[i], Y[i], units='xy', scale=1, color=current)
if X[i].is_integer():
X[i] = int(X[i])
if Y[i].is_integer():
Y[i] = int(Y[i])
ax.text(X[i], Y[i], f'({X[i]},{Y[i]})', color=current)
# Modifying the distance shown between the ticks\lines depending on the vector sizes
major_ticks = np.arange(-10, 11, 1)
minor_ticks = np.arange(-10, 11, 1)
if max_vector>10 and max_vector <=100:
major_ticks = np.arange(-100, 101, 10)
minor_ticks = np.arange(-100, 101, 10)
if max_vector>100 and max_vector <=1000:
major_ticks = np.arange(-1000, 1001, 200)
minor_ticks = np.arange(-1000, 1001, 200)
ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)
ax.grid(which='both')
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.2)
# UI details
plt.grid() # grid lines
ax.set_aspect('equal') # Spaces of boxes
ax.axhline(y=0, color='k') # coloring origin Axis
ax.axvline(x=0, color='k')
fig.set_size_inches(6, 6) # Setting figure size
# Naming the Axis
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
<file_sep>/main.pyw
from tkinter import *
from utilities import gui_utilities
from PIL import ImageTk, Image
from tkinter import ttk
from vector_Entry_2d import Vector_Visualization_2D
from vector_Entry_3d import Vector_Visualization_3D
from inverse_Entry import InverseEntry
from determinant_Entry import DeterminantEntry
main_root = Tk()
gui_utilities.Window_Style(main_root, " University Tools", "1003x589")
image = Image.open('images/main_img4.jpg')
resized_image = ImageTk.PhotoImage(image)
img_label = Label(main_root, image=resized_image, bg=gui_utilities.Main_Theme_Color())
img_label.grid(row=0, column=0, rowspan=5, columnspan=2)
main_root.iconbitmap('images/matrix.ico')
def Vector_Visualization_2D_Tab():
vector_top = Toplevel()
Vector_Visualization_2D(vector_top)
def Vector_Visualization_3D_Tab():
vector_top = Toplevel()
Vector_Visualization_3D(vector_top)
def Inverse_Matrix_Tab():
inverse_top = Toplevel()
InverseEntry(inverse_top)
def Determinant_Tab():
det_top = Toplevel()
DeterminantEntry(det_top)
vector_2d_button = ttk.Button(main_root, text=" הצגת וקטור דו-מימדי", command=Vector_Visualization_2D_Tab, width=21,
cursor='hand2')
vector_2d_button.grid(row=0, column=0, pady=100, padx=(150,0))
vector_3d_button = ttk.Button(main_root, text=" הצגת וקטור תלת-מימדי", command=Vector_Visualization_3D_Tab, width=21,
cursor='hand2')
vector_3d_button.grid(row=1, column=0, padx=(150,0))
Inverse_Matrix_button = ttk.Button(main_root, text=" חישוב מטריצה הפכית", command=Inverse_Matrix_Tab, width=21,
cursor='hand2')
Inverse_Matrix_button.grid(row=0, column=1, pady=100, padx=(0,150))
determinant_button = ttk.Button(main_root, text=" חישוב דטרמיננטה", command=Determinant_Tab, width=21,
cursor='hand2')
determinant_button.grid(row=1, column=1, pady=25, padx=(0,150))
main_root.mainloop()<file_sep>/determinant.py
from tkinter import ttk
from tkinter import *
import numpy as np
from numpy.linalg import inv
from utilities import gui_utilities, coordinate_Entry, errors
import determinant_Entry
class Determinant:
def __init__(self, top, dimension):
self.top = top
self.dimension = dimension
self.entries = [[],[],[],[],[],[]]
gui_utilities.Window_Style(self.top, "חישוב דטרמיננטה", "285x371")
self.dimension_status6 = 'normal'
self.dimension_status5 = 'normal'
self.dimension_status4 = 'normal'
self.dimension_status3 = 'normal'
if dimension<6:
self.dimension_status6 = 'disabled'
if dimension<5:
self.dimension_status5 = 'disabled'
if dimension<4:
self.dimension_status4 = 'disabled'
if dimension<3:
self.dimension_status3 = 'disabled'
self.background_label = Label(self.top, width=40, height=20, bg=gui_utilities.Main_Theme_Color())
self.background_label.grid(row=1, column=0, rowspan=9, columnspan=6, sticky=W + N + E + S)
coordinate_Entry.Coordinate_Entry(self.top, self.entries, self.dimension_status3, self.dimension_status4,
self.dimension_status5, self.dimension_status6)
self.confirm_button = ttk.Button(self.top, text="אישור", command=self.Get_Determinant, width=5,
cursor='hand2')
self.confirm_button.grid(row=7, column=0, pady=(20, 10), padx=(53, 0), columnspan=3)
self.clear_button = ttk.Button(self.top, text=" נקה", command=self.Clear_Entries, width=5,
cursor='hand2')
self.clear_button.grid(row=7, column=3, pady=(20, 10), padx=(0, 53), columnspan=3)
self.dimension_button = ttk.Button(self.top, text=" שנה גודל מטריצה", command=self.Change_Dimension,
cursor='hand2', width=20)
self.dimension_button.grid(row=8, column=0, pady=(10, 15), columnspan=6)
self.det_frame = LabelFrame(self.top, bg=gui_utilities.Main_Theme_Color())
self.det_frame.grid(row=9, column=0, columnspan=6, pady=(0,20))
self.det_label = Label(self.det_frame, font='Helvetica', text="תוצאה", bg='#F9EFDA')
self.det_label.grid(row=9, column=0, columnspan=6)
self.top.bind('<Return>', lambda func: self.Get_Determinant())
self.entries[0][0].focus_force()
def Get_Determinant(self):
vectors = []
for i in range(self.dimension):
vectors.append([])
for j in range(self.dimension):
if len(self.entries[i][j].get()) == 0:
errors.Empty_Error()
self.top.lift()
self.entries[i][j].focus_force()
return
try:
vectors[i].append(int(self.entries[i][j].get()))
except:
errors.Instance_Error("מספר")
self.top.lift()
self.entries[i][j].focus_force()
return
# Getting the determinant
np_vectors = np.array(vectors)
det = np.linalg.det(np_vectors)
# Checking if the determinant provided by numpy is a number that needs to be rounded
# (for example, numpy returns -3.00000000000004 instead of -3 for the matrix [123, 132, 111])
count_zeroes = 0
count_nines = 0
if '.' in str(det):
index = str(det).index('.')
for i in range(index+1, len(str(det))):
if str(det)[i] == '0':
count_zeroes += 1
elif str(det)[i] == '9':
count_nines += 1
else:
break
if count_zeroes >= 7 or count_nines >= 7:
final_det = int(det)
self.det_label.configure(text=str(final_det))
self.entries[0][0].focus_force()
else:
self.det_label.configure(text=det)
self.entries[0][0].focus_force()
else:
self.det_label.configure(text=det)
self.entries[0][0].focus_force()
self.Clear_Entries()
def Clear_Entries(self):
for row in self.entries:
for entry in row:
entry.delete(0, END)
self.entries[0][0].focus_force()
def Change_Dimension(self):
top = Toplevel()
determinant_Entry.DeterminantEntry(top)
self.top.destroy()
<file_sep>/utilities/gui_utilities.py
from ttkthemes import ThemedStyle
def Center_Window(win):
win.update_idletasks()
screen_width = win.winfo_screenwidth()
screen_height = win.winfo_screenheight()
size = tuple(int(_) for _ in win.geometry().split('+')[0].split('x'))
x = screen_width / 2 - size[0] / 2
y = screen_height / 2 - size[1] / 2
return x, y
def Window_Style(top, title, geometry):
top.title(title)
top.geometry(geometry)
top.resizable(width=False, height=False)
w, h = Center_Window(top)
top.geometry("+%d+%d" % (w, h))
# ttk theme:
style = ThemedStyle(top)
style.set_theme('blue')
def Main_Theme_Color():
return '#aa5922'
<file_sep>/vector_Entry_3d.py
from tkinter import *
from tkinter import ttk
from axis_3d import Axis_3D
from utilities import gui_utilities, errors
class Vector_Visualization_3D():
def __init__(self, top):
self.x_vectors = []
self.y_vectors = []
self.z_vectors = []
self.max_vector = 0
self.top = top
gui_utilities.Window_Style(self.top, "3D", "195x195")
self.background_label = Label(self.top, bg=gui_utilities.Main_Theme_Color(), width=27)
self.background_label.grid(row=0, column=0, rowspan=5, columnspan=2, sticky=W + N + E + S)
self.x_label = Label(top, text="X", anchor='center', width=6, bg=gui_utilities.Main_Theme_Color())
self.x_label.grid(row=1, column=0, pady=20)
self.y_label = Label(top, text="Y", anchor='center', width=6, bg=gui_utilities.Main_Theme_Color())
self.y_label.grid(row=2, column=0)
self.z_label = Label(top, text="Z", anchor='center', width=6, bg=gui_utilities.Main_Theme_Color())
self.z_label.grid(row=3, column=0, pady=20)
self.x_entry = ttk.Entry(top, width=6, justify='center')
self.x_entry.grid(row=1, column=1, pady=20)
self.y_entry = ttk.Entry(top, width=6, justify='center')
self.y_entry.grid(row=2, column=1)
self.z_entry = ttk.Entry(top, width=6, justify='center')
self.z_entry.grid(row=3, column=1, pady=20)
self.add_button = ttk.Button(top, text="הוסף", command=self.Add_Vector, cursor='hand2')
self.add_button.grid(row=4, column=0, pady=(0, 20))
self.show_button = ttk.Button(top, text="הצג", command=self.Show_Vector, cursor='hand2')
self.show_button.grid(row=4, column=1, pady=(0, 20))
self.top.bind('<Return>', lambda func: self.Add_Vector())
self.x_entry.focus_force()
def Add_Vector(self):
# Checking if the entries are empty
if len(self.x_entry.get()) == 0:
errors.Empty_Error()
self.top.lift()
self.x_entry.focus_force()
return
if len(self.y_entry.get()) == 0:
errors.Empty_Error()
self.top.lift()
self.y_entry.focus_force()
return
if len(self.z_entry.get()) == 0:
errors.Empty_Error()
self.top.lift()
self.z_entry.focus_force()
return
try:
# Checking if the entries are numbers before we enter only 1 of them by mistake
float(self.x_entry.get())
float(self.y_entry.get())
float(self.z_entry.get())
# Checking the biggest vector
if abs(float(self.x_entry.get())) > self.max_vector:
self.max_vector = abs(float(self.x_entry.get()))
if abs(float(self.y_entry.get())) > self.max_vector:
self.max_vector = abs(float(self.y_entry.get()))
if abs(float(self.z_entry.get())) > self.max_vector:
self.max_vector = abs(float(self.z_entry.get()))
# Entering the entries and deleting them from the fields
self.x_vectors.append(float(self.x_entry.get()))
self.y_vectors.append(float(self.y_entry.get()))
self.z_vectors.append(float(self.z_entry.get()))
self.x_entry.delete(0, END)
self.y_entry.delete(0, END)
self.z_entry.delete(0, END)
self.x_entry.focus_force()
except:
errors.Instance_Error("מספר")
self.top.lift()
self.x_entry.focus_force()
return
def Show_Vector(self):
self.top.destroy()
Axis_3D(self.x_vectors, self.y_vectors, self.z_vectors, self.max_vector)<file_sep>/vector_Entry_2d.py
from tkinter import *
from tkinter import ttk
from utilities import gui_utilities, errors
from axis_2d import Axis_2D
class Vector_Visualization_2D:
def __init__(self, top):
self.x_vectors = []
self.y_vectors = []
self.max_vector = 0
self.top = top
gui_utilities.Window_Style(self.top, "2D", "195x150")
self.background_label = Label(self.top, bg=gui_utilities.Main_Theme_Color(), width=27)
self.background_label.grid(row=0, column=0, rowspan=4, columnspan=2, sticky=W + N + E + S)
self.x_label = Label(top, text="X", anchor='center', width=6, bg=gui_utilities.Main_Theme_Color())
self.x_label.grid(row=1, column=0, pady=20)
self.y_label = Label(top, text="Y", anchor='center', width=6, bg=gui_utilities.Main_Theme_Color())
self.y_label.grid(row=2, column=0, pady=(0, 20))
self.x_entry = ttk.Entry(top, width=6, justify='center')
self.x_entry.grid(row=1, column=1, pady=20)
self.y_entry = ttk.Entry(top, width=6, justify='center')
self.y_entry.grid(row=2, column=1, pady=(0, 20))
self.add_button = ttk.Button(top, text="הוסף", command=self.Add_Vector, cursor='hand2')
self.add_button.grid(row=3, column=0, pady=(0, 20))
self.show_button = ttk.Button(top, text="הצג", command=self.Show_Vector, cursor='hand2')
self.show_button.grid(row=3, column=1, pady=(0, 20))
self.top.bind('<Return>', lambda func: self.Add_Vector()) # Binding the 'Enter' key to a button
self.x_entry.focus_force()
def Add_Vector(self):
# Checking if the entries are empty
if len(self.x_entry.get()) == 0:
errors.Empty_Error()
self.top.lift()
self.x_entry.focus_force()
return
if len(self.y_entry.get()) == 0:
errors.Empty_Error()
self.top.lift()
self.y_entry.focus_force()
return
try:
# Checking if the entries are numbers before we enter only 1 of them by mistake
float(self.x_entry.get())
float(self.y_entry.get())
# Checking the biggest vector
if abs(float(self.x_entry.get())) > self.max_vector:
self.max_vector = abs(float(self.x_entry.get()))
if abs(float(self.y_entry.get())) > self.max_vector:
self.max_vector = abs(float(self.y_entry.get()))
# Entering the entries and deleting them from the fields
self.x_vectors.append(float(self.x_entry.get()))
self.y_vectors.append(float(self.y_entry.get()))
self.x_entry.delete(0, END)
self.y_entry.delete(0, END)
self.x_entry.focus_force()
except:
errors.Instance_Error("מספר")
self.top.lift()
self.x_entry.focus_force()
return
def Show_Vector(self):
self.top.destroy()
Axis_2D(self.x_vectors, self.y_vectors, self.max_vector)<file_sep>/inverse_Entry.py
from tkinter import ttk
from tkinter import *
from utilities import gui_utilities, errors
from inverse_Matrix import InverseMatrix
class InverseEntry:
def __init__(self, top):
self.top = top
gui_utilities.Window_Style(self.top, "מטריצה הפכית", "332x150")
self.background_label = Label(self.top, width=47, bg=gui_utilities.Main_Theme_Color())
self.background_label.grid(row=1, column=0, rowspan=4, sticky=W + N + E + S)
self.label = Label(self.top, text='הזינו את גודל המטריצה הריבועית (2 - 6):', width=20, height=3,
bg=gui_utilities.Main_Theme_Color())
self.label.grid(row=0, column=0, sticky=W + N + E + S)
self.entry = ttk.Entry(self.top, width=10, justify='center')
self.entry.grid(row=2, column=0, pady=5, padx=50)
self.button = ttk.Button(self.top, text="אישור", command=self.Coordinate_Entry, cursor='hand2')
self.button.grid(row=3, column=0, pady=(15, 25))
self.top.bind('<Return>', lambda func: self.Coordinate_Entry())
self.entry.focus_force()
def Coordinate_Entry(self):
if len(self.entry.get()) == 0:
errors.Empty_Error()
self.top.lift()
self.entry.focus_force()
return
try:
if int(self.entry.get()) < 2 or int(self.entry.get()) > 6:
errors.Range_Error('2', '6')
self.top.lift()
self.entry.focus_force()
return
except:
errors.Instance_Error("מספר")
self.top.lift()
self.entry.focus_force()
return
dimension = int(self.entry.get())
coordinate_top = Toplevel()
self.top.destroy()
InverseMatrix(coordinate_top, dimension)
<file_sep>/utilities/errors.py
from tkinter import messagebox
def Instance_Error(instance):
messagebox.showerror("שגיאה", f"אנא הזינו {instance}")
def Range_Error(min, max):
messagebox.showerror("שגיאה", f"הטווח המותר הוא: {max} - {min}")
def Empty_Error():
messagebox.showerror("שגיאה", f"אנא מלאו את כל השדות")
<file_sep>/axis_3d.py
from itertools import cycle
import matplotlib.pyplot as plt
import numpy as np
class Axis_3D:
def __init__(self, x_vectors, y_vectors, z_vectors, max_vector):
X = x_vectors
Y = y_vectors
Z = z_vectors
# Creating the subplots and the axis
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Modifying the distance shown between the ticks\lines depending on the vector sizes
major_ticks = np.arange(-10, 11, 2)
minor_ticks = np.arange(-10, 11, 2)
axis_tick_modifier = 10
if max_vector>10 and max_vector <=100:
axis_tick_modifier*=10
major_ticks = np.arange(-100, 101, 20)
minor_ticks = np.arange(-100, 101, 20)
if max_vector>100 and max_vector <=1000:
axis_tick_modifier*=100
major_ticks = np.arange(-1000, 1001, 200)
minor_ticks = np.arange(-1000, 1001, 200)
x, y, z = np.array([[-axis_tick_modifier, 0, 0], [0, -axis_tick_modifier, 0], [0, 0, -axis_tick_modifier]])
u, v, w = np.array([[2*axis_tick_modifier, 0, 0], [0, 2*axis_tick_modifier, 0], [0, 0, 2*axis_tick_modifier]])
ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)
ax.set_zticks(major_ticks)
ax.set_zticks(minor_ticks, minor=True)
ax.grid(which='both')
ax.grid(which='minor', alpha=0.5)
ax.grid(which='major', alpha=0.5)
# Setting the origin axis vectors and the size of the figure
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
ax.set_zlim(-10, 10)
fig.set_size_inches(7, 6)
# Make a 3D quiver plot
ax.quiver(x, y, z, u, v, w, arrow_length_ratio=0.1, color="black")
# Naming the axis
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# Projecting the vectors while rotating their colors
colors = cycle('grbcmy')
for i in range(len(x_vectors)):
current = next(colors)
ax.quiver([0], [0], [0], X[i], Y[i], Z[i], color=current)
if X[i].is_integer():
X[i] = int(X[i])
if Y[i].is_integer():
Y[i] = int(Y[i])
if Z[i].is_integer():
Z[i] = int(Z[i])
ax.text(X[i], Y[i], Z[i], f'({X[i]},{Y[i]},{Z[i]})', color=current)
plt.show()
| 9eeedd63adbb97dbc4981d9d28e58441294ca8b1 | [
"Python"
] | 11 | Python | DavidBartTobi/Algebra-Tools | 457d1a7e4f732d4a1005f6fc74e10b6bd10164b7 | 12efd3c0bbd23e35377ba8b10bcba0c816eee05d | |
refs/heads/main | <repo_name>wild0ni0n/counting_color_for_minecraft<file_sep>/countin_color_tool.py
from tkinter import filedialog, Tk, Label, messagebox, Canvas
import getpass
from PIL import Image, ImageTk
from typing import Tuple
def conv_webcolor(rgb: Tuple[int, int, int]):
hex_colors = list(map(lambda x: hex(x)[2:].zfill(2), rgb))
return '#' + "".join(hex_colors).upper()
# initialized window
root = Tk()
root.title('Counting Color Tool for Minecraft')
root.geometry("400x300")
# open file dialog and read image
filetype=[('PNG','*.png'), ('すべてのファイル', '*.*')]
initialdir="C:\\Users\\{}\\Pictures".format(getpass.getuser())
filepath = filedialog.askopenfilename(filetypes=filetype, initialdir=initialdir)
im = Image.open(filepath)
colors = im.getcolors(im.size[0] * im.size[1])
if len(colors) > 255:
messagebox.showerror("エラー", "画像の色数が多すぎます。255色以下に減色してください")
exit()
# show image
#pi = ImageTk.PhotoImage(im)
#canvas = Canvas(bg = "black", width=im.size[0], height=im.size[1])
#canvas.create_image(30, 30, image=pi)
# label
lbl_head_title1 = Label(text="色コード")
lbl_head_title2 = Label(text="使用数")
lbl_head_title1.grid(row=0, column=1)
lbl_head_title2.grid(row=0, column=3)
for num, (cnt, rgb) in enumerate(colors):
print(rgb)
if len(rgb) == 4:
(rgb) = (rgb)[:3]
webcolor = conv_webcolor(rgb)
lbl_webcolor = Label(text=webcolor)
lbl_colorbox = Label(text="■", foreground=webcolor)
lbl_color_count = Label(text=cnt)
lbl_webcolor.grid(row=num+1, column=1)
lbl_colorbox.grid(row=num+1, column=2)
lbl_color_count.grid(row=num+1, column=3)
root.mainloop()
| b500cf499bb8c4cdeb7720f2a46af29ac245ea28 | [
"Python"
] | 1 | Python | wild0ni0n/counting_color_for_minecraft | f3109da46af552c776062454f7c14b713a5220bd | 869a441af23565342313002f76ea4887dd7a141e | |
refs/heads/master | <repo_name>linhsaarnold/Project3<file_sep>/p2-login.js
function navbarsearch() {
alert("I'm sorry, we can't find what you're looking for.");
}
<file_sep>/p2-all.js
function navbarsearch() {
alert("I'm sorry, we can't find what you're looking for.");
}
function moreinfoA() {
alert("No Info Available");
}
function moreinfoB() {
alert("from Winter 2017 Semester with <NAME>");
}
function moreinfoC() {
alert("From Winter 2017 Semester with <NAME>");
}
function moreinfoD() {
alert("From Fall 2016 Semester with <NAME>");
}
function moreinfoE() {
alert("From Winter 2017 Semester with <NAME>");
}
function moreinfoF() {
alert("Size small, from a vintage shop in Harajuku, Tokyo");
}
function moreinfoG() {
alert("Size 26, Levis");
}
function moreinfoH() {
alert("No Info Available");
}
function moreinfoI() {
alert("No Info Available");
}
function moreinfoJ() {
alert("No Info Available");
}
function moreinfoK() {
alert("Size Small, American Apparel");
}
function moreinfoL() {
alert("No Info Available");
}
function moreinfoM() {
alert("No Info Available");
}
function moreinfoN() {
alert("No Info Available");
}
function moreinfoO() {
alert("No Info Available");
}
var countA = 0;
function addinterestA() {
countA++;
document.getElementById("IntA").innerHTML = countA;
}
var countB = 0;
function addinterestB() {
countB++;
document.getElementById("IntB").innerHTML = countB;
}
var countC = 0;
function addinterestC() {
countC++;
document.getElementById("IntC").innerHTML = countC;
}
var countD = 0;
function addinterestD() {
countD++;
document.getElementById("IntD").innerHTML = countD;
}
var countE = 0;
function addinterestE() {
countE++;
document.getElementById("IntE").innerHTML = countE;
}
var countF = 0;
function addinterestF() {
countF++;
document.getElementById("IntF").innerHTML = countF;
}
var countG = 0;
function addinterestG() {
countG++;
document.getElementById("IntG").innerHTML = countG;
}
var countH = 0;
function addinterestH() {
countH++;
document.getElementById("IntH").innerHTML = countH;
}
var countI = 0;
function addinterestI() {
countI++;
document.getElementById("IntI").innerHTML = countI;
}
var countJ = 0;
function addinterestJ() {
countJ++;
document.getElementById("IntJ").innerHTML = countJ;
}
var countK = 0;
function addinterestK() {
countK++;
document.getElementById("IntK").innerHTML = countK;
}
var countL = 0;
function addinterestL() {
countL++;
document.getElementById("IntL").innerHTML = countL;
}
var countM = 0;
function addinterestM() {
countM++;
document.getElementById("IntM").innerHTML = countM;
}
var countN = 0;
function addinterestN() {
countN++;
document.getElementById("IntN").innerHTML = countN;
}
var countO = 0;
function addinterestO() {
countO++;
document.getElementById("IntO").innerHTML = countO;
}
<file_sep>/project2.js
function navbarsearch() {
alert("I'm sorry, we can't find what you're looking for.");
}
function moreinfo() {
alert("No Info Available");
}
var countA = 0;
function addinterestA() {
countA++;
document.getElementById("IntA").innerHTML = countA;
}
| b6348382dd637d458bb4cd99dfe7ad2ee27a88ab | [
"JavaScript"
] | 3 | JavaScript | linhsaarnold/Project3 | 78812534737bc6192149f58653d7d7251be9c72f | f2a4d4c385b8e584a55a93a801955f7378aaa313 | |
refs/heads/master | <file_sep># Abstract Factory Method
Factory patterns are examples of creational patterns.
Class creational patterns focus on the use of inheritance to decide the
object to be instantiated.
# Example

# Intent
* Provide an interface for creating families of related or dependent
objects without specifying their concrete classes.
* The Abstract Factory pattern is very similar to the Factory Method
pattern.One difference between the two is that with the Abstract
Factory pattern, a class delegates the responsibility of object
instantiation to another object via composition whereas the Factory
Method pattern uses inheritance and relies on a subclass to handle the
desired object instantiation
* Actually, the delegated object frequently uses factory methods to
perform the instantiation!
# Participants
* **AbstractFactory**:
Declares an interface for operations that create abstract product objects
* **ConcreteFactory**:
Implements the operations to create concrete product objects Implements the product interfcae
* **AbstractProduct**:
Declares an interface for a type of product object
* **ConcreteCreator**
Defines a product object to be created by the corresponding concrete factor
Implements the AbstractProduct interface
* **Client**
Uses only interface declared by abstractFactory and AbstractProduct classes
# Structure
<file_sep># Command Pattern
an object oriented callback,
Using command as a object gives you lots of opportunities,
you can declare macro command or support undoable operations
# Example

# Intent
* Encapsulate a request as an object, thereby letting you manipulate the
requests in various ways, queue or log requests, support undoable
operations.
# Participants
* **Command**:
Declares an interface for executing an operation.
* **ConcreteCommand**:
Defines a biding between a Receiver object and an action
* **Client**:
creates a ConcreteCommand object and sets its receiver
* **Invoker**
Asks the command to carry out the request
* **Receiver**
Knows how to perform the operations associated with
carrying out a request, anc class may serve as a Receiver
# Structure
<file_sep># Template Method
Define a method in base-super class for an algorithm, and let sub-classes redefine sub-steps.
It is just an method, that performs with the same structure & order & algorithm.
# Example
This example for creating game with GameEngines, the algorithm is same for creating a new project in game engines.

# Intent
* Define the skeleton of an algorithm in an operation, deferring some
steps to subclasses. Template Method lets subclasses redefine certain
steps of an algorithm without changing the algorithm’s structure.
# Problem
Sometimes you want to specify the order of operations that a method
uses, but allow subclasses to provide their own implementations of
some of these operations.
# Structure
<file_sep># Singleton Pattern
# Example

# Intent
* Ensure a class only has one instance, and provide a global point of
access to it.
# Problem
* Sometimes we want just a single instance of a class to exist in the
system.
* A GUI application must have a single mouse.
* An OS must have one window manager.
* An active modem needs one telephone line.
* PC is connected to one keyboard.
* We need to have that one instance easily accessible.
And we want to ensure that additional instances of the class can not
be created.
# Participants
* **Singleton**:
defines a getInstance operation that lets clients access its unique
instance. getInstance is a class operation.
May be responsible for creating its own unique instance.
# Structure
<file_sep># Factory Method
Factory patterns are examples of creational patterns.
Class creational patterns focus on the use of inheritance to decide the
object to be instantiated.
# Example

# Intent
* Define an interface for creating an object, but let subclasses decide
which class to instantiate
# Participants
* **Product**:
Defines the interface for the type of objects the factory method creates
* **ConcreteProduct**:
Implements the product interface
* **Creator**:
Declares the factory method which returns an object of type Product
* **ConcreteCreator**
Overrides the factory method to return an instance of a ConcreteProduct
# Structure
<file_sep># Visitor Pattern
# Example
This example for increasing the employees income and vacation days,
To increase Employee income and vacation days we don't want to change
class representation so that we use **Visitor** pattern,
Firstly, We create **IncomeVisitor** for **changing the income of the employee**
and **VacationVisitor** for **manipulating the vacation days of the employee**

# Intent
* The visitor pattern let you define a new operation for a class/object without
changing the classes representation.
* Do the right thing based on the type of the objects.
* Double dispatch
# Problem
Sometimes you need to add new operations to (interface)node objects but
it needs to know each sub type to performs the operation different in
each object&sub-classes.
Many distinct and unrelated operations would need to be performed on node objects/classes
in a heterogeneous aggregate structure. You dont want to have to query the type of
each node and cast the pointer to correct type before performing the desired operation.
# Participants
**Visitor** : Defins a Visit operation for each class
of **ConcreteElement** in the object structure.
**ConcreteVisitor** : Implements each operation declared by the **Visitor**
**Element** : Defines an accept operation that takes visitor as an argument.
**ConcreteElement** : Implements an accept operation that takes **Visitor** as an argument.
**ObjectStructure** : Can enumerate its elements.
May provide a high-level interface to allow the visitor to visit its
elements.
May either be a composite or a collection such as a list or set.
# Structure
<file_sep># Iterator Pattern(Cursor)
An aggregate object such as a list should allow a way to traverse its
elements without exposing its internal structure.
It should allow different traversal methods.
But, we really do not want to add all these methods to the interface
for the aggregate.
# Example

# Intent
* Provide a way to access the elements of an aggregate object
sequentially without exposing its underlying representation.
* An aggregate object is an object that contains other objects for the
purpose of grouping those objects as a unit. It is also called a
container or a collection. Examples are a linked list and a hash table
# Participants
* **Iterator**
Defines an interface for accessing and traversing elements.
* **ConcreteIterator**
Implements the Iterator interface.
Keeps track of the current position in the traversal.
* **Aggregate**
Defines an interface for creating an Iterator object (a factory method!)
* **ConcreteAggregate**
Implements the Iterator creation interface to return an instance of the
proper ConcreteIterator
# Structure

<file_sep># Facade Pattern
# Example

# Intent
* Provide a unified interface to a set of interfaces in a subsystem.
* Facade defines higher-level interface
that makes the subsystem easier to use,
but the client still has access to subsystem.
# Problem

* Structuring a system into subsystems helps reduce complexity.
* Subsystems are groups of classes, or groups of classes and other
subsystems.
* One way to reduce this complexity is to introduce a facade object that
provides a single, simplified interface to the more general facilities of a
subsystem.
# Participants
* **Facade**:
Knows which subsystem classes are responsible for a request.
Delegates the client requests to appropriate subsystem objects.
* **Subsystem classes**
Implement subsystem functionality.
Handle work assigned by the facade object.
Have no knowledge of the facade; that is they keep no references to it.
# Structure
<file_sep># Composite Pattern
A composite object represents a composition of heterogeneous, possibly
recursive, component objects.
**Problem**: composite object consists of several heterogeneous parts
Client code is complicated by knowledge of object structure.
Client must change if data structure changes.
**Solution**: create a uniform interface for the object’s components
Interface advertises all operations that components offer.
Client deals only with the new uniform interface.
Uniform interface is the union of the components’ services
# Example
Flutter widgets example with transparent version of the Composite pattern.

# Intent
* Compose objects into tree structures to represent part-whole
hierarchies.
* Composite lets clients treat individual objects and compositions of
objects uniformly. This is called recursive composition
# Participants
* **Component**
declares the interface for objects in the composition.
implements default behavior for the interface common to all classes, as
appropriate.
declares an interface for accessing and managing its child components.
* **Leaf**
represents leaf objects in the composition. A leaf has no children.
defines behavior for primitive objects in the composition.
* **Composite**
defines behavior for components having children.
stores child components.
implements child-related operations in the Component interface.
* **Client**
manipulates objects in the composition through the Component
interface.
# Structure


<file_sep># Observer Pattern
# Example
This example about stock's, when stock price change it observers should notify.
In this example
* Stock is our Subject(AbstractSubject)
* IBM is ConcreteSubject
* Observer is AbstractObserver(interface for observables)
* Investor is ConcreteObserver

# Intent
* Define a one-to-many dependency between objects so that
when one object change the state, all its dependents are notified and updated automatically.
# Problem
A large monolithic design does not scale well as new graphing or monitoring requirements are levied.
# Participants
**Subject** :
* Keeps track of its observers (attach,detach)
* Defines an interface for notify its observers.
**Observer** : Defines an interface for update notification.
**ConcreteSubject** :
* The object being observed
* Stores state of interest to ConcreteObserver objects
* Sends a notification to its observers when state change
**ConcreteObserver** :
* The observing object
* Stores state that should stay consistent with the subject’s.
* Implements the Observer update interface to keep its state consistent
with the subject’s
# Structure
<file_sep>## Lecture : SE 311 - Software Architecture (Design Patterns)
In Izmir University of Economics
You can find weekly patterns inside the src folder
<file_sep>package week_06_abstract_factory;
public class SE311_Week06AbstractFactory {
public static void main(String[] args) {
PhoneCreator appleCreator = new AppleCreator();
PhoneCreator samsungCreator = new SamsungCreator();
appleCreator.createPhone();
samsungCreator.createPhone();
}
}
/**
* Abstract Factory
*/
abstract class PhoneCreator {
/**
* Factory Method, let subclasses decide which class to instantiate
*
* @return
*/
abstract Screen createScreen();
/**
* Factory Method, let subclasses decide which class to instantiate
*
* @return
*/
abstract Processor createProcessor();
/**
* This is an Template Method,
* We implement it, base class and we are overriding the steps which are Factory methods in sub-classes.
*/
void createPhone() {
createScreen();
createProcessor();
}
}
class AppleCreator extends PhoneCreator {
@Override
Screen createScreen() {
return new AppleScreen();
}
@Override
Processor createProcessor() {
return new AppleProcessor();
}
}
class SamsungCreator extends PhoneCreator {
@Override
Screen createScreen() {
return new SamsungScreen();
}
@Override
Processor createProcessor() {
return new SamsungProcessor();
}
}
/**
* Product one
*/
interface Processor {
}
class AppleProcessor implements Processor {
AppleProcessor() {
System.out.println("AppleProcessor created!!");
}
}
class SamsungProcessor implements Processor {
SamsungProcessor() {
System.out.println("SamsungProcessor created!!");
}
}
interface Screen {
}
class AppleScreen implements Screen {
AppleScreen() {
System.out.println("AppleScreen created!!");
}
}
class SamsungScreen implements Screen {
SamsungScreen() {
System.out.println("SamsungScreen created!!");
}
}
<file_sep>package week_10_template;
public class SE311_Week10Template {
public static void main(String[] args) {
GameEngine unity = new Unity();
GameEngine unreal = new UnrealEngine();
unity.createNewGame("the-ozon");
unreal.createNewGame("FindIt");
}
}
abstract class GameEngine {
/**
* this is the template method
* it has some steps which is can differ according to gameEngines
* but the steps is generally is same.
* <p>
* We use this method from the base class
*
* @param gameName
*/
public void createNewGame(String gameName) {
startGameEngine();
performCreateGame();
typeGameProjectName(gameName);
completeProcess();
System.out.println("---------------------------------");
}
protected abstract void performCreateGame();
protected abstract void typeGameProjectName(String gameName);
protected abstract void completeProcess();
protected abstract void startGameEngine();
}
class Unity extends GameEngine {
@Override
protected void performCreateGame() {
System.out.println("Unity perform create game build.!");
}
@Override
protected void typeGameProjectName(String gameName) {
System.out.println("Unity perform type name build.! the name is : " + gameName);
}
@Override
protected void completeProcess() {
System.out.println("Unity perform complete process build.!");
System.out.println("Game Created!!!");
}
@Override
protected void startGameEngine() {
System.out.println("Unity start game engine build.!");
}
}
class UnrealEngine extends GameEngine {
@Override
protected void performCreateGame() {
System.out.println("Unreal perform create game build.!");
}
@Override
protected void typeGameProjectName(String gameName) {
System.out.println("Unreal perform type name build.! the name is : " + gameName);
}
@Override
protected void completeProcess() {
System.out.println("Unreal perform complete process build.!");
System.out.println("Game Created!!!");
}
@Override
protected void startGameEngine() {
System.out.println("Unreal start game engine build.!");
}
}<file_sep>package week_04_composite;
import java.util.ArrayList;
import java.util.List;
public class SE311_Week04Composite {
public static void main(String[] args) {
Widget column = new Column();
Widget container = new Container();
Widget text = new Text();
Widget subColumn = new Column();
Widget subContainer = new Container();
Widget subText = new Text();
column.add(container);
column.add(text);
subColumn.add(subContainer);
subColumn.add(subText);
column.add(subColumn);
column.build();
}
}
/**
* This is the Component, Transparent version
*/
interface Widget {
void add(Widget widget);
void remove(Widget widget);
Widget getChild(int index);
void build();
}
/**
* This is the Composite which can have a leaf or composite
*/
class Column implements Widget {
List<Widget> widgets = new ArrayList<>();
@Override
public void add(Widget widget) {
widgets.add(widget);
}
@Override
public void remove(Widget widget) {
widgets.remove(widget);
}
@Override
public Widget getChild(int index) {
return widgets.get(index);
}
@Override
public void build() {
System.out.println("----------");
for (int i = 0; i < widgets.size(); i++) {
getChild(i).build();
}
}
}
class Container implements Widget {
@Override
public void add(Widget widget) {
throw new UnsupportedOperationException();
}
@Override
public void remove(Widget widget) {
throw new UnsupportedOperationException();
}
@Override
public Widget getChild(int index) {
throw new UnsupportedOperationException();
}
@Override
public void build() {
System.out.println("Container Build!!");
}
}
class Text implements Widget {
@Override
public void add(Widget widget) {
throw new UnsupportedOperationException();
}
@Override
public void remove(Widget widget) {
throw new UnsupportedOperationException();
}
@Override
public Widget getChild(int index) {
throw new UnsupportedOperationException();
}
@Override
public void build() {
System.out.println("Text Build!!");
}
}
<file_sep># Adapter Pattern (Wrapper)
# Example
This example for creating game with GameEngines, the algorithm is same for creating a new project in game engines.

# Intent
* Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that could not otherwise because of incompatible interfaces.
# Problem
* Sometimes a toolkit or class library can not be used because its
interface is incompatible with the interface required by an application.
* We can not change the library interface, since we may not have its
source code.
* Even if we did have the source code, we probably should not change
the library for each domain-specific application
# Participants
* **Target**:
Defines the domain-specific interface that Client uses
* **Adapter**:
Adapts the interface of Adaptee to the Target interface
* **Client**
Colloborates with objects conforming to the Target interface
* **Adaptee**:
Defines an existing interface that needs adapting
# Structure

 | 63f6530400ae6a6b1f77861f4945e123b973b482 | [
"Markdown",
"Java"
] | 15 | Markdown | onatcipli/DesignPatternsJava | 181ab26d5760b65ff6698afa29e951180aefaa4d | 8a2e66adf245db402aa01ed903e26638fd70b6d7 | |
refs/heads/master | <repo_name>Dips97/Udacity-Landing-page<file_sep>/js/app.js
//creating variable for navigation list
const MyNav = document.querySelector("#navbar__list");
//creating variables to store all section data and global use
const mySections = document.querySelectorAll("section");
//empty variable to store list elements
let navItems = "";
//looping through sections using for loop and storing the values in upper empty variable
for (let item of mySections) {
const sectionData = item.dataset.nav;
const sectionIds = item.id;
navItems += `<li><a class="menu__link" href="#${sectionIds}">${sectionData}</a></li>`;
}
//adding list items(li) to the (ul) tag
MyNav.innerHTML = navItems;
//getting the largest value that's less or equal to the top of viewport
const elementOffset = (section) => {
return Math.floor(section.getBoundingClientRect().top);
};
//'active' class remove function
const activeClassremover = (section) => {
section.classList.remove("your-active-class");
};
//'active' class add function
const activeClassAdd = (conditional, section) => {
if (conditional) {
section.classList.add("your-active-class");
}
};
//implementing the 'active' status in the section using for..of loop
function activeSection() {
for (let items of mySections) {
const elementsOffset = elementOffset(items);
AddClasscondition = () => elementsOffset < 130 && elementsOffset >= -130;
activeClassremover(items);
activeClassAdd(AddClasscondition(), items);
}
}
//adding the 'active' class scroll event listener
window.addEventListener("scroll", activeSection);
/* Jump to Top button */
const TopBtn = document.getElementById("myBtn");
//calling the function on user Scroll
window.onscroll = function () {
scrollingFunction();
};
function scrollingFunction() {
if (document.body.scrollTop > 30 || document.documentElement.scrollTop > 30) {
TopBtn.style.display = "block";
} else {
TopBtn.style.display = "none";
}
}
// page go up when user click on button with smooth behavior
function topFunction() {
document.documentElement.scrollIntoView({ behavior: "smooth" });
}
// Scroll to sections
function scrollToAnchor() {
MyNav.addEventListener("click", function (e) {
e.preventDefault();
const linkClick = document.querySelector(e.target.getAttribute("href"));
linkClick.scrollIntoView({ behavior: "smooth" });
});
}
// calling scroll function
scrollToAnchor();
<file_sep>/README.md
# Udacity Landing Page
This is the project made by me in the learning process of Front End Developer
## Specification
- This project is made of HTML, CSS and JavaScript
- HTML and CSS files are provided by udacity.
- JavaScript functions are created by me.
- This project has a dynamic navigation page.
- When you click on any section it will scroll to that particular section.
- The page's sections are active. | 6b84296a2dcddf4f8faa311af55119871013e8b6 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Dips97/Udacity-Landing-page | e33da0743f0c0c132749b46d3ecd06b136dc8ec2 | 7914d19bc26229fd904fd6cbf577137887e65dd4 | |
refs/heads/master | <file_sep>start_image_filename = 'start.png'
back_image_filename = 'bg.jpg'
block_image_filename = 'pipe.png'
bird_image_filename = 'bird.png'
title_image_filename = 'main.png'
ready_image_filename = 'ready.png'
over_image_filename = 'over.png'
fly_music_filename = 'fly.wav'
dead_music_filename = 'dead.wav'
jump_music_filename = 'jump.wav'
ready_music_filename = 'ready.wav'
coin_music_filename = 'coin.wav'
over_music_filename = 'over.wav'
import pygame
from pygame.locals import *
from gameobjects.vector2 import *
import random
import math
SCREEN_SIZE = (378,537)#屏幕分辨率
run1 = 0#全局变量
run2 = 0
over = 0
def load_image(file, width, number):#用于载入子图
surface = pygame.image.load(file).convert_alpha()
height = surface.get_height()
return [surface.subsurface(
Rect((i * width, 0), (width, height))
) for i in range(number)]
class Object(object):#实体类
def __init__(self,name,position):
self.name = name
self.position = Vector2(*position)
self.speed = 0
class Fish(pygame.sprite.Sprite):#精灵类
images = []
def __init__(self,r):#初始化
self.order = 0#图片序列号
self.rate = 0.2#更新速率0.2秒
self.height = 60#图片高度
self.number = 3#图片数量
self.position = Vector2(189,269)#位置
self.r = r#碰撞半径
self.speed = 0#速度
pygame.sprite.Sprite.__init__(self)
self.images = load_image(bird_image_filename,80, 3)#载图
self.image = self.images[self.order]#判断是哪个贴图
#self.rect = Rect(0, 0, self.width, self.height)
#self.life = self._life
self.passed_time = 0#根据时间判断
def update(self, passed_time):#更新图片
self.passed_time += passed_time
self.order = ( self.passed_time / self.rate ) % self.number
if self.order == 0 and self.passed_time > self.rate:
self.passed_time = 0
self.image = self.images[int(self.order)]
def render(self,screen):#其实精灵类有自己的blit方法,这里写的不好
x,y = self.position
x -= 40
y -= 30
screen.blit(self.image,(int(x),int(y)))
class Block(Object):#管道类,最一开始用方块实现的,所以叫BLOCK
def __init__(self,name,position,ID,image):
Object.__init__(self,name,position)
self.ran = random.randint(0,200)#随机值用于开口位置
self.ID = ID#用于标记这是第几个管道,方便统计分数
self.image = image#图片
def render(self,screen):#绘制
x,y = self.position
screen.blit(self.image,(x,250+self.ran))#画下方管道
screen.blit(self.image,(x,self.ran-353))#画上方管道
class Button(object):#按钮类
def __init__(self , position,image):
self.position = position
self.image = image
def render(self, screen):
x, y = self.position
w, h = self.image.get_size()
screen.blit(self.image, (x-w/2, y-h/2))
def is_over(self, point):#判断鼠标是否在按钮上
if (SCREEN_SIZE[0]-self.image.get_size()[0])/2 < point[0]<(SCREEN_SIZE[0]+self.image.get_size()[0])/2:
if (SCREEN_SIZE[1]-self.image.get_size()[1])/2 < point[1]<(SCREEN_SIZE[1]+self.image.get_size()[1])/2:
return True
def start():#开始界面
buttons = {}
pygame.mixer.pre_init(44100, 16, 2, 1024*4)
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE,0,32)#设置窗口
start_image = pygame.image.load(start_image_filename).convert_alpha()
title_image = pygame.image.load(title_image_filename).convert_alpha()
ready_image = pygame.image.load(ready_image_filename).convert_alpha()
bg_image = pygame.image.load(back_image_filename).convert()
buttons["start"] = Button((189,269),start_image)#开始按钮位置
x,y = title_image.get_size()
pygame.mixer.music.load(ready_music_filename)
pygame.mixer.music.play()
while True:
#if pygame.mixer.music.get_busy()== 1 :
#pygame.mixer.music.rewind()
if pygame.mixer.music.get_busy()==0:
pygame.mixer.music.play()
button_pressed = None#初始化按钮
buttons["start"]
screen.blit(bg_image, (0,0))
screen.blit(title_image,(SCREEN_SIZE[0]/2-x/2,100+y/2))
for button in buttons.values():#绘制所有按钮
button.render(screen)
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == MOUSEBUTTONDOWN :#如果鼠标按下
for button_name, button in buttons.items():
if button.is_over(event.pos):
button_pressed = button_name
break
if button_pressed is not None:
if button_pressed == "start":#如果按得是开始按钮
screen.blit(bg_image, (0,0))#准备画面
screen.blit(ready_image,(0,0))
pygame.display.update()
pygame.time.wait(2000)#停2S
pygame.mixer.music.stop()
run()#开始
def dead(block1,block2,fish):#如果dead
pygame.mixer.music.stop()
dead_sound = pygame.mixer.Sound(dead_music_filename)
dead_sound.play()
block1.speed = 0#管道静止
block2.speed = 0
global run1
global run2
global over
run1 = 1#防止游戏接着跑
run2 = 1
over = 1
pygame.time.wait(1000)#等一秒
fish.speed = -35#bird向上跳
pygame.event.set_blocked(KEYDOWN)#阻止键盘操作
def game_over(ID):
pygame.mixer.pre_init(44100, 16, 2, 1024*4)
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE,0,32)#设置窗口
bg_image = pygame.image.load(back_image_filename).convert()
over_sound = pygame.mixer.Sound(over_music_filename)
over_image = pygame.image.load(over_image_filename).convert_alpha()
over_sound.play()
pygame.event.set_allowed(KEYDOWN)#允许按键
x,y = over_image.get_size()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
if event.key == K_SPACE:
over_sound.stop()
start()
screen.blit(bg_image,(0,0))
screen.blit(over_image,(SCREEN_SIZE[0]/2-x/2,100+y/2))
pygame.display.update()
#print (ID)
score = ID - 1
def run():
pygame.mixer.pre_init(44100, 16, 2, 1024*4)
pygame.init()#初始化
screen = pygame.display.set_mode(SCREEN_SIZE,0,32)#窗口
bg_image = pygame.image.load(back_image_filename).convert()
block_image = pygame.image.load(block_image_filename).convert_alpha()
r = 15#bird半径
font = pygame.font.SysFont("arial",32)#字体
fish = Fish(r)#bird
block1 = Block("Block1",(378.,0.),1,block_image)#管道1
block2 = Block("Block2",(378.,0.),0,block_image)#管道2
flag1 = 0#计数标志位
flag2 = 0
global run1
global run2
global over
run1 = 0#运行标志位
run2 = 0
over = 0#结束标志位,为1则结束
clock = pygame.time.Clock()#引入时钟
point_text = "0"#初始化分数
ID = 1#初始化方块ID
bgx,bgy = bg_image.get_size()
x = bgx/2
y = bgy/2
width = 70
pygame.mixer.music.load(fly_music_filename)
jump_sound = pygame.mixer.Sound(jump_music_filename)
coin_sound = pygame.mixer.Sound(coin_music_filename)
pygame.mixer.music.play()
if pygame.mixer.music.get_busy() == 0:
pygame.mixer.music.play()
while True:
screen.blit(bg_image, (0,0))
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:#空格就获得向上的速度
if event.key == K_SPACE:
jump_sound.stop()
jump_sound.play()
fish.speed = -6
passed_time = clock.tick(80)/1000#80fps
fish.speed += passed_time * 25#小球的加速度
fish.position += (0,fish.speed)#计算小球位置
if over!=1:
block1.speed = passed_time * 160#方块的速度
block1.position[0] -= block1.speed#方块的位置
block2.position[0] -= block2.speed
block1.render(screen)#绘制
block2.render(screen)
if fish.speed < 0:
fish.update(passed_time)#鸟在上飞过程才扇翅膀
else:
fish.image = fish.images[0]#下降过程图片静止
fish.render(screen)
screen.blit(font.render(point_text,True,(0,0,0)),(189,50))#打印分数
pygame.display.update()#update
if fish.position[1] - r< 0:#到达顶方的碰撞
fish.position[1] = r
fish.speed = 0
if over == 0:
if fish.position[1] + r > 537:#到达最下方
dead(block1,block2,fish)#dead
fish.position -= (0,30)#防止直接退出
elif fish.position[1] > 580:#掉下以后
pygame.time.wait(1000)#等一秒退出
game_over(ID)
if block1.position[0] < 189 - width - r and flag1 == 0 :#当一个方块x到一定值时另一个方块准备就绪
block2.position[0] = bgx
block2.speed = 0
block2.ran = random.randint(0,200)
ID+=1
block2.ID = ID
flag1 = 1
flag2 = 0
if block2.position[0] < 189 - width - r and flag2 == 0 :
block1.position[0] = bgx
block1.speed = 0
block1.ran = random.randint(0,200)
ID+=1
block1.ID = ID
flag2 = 1
flag1 = 0
if block1.position[0] < 40 and run1 == 0:#当一个方块左移到40时,另一个方块获得速度
block2.speed = block1.speed
run1 = 1
run2 = 0
if block2.position[0] < 40 and run2 == 0:
block1.speed = block2.speed
run2 = 1
run1 = 0
if over!=1:
if x - width - r <= block1.position[0] <= x + r :#判定碰撞
if x < block1.position[0] <= x + r and (math.sqrt(r**2 - (block1.position[0]-x)**2)+100+block1.ran > fish.position[1] or (math.sqrt(r**2 - (block1.position[0]-x)**2))>250+block1.ran - fish.position[1]):
dead(block1,block2,fish)
if x - width <= block1.position[0] <= x and (fish.position[1] < block1.ran + 100 + r or fish.position[1] > 250 - r + block1.ran):
dead(block1,block2,fish)
if x - width - r <= block1.position[0] < x - width and (math.sqrt(r**2 - (block1.position[0]-(x-width-r))**2)+100+block1.ran > fish.position[1] or (math.sqrt(r**2 - (block1.position[0]-(x-width-r))**2))>250+block1.ran- fish.position[1]):
dead(block1,block2,fish)
if x - width - r <= block2.position[0] <= x + r :#判定碰撞
if x < block2.position[0] <= x + r and (math.sqrt(r**2 - (block2.position[0]-x)**2)+100+block2.ran > fish.position[1] or (math.sqrt(r**2 - (block2.position[0]-x)**2))>250+block2.ran - fish.position[1]):
dead(block1,block2,fish)
if x - width <= block2.position[0] <= x and (fish.position[1] < block2.ran + 100 + r or fish.position[1] > 250 - r + block2.ran):
dead(block1,block2,fish)
if x - width - r <= block2.position[0] < x - width and (math.sqrt(r**2 - (block2.position[0]-(x-width-r))**2)+100+block2.ran > fish.position[1] or (math.sqrt(r**2 - (block2.position[0]-(x-width-r))**2))>250+block2.ran - fish.position[1]):
dead(block1,block2,fish)
old_point = point_text
point_text = str(min (block1.ID,block2.ID))#获得当前分数
if old_point != point_text:
coin_sound.play()
if __name__ == "__main__":
start()
<file_sep>import pygame
from pygame.locals import *
SCREEN_SIZE = (200,200)
def load_image(file, width, number):
surface = pygame.image.load(file).convert_alpha()
height = surface.get_height()
return [surface.subsurface(
Rect((i * width, 0), (width, height))
) for i in range(number)]
class fish(pygame.sprite.Sprite):
#_life = 100
images = []
def __init__(self):
self.order = 0
self.rate = 200
self.height = 60
self.number = 3
pygame.sprite.Sprite.__init__(self)
self.images = load_image("bird.png",80, 3)
self.image = self.images[self.order]
#self.rect = Rect(0, 0, self.width, self.height)
#self.life = self._life
self.passed_time = 0
def update(self, passed_time):
self.passed_time += passed_time
self.order = ( self.passed_time / self.rate ) % self.number
if self.order == 0 and self.passed_time > self.rate:
self.passed_time = 0
self.image = self.images[int(self.order)]
def render(self,screen):
screen.blit(self.image,(0,0))
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE,0,32)#窗口
Fish = fish()
clock = pygame.time.Clock()
while True:
#screen = pygame.display.set_mode(SCREEN_SIZE,0,32)#窗口
passed_time = clock.tick(100)
print (passed_time)
Fish.update(passed_time)
screen.fill((0,0,0))
#Fish.render(screen)
#Fish.order = 1
#Fish.render(screen)
Fish.order = 2
Fish.render(screen)
for event in pygame.event.get():
if event.type == QUIT:
exit()
pygame.display.update()
<file_sep>Python3.3编写的
另外需要gameobject 和 pygame模块,游戏开发必备
gameobject貌似不支持python3,所以我修改了vector里面部分代码
| 808ca9c892cf9750c16736ad1dc3f81de89ffe71 | [
"Python",
"Text"
] | 3 | Python | Leo1973/flappyfish | 619cdfcfdbefb10332478cbd0b6283edddd69e7b | 70db2500c11b9c4a8b22f0f7c720aaa1f135846d | |
refs/heads/master | <file_sep><?php
include '/var/www/db_params.php';
$dv_id = array();
$dv_id_second=array();
$dv_time_on=array();
$dv_time_on_second=array();
$empty="";
$done=0;
//while(1){
if(date("d")==1 && $done==0){
//if(date("G")==17 && date("i")==26 && date("s")==1){
$done=1;
$conn = new mysqli($host, $username, $password, $dbname); //vruzka kum db
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if($stmt = $conn->prepare("DELETE FROM months_consumption"));
$stmt->execute();
if($stmt = $conn->prepare("SELECT id,id_second,time_on,time_on_second FROM devices WHERE id_second<>?")){//izbiram vsichko ot devices za da zapisha v druga tablica
$stmt->bind_param("i",$empty);
$stmt->execute();
$stmt->bind_result($col_id,$col_id_second,$col_time_on,$col_time_second);
$n=0;
while ($stmt->fetch()) {//poluchavane na otgovor i podrejdane v masivi
$dv_id[$n]=$col_id;
$dv_id_second[$n]=$col_id_second;
$dv_time_on[$n]=$col_time_on;
$dv_time_on_second[$n]=$col_time_second;
$n++;
}
//$stmt->close();
//$conn->close();
}
if(!empty($dv_id)){
for($r=0;$r<=count($dv_id)-1;$r++){
if($stmt = $conn->prepare("INSERT INTO months_consumption (id_hs, id_second_hs,time_on,time_on_second) VALUES (?, ?, ?,?)")){ //zapisvam jivite danniti koito ustroistvoto e izpratilo
$stmt->bind_param("iiii", $dv_id[$r], $dv_id_second[$r],$dv_time_on[$r],$dv_time_on_second[$r]);
$stmt->execute();
$stmt->close();
}
}
if($stmt = $conn->prepare("UPDATE devices SET time_on=?,time_on_second=?")){//updeitvam vremeto i vatovete
$stmt->bind_param("ii", $empty,$empty);
$stmt->execute();
}
$conn->close();
}
//}
}
else if(date("d")!=1)
$done=0;
//}
?><file_sep>var valid_name=0;
var jsonURL = [];
var patt = new RegExp(/^[a-z0-9]+$/i);
var name = document.getElementById("name");
var button=document.getElementById("send");
function check_name(){
var name = document.getElementById("name");
var status =document.getElementById("status");
if(name.value.length<3){
name.style.border = "solid #ff4d4d";
status.innerHTML="Името е твърде късо!";
}
else if (name.value.length>40){
name.style.border = "solid #ff4d4d";
status.innerHTML="Името е твърде дълго!";
}
else if (!patt.test(name.value)){
name.style.border = "solid #ff4d4d";
status.innerHTML="Името съдържа забранени знаци!";
}
else{
name.style.border = "solid #4dff4d";
status.innerHTML="";
valid_name=1;
}
}
function send(){
var name = document.getElementById("name");
var pass = document.getElementById("pass");
var status =document.getElementById("status");
if(valid_name==1){
var oreg = new XMLHttpRequest();
oreg.onreadystatechange = function() {
if (oreg.readyState == 4 && oreg.status == 200) { //poluchavam otgovor za tova kakvo deistvie e izvursheno
jsonURL = JSON.parse(oreg.responseText);
var msg=jsonURL[0].msg1+"<br>"+jsonURL[0].msg2;
status.innerHTML=msg;
if(jsonURL[0].url!="")
window.location=jsonURL[0].url;
switch(jsonURL[0].stat) {
case 0:
pass.style.border="solid #4dff4d";
name.style.border="solid #4dff4d";
break;
case 1:
pass.style.border="<PASSWORD>";
name.style.border="solid #ff4d4d";
break;
}
return false;
}
};
oreg.open("post", "user_login.php", true);
oreg.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
oreg.send("name="+name.value+"&pass="+pass.value);
}
else
name.style.border="solid #ff4d4d";
}
document.getElementById("name").addEventListener("keyup", check_name);
button.addEventListener('click', send);<file_sep><?php
session_start();
include '/var/www/db_params.php';
$id=$_GET["id"];
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$devices = array(
0 => "SELECT time_start,time_on,last_wats FROM devices WHERE id=?",
1 => "SELECT time_start_second,time_on_second,last_wats_second FROM devices WHERE id_second=?");
$history = array(
0 => "SELECT time_on FROM months_consumption WHERE id_hs=?",
1 => "SELECT time_on_second FROM months_consumption WHERE id_second_hs=?");
for($i=0;$i<=1;$i++){
if($stmt = $conn->prepare($devices[$i])){
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($col_dv_time_start,$col1_dv_time_on,$col2_dv_last_wats);
$stmt->fetch();
$stmt->close();
}
}
for($i=0;$i<=1;$i++){
if($stmt = $conn->prepare($history[$i])){
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($mn_time_on);
$stmt->fetch();
$stmt->close();
}
}
$array=array(
'time_start' => $col_dv_time_start, //slagam gi v masiv
'time_on' => $col1_dv_time_on,
'last_wats' => $col2_dv_last_wats,
'history' => $mn_time_on
);
$return[]=$array;
echo json_encode($return); //encodvam i prashtam
$conn->close();
?><file_sep><?php
session_start();
include '/var/www/db_params.php';
if(isset($_POST["q"],$_POST["status"],$_POST["last_wats"])){
if(!empty($_POST["q"] && !empty($_POST["status"]) && !empty($_POST["last_wats"]))){
$in_id=$_POST["q"];
$status=$_POST["status"];
$last_wats=$_POST["last_wats"];
}
}
elseif(isset($_POST["in_type"]) && !empty($_POST["in_type"])){
$in_type=$_POST["in_type"];
if($in_type=="mouse"){
$datax=$_POST["datax"];
$datay=$_POST["datay"];
$command=$datax."&".$datay;
}
else if($in_type=="key"){
$command=$_POST["command"];
}
else if($in_type=="mouse_click"){
$command=$_POST["command"];
}
$variable = array( 'type' => "$in_type",
'command' => "$command" );
$msg=json_encode($variable);
}
if(isset($_SESSION["logged"])){
$conn = new mysqli($host, $username, $password, $dbname);
if(isset($_POST["q"])){
if($stmt = $conn->prepare("SELECT ip,port,id_second,time_on,time_start,label FROM devices WHERE id=(?)")){ //vziamm informaciq ot sct1-kontakt purvi
$stmt->bind_param("i", $in_id);
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4,$col5,$col6);
$stmt->fetch();
$stmt->close();
}
if(($col1==0)&&($col3==0)){ //SCT nomer 2
$stmt = $conn->prepare("SELECT ip,port,time_on_second,time_start_second,label1 FROM devices WHERE id_second=(?)"); //izbiram vsichko ot sct nomer 2
$stmt->bind_param("i", $in_id);
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4,$col5);
$stmt->fetch();
$stmt->close();
$msg=2;
if($status!="true"){ //status false
$time_cmp = date("H:i"); //segashno vreme
$currentTime = strtotime($time_cmp);
$formatTime2= date("H:i", $currentTime); //tekusht chas
$time_total= (strtotime($formatTime2) - strtotime($col4))/60; //razlika vuvu vremeto
//$time_h=floor($time_h);
//$time_m=$time_h%60;
//$time_h=($time_h-$time_m)/60;
//$time_total=$time_h.":".$time_m;
//$time_ac=$formatTime2-$col4; //izminato vreme
if($col5!="")
$time_total=$time_total+$col3;
else
$time_total="";
$formatTime="";
}
else{ //status true
$time_cmp = date("H:i");
$currentTime = strtotime($time_cmp);
$formatTime= date("H:i", $currentTime);
$time_total=$col3;
}
$stmt = $conn->prepare("UPDATE devices SET time_start_second=?, time_on_second=?, last_wats_second=? WHERE id_second=?"); //updeitvam vremeto i vatovete
$stmt->bind_param("sisi", $formatTime,$time_total,$last_wats,$in_id);
$stmt->execute();
$stmt->close();
}//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
else{
$msg = 1;
if($status!="true"){
$time_cmp = date("H:i");
$currentTime = strtotime($time_cmp);
$formatTime2= date("H:i", $currentTime); //tekusht chas
$time_total= (strtotime($formatTime2) - strtotime($col5))/60;
if($col6!="")
$time_total=$time_total+$col4;
else
$time_total="";
$formatTime="";
}
else{
$time_cmp = date("H:i");
$currentTime = strtotime($time_cmp);
$formatTime= date("H:i", $currentTime);
$time_total=$col4;
}
if($col3!=0){
$stmt = $conn->prepare("UPDATE devices SET time_start=?, time_on=?, last_wats=? WHERE id=?");
$stmt->bind_param("sisi", $formatTime,$time_total,$last_wats,$in_id);
$stmt->execute();
$stmt->close();
}
}
$conn->close();
}
else{
if($stmt = $conn->prepare("SELECT pc_ip,pc_port FROM settings")){ //vziamm informaciq ot sct1-kontakt purvi
$stmt->execute();
$stmt->bind_result($col1,$col2);
$stmt->fetch();
$stmt->close();
}
}
$len = strlen($msg);
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_sendto($socket, $msg, $len, 0, $col1, $col2);
}
?><file_sep><?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_SESSION["logged"])){ //proverqvam dali sum lognat
function touch_pad(){ //touch pad za upravlenie na pc
echo <<<EOT
<div class="row">
<div class="small-12 columns">
<div class="panel">
<div id="kb-buttons" class="pc-buttons buttons-container">
<div id="esc">ESC</div>
<div id="left" class="fi-arrow-left"></div>
<div id="up" class="fi-arrow-up"></div>
<div id="down" class="fi-arrow-down"></div>
<div id="right" class="fi-arrow-right"></div>
<div id="enter" >ENTER</div>
<div id="vdown" class="fi-volume-none"></div>
<div id="mute" class="fi-volume-strike"></div>
<div id="vup" class="fi-volume"></div>
<div id="space" >SPACE</div>
<div id="f" class="fi-arrows-out"></div>
<div id="exit" class="fi-x"></div>
</div>
<div class="row">
<div class="small-12 columns">
<div id="panel" class="touch_area"></div>
</div>
</div>
<div class="row">
<div id="mouse_buttons">
<div class="small-6 columns" style="padding-right: 0px;">
<div id="left_mouse" class="left_button" ></div>
</div>
<div class="small-6 columns" style="padding-left: 0px;">
<div id="right_mouse" class="right_button"></div>
</div>
</div>
</div>
</div>
</div>
<div id=testing></div>
</div>
EOT;
}
function sct_btn(&$sct_id ,&$sct_id_second,$br_sct){ //zarejdane na kontaktite s id-ta i imena
for($q=0;$q<=$br_sct-1;$q++){
echo <<<EOT
<div class="row">
<div class="small-6 columns">
<div class="panel">
<input type="text" class="wet_asphalt btn_stl" id="lb-$sct_id[$q]" maxlength="10" placeholder="Бутон" onfocusout="label_save(this)" />
<div class="switch round large" >
<input id="$sct_id[$q]" type='checkbox' onchange='UDP_send(this)'>
<label for="$sct_id[$q]" style='margin: 0 auto; display: block;'></label>
</div>
<hr style="padding:0 0 0.5rem; margin:0;">
<div class="row">
<div class="small-6 columns">
<div class="inf-w" id="info-$sct_id[$q]"></div>
</div>
<div class="small-6 columns">
<i data-reveal-id="tbModal" class="fi-info info-tb" id="info-tb-$sct_id[$q]" onclick="resp_hand(1,this)"></i>
</div>
</div>
</div>
</div>
<div class="small-6 columns">
<div class="panel">
<input type="text" class="wet_asphalt btn_stl" id="sub-lb-$sct_id[$q]" maxlength="10" placeholder="Бутон" onfocusout="label_save(this)"/>
<div class="switch round large">
<input id="$sct_id_second[$q]" type="checkbox" onchange="UDP_send(this)">
<label for="$sct_id_second[$q]" style="margin: 0 auto; display: block;" ></label>
</div>
<hr style="padding:0 0 0.5rem; margin:0;">
<div class="row">
<div class="small-6 columns">
<div class="inf-w" id="info-$sct_id_second[$q]" ></div>
</div>
<div class="small-6 columns">
<i data-reveal-id="tbModal" class="fi-info info-tb" id="info-tb-$sct_id_second[$q]" onclick="resp_hand(1,this)"></i>
</div>
</div>
</div>
</div>
</div>
EOT;
}
}
function lc_btn(&$lc_id,$br){ //zarejdane na kliuchovete za lampi s id-ta i nomera
$tr=0;
$br_lc=intval($br/2);
$br_second_lc=$br%2;
if($br_lc>0){
$br_lo=$br_lc-1;
$br_li=1;
$columns=6;
}
else if($br_second_lc==1){
$br_lo=0;
$br_li=0;
$columns=12;
}
else{
$br_lo=-2;
$br_li=-2;
}
for($q=0;$q<=$br_lo;$q++){
echo "<div class='row'>";
for($i=0;$i<=$br_li;$i++){
if($q>0)
$v=$i+2*$q;
else
if($tr==1)
$v=$br-1;
else
$v=$i;
echo "<div class='small-$columns columns'>";
echo <<<EOT
<div class="panel">
<input type='text' class="midnight_blue btn_stl" id="lb-$lc_id[$v]" maxlength='10' placeholder='Бутон' onfocusout="label_save(this)"/>
<div class="switch round large" >
<input id=$lc_id[$v] type = 'checkbox' onchange='UDP_send(this)'>
<label for=$lc_id[$v] style='margin: 0 auto; display: block;'></label>
</div>
</div>
</div>
EOT;
}
echo "</div>";
if(($br_second_lc==1)&&($q==$br_lo)){
if($br_lc==0)
$br_lo=-1;
else
$br_lo=0;
$br_li=0;
$columns=12;
$br_second_lc=0;
$tr=1;
$v=$v+1;
$q=-1;
}
}
}
function video_panel(&$cam_ip,&$cam_label,&$cam_port,&$cam_id,$cam_br){ //video panel za kamerite
// echo <<<EOT
// <div class="row">
// <div class="small-12 columns">
// <ul class="example-orbit" data-orbit>
// <li>
// <img src="../assets/img/examples/satelite-orbit.jpg" alt="slide 1" />
// <div class="orbit-caption">
// Caption One.
// </div>
// </li>
// <li class="active">
// <img src="../assets/img/examples/andromeda-orbit.jpg" alt="slide 2" />
// <div class="orbit-caption">
// Caption Two.
// </div>
// </li>
// <li>
// <img src="../assets/img/examples/launch-orbit.jpg" alt="slide 3" />
// <div class="orbit-caption">
// Caption Three.
// </div>
// </li>
// </ul>
// </div>
// </div>
// EOT;
// <div class="video-panel">
// <ul class="example-orbit" data-orbit>
// <li>
// <div class="orbit-caption">дз</div>
// </li>
echo <<<EOT
EOT;
for($t=0;$t<=$cam_br-1;$t++){
$slide=$t+1;
$stream="http://".$cam_ip[$t].":".$cam_port[$t]."/video";
echo <<<EOT
<div class="medium-12 columns">
<div class="row">
<div class="panel">
<img id="cam_$cam_id[$t]" src="$stream"/>
<div id="cam_title">$cam_label[$t]</div>
</div>
</div>
</div>
EOT;
}
if($cam_br==0)
echo "<h3 class='midnight_blue'>Няма охранителни камери</h3>";
}
function led_panel(){ //budeshta funkciq
echo <<<EOT
<div class="row">
<div class="small-12 columns">
<div class="led-panel">
<div class="row">
<div class="small-8 columns">
<label class="midnight_blue">ЛЕД осветление</label>
</div>
<div class="small-2 small-offset-2 columns">
<span id="sliderOutput3" ></span><span class="midnight_blue">%</span>
</div>
</div>
<div class="row">
<div class="small-12 medium-12 columns">
<div id="slider" class="range-slider round" data-slider data-options="display_selector: #sliderOutput3; step:2;">
<span id="switch" class="range-slider-handle" ontouchstart="doTimer()"></span>
<span class="range-slider-active-segment"></span>
<input type="hidden">
</div>
</div>
</div>
<div class="row">
<div class="silver medium">
<div class="small-2 medium-2 columns " ontouchend="iconLock()">
<div class="right">
<i id="icon" class="fi-unlock"></i>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
EOT;
}
}
?><file_sep><?php
session_start();
include '/var/www/db_params.php';
if(isset($_GET['day_price']))
$day_price=$_GET["day_price"]; //vzimam informaciq za centa
if(isset($_SESSION["logged"])){
$conn = new mysqli($host, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO electricity_price (day_price) VALUES (?) ON DUPLICATE KEY UPDATE day_price=?"); //zpisvam q v db
$stmt->bind_param("ss", $day_price,$day_price);
$stmt->execute();
$stmt->close();
$conn->close();
}
?>
<file_sep><?php
session_start();
include '/var/www/db_params.php';
if(isset($_GET['dvs_id'])){
$label=$_GET["label"];
$second_label=$_GET["label1"];
$id=$_GET["dvs_id"];
}
if(isset($_SESSION["logged"])){
$conn = new mysqli($host, $username, $password, $dbname);
if($label==""){
$stmt = $conn->prepare("UPDATE devices SET label1=(?) WHERE id=(?)"); //zapisvam label ot sct1 ili LC
$stmt->bind_param("si", $second_label,$id);
$stmt->execute();
}
else{
$stmt = $conn->prepare("UPDATE devices SET label=(?) WHERE id=(?)");//zapisvam label ot SCT2
$stmt->bind_param("si", $label,$id);
$stmt->execute();
}
$stmt->close();
$conn->close();
}
?><file_sep>#библиотеки нужни за програмата
import socket
import ctypes
from ctypes import windll, Structure, c_ulong, byref
import time
import os
import sys
import json
import re
from win32api import * #api за ос
SendInput = ctypes.windll.user32.SendInput # Начало на инициализация на ctypes библиотеката
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
_fields_ = [("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class HardwareInput(ctypes.Structure):
_fields_ = [("uMsg", ctypes.c_ulong),
("wParamL", ctypes.c_short),
("wParamH", ctypes.c_ushort)]
class MouseInput(ctypes.Structure):
_fields_ = [("dx", ctypes.c_long),
("dy", ctypes.c_long),
("mouseData", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("time",ctypes.c_ulong),
("dwExtraInfo", PUL)]
class Input_I(ctypes.Union):
_fields_ = [("ki", KeyBdInput),
("mi", MouseInput),
("hi", HardwareInput)]
class Input(ctypes.Structure):
_fields_ = [("type", ctypes.c_ulong),
("ii", Input_I)]
def PressKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( hexKeyCode, 0x48, 0, 0, ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def ReleaseKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( hexKeyCode, 0x48, 0x0002, 0, ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
SendInput(1, ctypes.pointer(x), ctypes.sizeof(x)) #<Край
class POINT(Structure):
_fields_ = [("x", c_ulong), ("y", c_ulong)]
try:
with open('config.txt') as data_file:
data = json.load(data_file)
except:
ctypes.windll.user32.MessageBoxW(0,"Липсва конфигурационен файл!", "Данни за свързване", 0)
sys.exit()
x_old=0
y_old=0
conf_port=data["settings"]["port"]
conf_mouse_x=data["settings"]["mouse_sens_x"]
conf_mouse_y=data["settings"]["mouse_sens_y"]
conf_mouse_x=re.sub(r'[^\d]+','',conf_mouse_x)
conf_mouse_y=re.sub(r'[^\d]+','',conf_mouse_y)
conf_port=re.sub(r'[^\d]+','',conf_port)
conf_port=int(conf_port)
conf_mouse_x=int(conf_mouse_x)
conf_mouse_y=int(conf_mouse_y)
UDP_IP = socket.gethostbyname(socket.getfqdn()) #адрес на хост-а
if conf_port !=0 and conf_port <= 65535 and conf_port>0:
UDP_PORT = conf_port #Порт
ctypes.windll.user32.MessageBoxW(0,"Адрес:"+UDP_IP+'\n'
+"Порт:"+str(UDP_PORT)+'\n'
+"X офсет:"+str(conf_mouse_x)+'\n'
+"У офсет:"+str(conf_mouse_y), "Данни за свързване", 0)
elif conf_port<0:
conf_port=abs(conf_port)
if conf_port > 65535:
UDP_PORT = 65535 #Порт
else:
UDP_PORT=conf_port
ctypes.windll.user32.MessageBoxW(0,"Адрес:"+UDP_IP+'\n'+"Порт:"+str(UDP_PORT), "Данни за свързване", 0)
elif conf_port>65535:
UDP_PORT = 65535 #Порт
ctypes.windll.user32.MessageBoxW(0,"Адрес:"+UDP_IP+'\n'+"Порт:"+str(UDP_PORT), "Данни за свързване", 0)
else:
ctypes.windll.user32.MessageBoxW(0,"Проблем с порта!", "Данни за свързване", 0)
sys.exit()
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #Създаване на сокет и bind-ване
sock.bind((UDP_IP, UDP_PORT))
#x=int(GetSystemMetrics(0)/2) # половината от широчината на екрана в пиксели
#y=int(GetSystemMetrics(1)/2) # половината от височината на екрана в пиксели
while True:
try:
data, addr = sock.recvfrom(1024) #Задаване размер на буфер за получените данни
line=data.decode("ascii")#декодиранена данните
loaded = json.loads(line)
dv_type=loaded["type"]
dv_command=loaded["command"]
line="@"+dv_type+":"+dv_command
print(line)
if line=='@key:up':
PressKey(0x26) #стрелка нагоре
ReleaseKey(0x26)
elif line=='@key:down':
PressKey(0x28)#стрелка надолу
ReleaseKey(0x28)
elif line=='@key:left':
PressKey(0x25)# лява стрелка
ReleaseKey(0x25)
elif line=='@key:right':
PressKey(0x27)# дясна стрелка
ReleaseKey(0x27)
elif line=='@key:esc':
PressKey(0x1B)# esc
ReleaseKey(0x1B)
elif line=='@key:space':
PressKey(0x20)
ReleaseKey(0x20)
elif line=='@key:mute':
PressKey(0xAD)
ReleaseKey(0xAD)
elif line=='@key:exit':
PressKey(0x12)
PressKey(0x73)
ReleaseKey(0x12)
ReleaseKey(0x73)
elif line=='@key:menu':
PressKey(0x5C)# старт бутон
ReleaseKey(0x5C)
elif line=='@key:enter':
PressKey(0x0D)
ReleaseKey(0x0D)#ентър
elif line=='@key:vup':
PressKey(0xAF)
ReleaseKey(0xAF)# увеличаване на звука
elif line=='@key:vdown':
PressKey(0xAE)
ReleaseKey(0xAE)# намаляне на звука
elif line=='@key:f':
PressKey(0x46)
ReleaseKey(0x46)# f бутон
elif line=='@key:pc_restart':
os.system('shutdown /r /t 0')# рестартиране на машината
elif line=='@key:pc_shutdown':
os.system('shutdown /s /t 0')# рестартиране на машината
elif line=='@key:pc_sleep':
os.system('rundll32.exe powrprof.dll,SetSuspendState 0,1,0')# вкарване на машината в спящ режим
elif line=='@mouse_click:left':
ctypes.windll.user32.mouse_event(2, 0, 0, 0,0)# ляв бутон на мишката
ctypes.windll.user32.mouse_event(4, 0, 0, 0,0)
elif line=='@mouse_click:right':
ctypes.windll.user32.mouse_event(8, 0, 0, 0,0)# десен бутон на мишката
ctypes.windll.user32.mouse_event(16, 0, 0, 0,0)
elif '@mouse:' in line:
aft_line=line.replace("@mouse:", "")
x2,y2=aft_line.split("&")
x2=int(x2)
y2=int(y2)
x2=x2/conf_mouse_x #offset x
y2=y2/conf_mouse_y# offset y
pt = POINT()
windll.user32.GetCursorPos(byref(pt))
x=pt.x+((pt.x+int(x2))-x_old)#-conf_mouse_x
y=pt.y+(pt.y+int(y2)-y_old)#-conf_mouse_y
x_old=x
y_old=y
ctypes.windll.user32.SetCursorPos(x,y)
except:
pass
<file_sep><?php
session_start();
include '/var/www/db_params.php';
if(isset($_POST['pc_ip'],$_POST['pc_port'],$_POST['update'])){
if($_POST['update']==0){
$pc_ip=$_POST['pc_ip'];
$pc_port=$_POST['pc_port'];
if(isset($_SESSION["logged"])){
$conn = new mysqli($host, $username, $password, $dbname);
$stmt = $conn->prepare("DELETE FROM settings");
$stmt->execute();
$stmt = $conn->prepare("INSERT INTO settings (pc_ip,pc_port) VALUES (?,?)"); //zpisvam q v db
$stmt->bind_param("si", $pc_ip,$pc_port);
$stmt->execute();
$stmt->close();
$conn->close();
get_info($host, $username, $password, $dbname);
}
}
else if($_POST['update']==1)
get_info($host, $username, $password, $dbname);
}
function get_info($host, $username, $password, $dbname){
$conn = new mysqli($host, $username, $password, $dbname);
if($stmt = $conn->prepare("SELECT pc_ip,pc_port FROM settings")){ //vzimam vsicko kakvoto e zapisano v db
$stmt->execute();
$stmt->bind_result($col,$col1);
$stmt->fetch();
$array=array(
'ip' => $col,
'port' => $col1
);
$return[]=$array;
$stmt->close();
if(!empty($return))
echo json_encode($return); //encodvam i prashtam
}
}
?>
<file_sep><?php
$command="/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
$localIP = exec ($command); //vziamm localnoto ip ot linux mashinata
include '/var/www/db_params.php'; //zarejdam danni za db
include 'items_types.php';
$head = 'DV-INFORMATION'; //tursq tozi fragment
$cl = ':';
$match=0;
$from = '';
$port = 0;
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); //suzdavam UDO soket
socket_bind($socket,$localIP, 5113); //i go bind-vam na localnoto ip i port
while(1){
socket_recvfrom($socket, $buf, 50, 0, $from, $port);
if($buf!=null){ //proverqm za informaciq
$match=0;
$pos_h = strpos($buf, $head); //sravnqvam po gorniq fragment
if ($pos_h=== false) {
$pos_tp = strpos($buf, $dv_type1); //tursq tipa na ustroistvoto
if($pos_tp===false){
$int=2;
$pos_tp = strpos($buf, $dv_type0);
}
else{
$int=3;
}
$dv_type = substr($buf,$pos_tp,$int);
$data = substr($buf,$int,50);
$conn = new mysqli($host, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO incoming_data (ip, device,data) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data=?"); //zapisvam jivite danniti koito ustroistvoto e izpratilo
$stmt->bind_param("ssss", $from, $dv_type,$data,$data);
$stmt->execute();
$stmt->close();
$conn->close();
}
else{
$pos_tp = strpos($buf, $dv_type1);
if($pos_tp==false){
$int=2;
$pos_tp = strpos($buf, $dv_type0);
}
else
$int=3;
$pos_port = strripos($buf, $cl);
$dv_ip= substr($buf, $pos_tp+$int, $pos_port-($pos_tp+$int));
$dv_port = substr($buf,$pos_port+1,4);
$dv_type = substr($buf,$pos_tp,$int);
if (!filter_var($dv_ip, FILTER_VALIDATE_IP) === false) {
$conn = new mysqli($host, $username, $password, $dbname);
if($stmt = $conn->prepare("SELECT ip,id,id_second FROM devices")){
$stmt->execute();
$stmt->bind_result($col,$col1,$col2);
while ($stmt->fetch()) {
if($col==$dv_ip){
$match=1;
}
$lst_id_second=$col2;
$lst_id=$col1;
}
$stmt->close();
}
if($match==0){
if($lst_id_second>$lst_id)
$dv_id=$lst_id_second+1;
else
$dv_id=$lst_id+1;
if($dv_type==$dv_type1)
$dv_id_second=$dv_id+1;
else
$dv_id_second=0;
if($stmt = $conn->prepare("INSERT INTO devices (ip,port,type,id,id_second) VALUES (?,?,?,?,?)")){ //zapisvam v db dannite za ustroistvoto
$stmt->bind_param("sisii", $dv_ip, $dv_port,$dv_type,$dv_id,$dv_id_second);
$stmt->execute();
$stmt->close();
}
}
$conn->close();
}
}
}
}
?>
<file_sep><?php
session_start();
include '/var/www/db_params.php';
if(isset($_SESSION["logged"])){
$command="/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
$localIP = exec ($command); //vziamm localnoto ip
$port=5113;
$conn = new mysqli($host, $username, $password, $dbname);
if($stmt = $conn->prepare("SELECT day_price FROM electricity_price")){ //vzimam cenata ot db
$stmt->execute();
$stmt->bind_result($col);
$stmt->fetch();
$stmt->close();
}
$array=array(
'host_ip' => $localIP, //slagam gi v masivi
'host_port' => $port,
'el_price'=> $col
);
$return[]=$array;
echo json_encode($return); //encodvam v json i prashtam
}
?><file_sep><?php
//$command="/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
//$localIP = exec ($command); //vziamm localnoto ip ot linux mashinata
$from = '';
$port = 0;
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); //suzdavam UDO soket
socket_bind($socket,'192.168.1.166', 5150); //i go bind-vam na localnoto ip i port
socket_recvfrom($socket, $buf, 150, 0, $from, $port);
//if($buf!=null){ //proverqm za informaciq
// $match=0;
echo $buf;
$obj = json_decode($buf);
echo $obj->{'head'}; // 12345
?><file_sep><?php
echo <<<EOT
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/foundation.css" />
<link rel="stylesheet" href="css/ui_colors.css" />
<link rel="stylesheet" href="icon_pack/foundation-icons.css" />
</head>
<body>
<div class="off-canvas-wrap" data-offcanvas>
<div class="inner-wrap">
<a class="left-off-canvas-toggle" href="#" >Menu</a>
<!-- Off Canvas Menu -->
<aside class="left-off-canvas-menu">
<!-- whatever you want goes here -->
<ul>
<li><a href="#">Item 1</a></li>
...
</ul>
</aside>
<!-- main content goes here -->
<p>Set in the year 0 F.E. ("Foundation Era"), The Psychohistorians opens on Trantor, the capital of the 12,000-year-old Galactic Empire. Though the empire appears stable and powerful, it is slowly decaying in ways that parallel the decline of the Western Roman Empire. <NAME>, a mathematician and psychologist, has developed psychohistory, a new field of science and psychology that equates all possibilities in large societies to mathematics, allowing for the prediction of future events.</p>
<!-- close the off-canvas menu -->
<a class="exit-off-canvas"></a>
</div>
</div>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script src="js/functionality.js"></script>
<script>
$(document).foundation();
</script>
</body>
</html>
EOT;
?><file_sep><?php
session_start();
if(isset($_SESSION["logged"])){ //proverka dali si lognat
if(isset($_GET["load"])){ //proverka i vzima na stoinosti ot zaqvkata
$load_n=$_GET["load"];
}
else
$load_n="";
include 'items.php';
include 'items_types.php';
include '/var/www/db_params.php';
$ip_dvs = array(); //deklarirane na mnogo masivi
$id_dvs = array();
$id_dvs_second = array();
$id_dvs_second_sub = array();
$dv_status=array();
$tp_dvs = array();
$label_id=array();
$label_id_lc=array();
$label_id_sct=array();
$label_id_sct_second=array();
$label=array();
$id_dvs_lc=array();
$cam_ip=array();
$cam_label=array();
$cam_id=array();
$cam_port=array();
$lc_cnt=0;
$sct_cnt=0;
$match=0;
$conn = new mysqli($host, $username, $password, $dbname); //vruzka kum db
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$ip_cam = array();
$cam_label = array();
$n=0;
$conn = new mysqli($host, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT ip,label,id,port FROM cameras"); //izprashtane na zaqvka
$stmt->execute();
$stmt->bind_result($col_ip,$col_label,$col_ids,$col_ports);
$z=0;
while ($stmt->fetch()) { //poluchavane na otgovor
$cam_ip[$z]=$col_ip;
$cam_label[$z]=$col_label;
$cam_id[$z]=$col_ids;
$cam_port[$z]=$col_ports;
$z++;
}
$stmt->close();
$z=$z-1;
if(count($cam_ip)>0){ //proverqvam kolko sa kamerite
for($q=0;$q<=$z;$q++){ //slagam gi v masivi
$array=array(
'cam_ip'=> $cam_ip[$q],
'cam_port' => $cam_port[$q],
'cam_id'=>$cam_id[$q],
'cam_label'=>$cam_label[$q],
);
$return_cams[]=$array;
}
}
//echo json_encode($return);
if($stmt = $conn->prepare("SELECT type,id,ip,label,id_second,label1 FROM devices")){//izprashtane na zaqvka
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4,$col5,$col6);
$n=0;
$r=0;
while ($stmt->fetch()) {//poluchavane na otgovor
$tp_dvs[$n]=$col1;
$id_dvs[$n]=$col2;
$ip_dvs[$n]=$col3;
$label[$n]=$col4;
$id_dvs_second[$n]=$col5;
$label_id_sct_second[$n]=$col6;
if($id_dvs_second[$n]>0){
$id_dvs_second_sub[$r]=$id_dvs_second[$n];
$r++;
}
$label_id[$n]=0;
$n++;
}
$n=$n-1;
$stmt->close();
$conn->close();
if(count($ip_dvs)>0){ //proverqvam kolko sa ustroistvata
for($j=0;$j<=$n;$j++){ //slagam gi v masivi
$array=array(
'ip'=> $ip_dvs[$j],
'id' => $id_dvs[$j],
'second_id'=>$id_dvs_second[$j],
'type'=>$tp_dvs[$j],
'label' => $label[$j],
'second_label' => $label_id_sct_second[$j],
);
$return[]=$array;
}
//}
for($k=0;$k<=$n;$k++){
if($tp_dvs[$k]==$dv_type0){
$id_dvs_lc[$lc_cnt]=$id_dvs[$k]; //pravq malko magii za vseki ot elementite
$lc_cnt++;
}
if($tp_dvs[$k]==$dv_type1){
$id_dvs_sct[$sct_cnt]=$id_dvs[$k]; //sushtoto
$sct_cnt++;
}
}
}
}
if(!empty($return)){
echo "<div id='id-info' style='display:none;'>";
echo json_encode($return); //encodvam gi v json
echo "</div>";
}
switch ($load_n) { //proverka na zaqvenite elementi
case 1: //lampi i razklonitel
$fn_type1($id_dvs_sct,$id_dvs_second_sub,$sct_cnt);
$fn_type0($id_dvs_lc,$lc_cnt);
break;
case 2:
$fn_type2($cam_ip,$cam_label,$cam_port,$cam_id,$z+1); //kameri
if(!empty($return)){
echo "<div id='id-info-cams' style='display:none;'>";
echo json_encode($return_cams); //encodvam gi v json i gi izkarvam
echo "</div>";
}
break;
case 3:
$fn_type0($id_dvs_lc,$lc_cnt); //samo lampi
break;
case 4:
//echo "REMOTES"; //budeshta funkciq
$fn_type4();
break;
default:
$fn_type1($id_dvs_sct,$id_dvs_second_sub,$sct_cnt); //defaultnite kakto pri 1
$fn_type0($id_dvs_lc,$lc_cnt);
//$fn_type2($cam_ip,$cam_label,$z);
}
}
?><file_sep>var c = 0;
var t;
var tr = 0;
var drop_stat = 1;
var timer_is_on = 0;
var lock_stat = 1;
var i = 0; //loops
var buffer = 0;
var ip = 0;
var ssid = 0;
var pass = 0;
var jsonData = [];
var jsonIpPort = [];
var jsonModals = [];
var jsonData3 = [];
var ids = [];
var label_ids = [];
var labels = [];
var labels_second = [];
var id_sd = 0;
var second_label;
var raw;
var stats;
var stats_n;
var inx;
var tg=0;
var b;
var data_js=[];
var frst=[];
var scnd=[];
var dt_scnd=[];
var dt_frst=[];
var wts_1=[];
var wts_2=[];
var each_info=[[],[]];
var inf_arrs=0;
var ip_ch = new RegExp(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/);
var table = document.getElementsByTagName("TABLE")[0];
var rows=table.getElementsByTagName("TR");
var cell=table.getElementsByTagName("TD");
//===>Intervals
setInterval(outReq, 1000);
//===>Functions
function get_crn_d(id_tb){
tg=1;
var numb = id_tb.id.match(/\d/g);
numb = numb.join("");
for(var t=0;t<=jsonData.length-1;t++){
if(jsonData[t].id==numb)
document.getElementById("title-tb").innerHTML =jsonData[t].label;
else if(jsonData[t].second_id==numb)
document.getElementById("title-tb").innerHTML =jsonData[t].second_label;
}
}
function resp_hand(a) {
if(a!=undefined)
b=a
for (var j = 0; j <= jsonData3.length - 1; j++) {
for (var q = 0; q <= jsonData3.length - 1; q++) {
if (jsonData3[j].ip == jsonData[q].ip) {
if (jsonData[q].type == "LC") {
inx = jsonData3[j].data.indexOf(":TMP:");
stats_n = jsonData3[j].data.substring(inx - 1, inx)
if (stats_n == 0)
stats = false;
else
stats = true;
document.getElementById(jsonData[q].id).checked = stats;
//alert(stats);
} else {
data_js[inf_arrs]=jsonData3[j].data;
frst[inf_arrs]=data_js[inf_arrs].indexOf("N");
scnd[inf_arrs]=data_js[inf_arrs].indexOf("k1");
dt_frst[inf_arrs]=data_js[inf_arrs].substring(frst[inf_arrs]+1, scnd[inf_arrs]);
dt_scnd[inf_arrs]=data_js[inf_arrs].substring(0, frst[inf_arrs]);
wts_1[inf_arrs]=dt_frst[inf_arrs]*228;
wts_2[inf_arrs]=dt_scnd[inf_arrs]*228;
//for (var l = 0; l <= 1; l++) {
// if (l == 0) {
for(var t=0;t<=1;t++)
each_info[inf_arrs][t]=;
}
inx = data_js.lastIndexOf(":");
stats_n = data_js.substring(inx + 1, inx + 2)
var id_inf="info-"+jsonData[q].id;
if(b==1)
rows[1].getElementsByTagName("TD")[1].innerHTML = wts_1.toFixed(2)+"W";
if (stats_n == 0){
stats = false;
wts_1=0;
}
else
stats = true;
document.getElementById(id_inf).innerHTML=wts_1.toFixed(2)+"W";
document.getElementById(jsonData[q].id).checked = stats;
// } else {
inx = data_js.indexOf(":");
stats_n = data_js.substring(inx + 1, inx + 2)
id_inf="info-"+jsonData[q].second_id;
if(b==2)
rows[1].getElementsByTagName("TD")[1].innerHTML = wts_2.toFixed(2)+"W";
if (stats_n == 0){
stats = false;
wts_2=0;
}
else
stats = true;
document.getElementById(id_inf).innerHTML=wts_2.toFixed(2)+"W";
document.getElementById(jsonData[q].second_id).checked = stats;
// }
//}
inf_arrs=inf_arrs+1;
}
}
}
}
inf_arrs=0;
}
function outReq() {
var oReq = new XMLHttpRequest();
oReq.onreadystatechange = function() {
if (oReq.readyState == 4 && oReq.status == 200) {
if (oReq.responseText.length == 0) {
for (var t = 0; t <= jsonData.length - 1; t++) {
document.getElementById(jsonData[t].id).disabled = true;
if (jsonData[t].second_id != 0)
document.getElementById(jsonData[t].second_id).disabled = true;
}
} else {
for (var t = 0; t <= jsonData.length - 1; t++) {
document.getElementById(jsonData[t].id).disabled = false;
if (jsonData[t].second_id != 0)
document.getElementById(jsonData[t].second_id).disabled = false;
}
jsonData3 = JSON.parse(oReq.responseText);
resp_hand();
}
}
};
oReq.open("get", "get-data.php", true);
oReq.send();
}
var cpReq = new XMLHttpRequest();
cpReq.onreadystatechange = function() {
if (cpReq.readyState == 4 && cpReq.status == 200) {
jsonIpPort = JSON.parse(cpReq.responseText);
}
};
cpReq.open("GET", "get-ip-port.php", true);
cpReq.send();
function label_save(val) {
var plc_holder = document.getElementById(val.id).value;
var p = val.id.search("sub-");
if (p >= 0) {
var numb = val.id.match(/\d/g);
numb = numb.join("");
for (var n = 0; n <= jsonData.length - 1; n++) {
if (numb == jsonData[n].label_id) {
id_sd = jsonData[n].id;
second_label = plc_holder;
plc_holder = "";
}
}
} else {
for (var n = 0; n <= jsonData.length - 1; n++) {
if (val.id == jsonData[n].label_id)
id_sd = jsonData[n].id;
second_label = "";
}
}
var lblReq = new XMLHttpRequest();
lblReq.open("GET", "label_save.php?label=" + plc_holder + "&label1=" + second_label + "&dvs_id=" + id_sd, true);
lblReq.send();
}
var coReq = new XMLHttpRequest();
coReq.onreadystatechange = function() {
if (coReq.readyState == 4 && coReq.status == 200) {
document.getElementById("main-container").innerHTML = coReq.responseText;
get_el();
}
};
coReq.open("GET", "items_boot.php", true);
coReq.send();
function get_el() {
raw = document.getElementById("id-info").innerHTML;
jsonData = JSON.parse(raw);
for (var k = 0; k <= jsonData.length - 1; k++) {
ids[k] = jsonData[k].id;
label_ids[k] = jsonData[k].label_id;
labels[k] = jsonData[k].label;
labels_second[k] = jsonData[k].second_label;
if (labels_second[k] != "") {
var id_mrg = "sub-" + label_ids[k];
document.getElementById(id_mrg).value = labels_second[k];
}
if (labels[k] != "")
document.getElementById(label_ids[k]).value = labels[k];
}
//alert(jsonData[0].id);
}
document.getElementById("wifi-data").style.display = "none";
function dvSearch() {
ip = document.getElementById("ip-holder").value;
if (ip_ch.test(ip)) {
document.getElementById("ip-data").style.display = "none";
document.getElementById("wifi-data").style.display = "block";
} else
document.getElementById("ip-holder").style.border = "solid #ff0000";
}
function dvSave() {
ssid = document.getElementById("ssid-holder").value;
pass = document.getElementById("pass-holder").value;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://" + ip, true);
xmlhttp.send("ssid=" + ssid + "&" + "pass=" + pass + "&target=" +jsonIpPort[0].host_ip + "&port=" + jsonIpPort[0].host_port + "end");
}
function Defaults() {
ip = "";
document.getElementById("ip-holder").style.border = "";
document.getElementById("ip-holder").value = "";
document.getElementById("ssid-holder").value = "";
document.getElementById("pass-holder").value = "";
document.getElementById("wifi-data").style.display = "none";
document.getElementById("ip-data").style.display = "block";
}
function UDP_send(elt) {
var sReq = new XMLHttpRequest();
sReq.open("get", "UDP_send.php?q=" + elt.id, true);
sReq.send();
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function timedCount() {
if (lock_stat == 1) {
document.getElementById("slider").onchange = function() {
var value = document.getElementById('slider').getAttribute('data-slider');
document.getElementById('qj').innerHTML = value;
if (value > 80)
document.getElementById('qj').style.backgroundColor = 'red';
else
document.getElementById('qj').style.backgroundColor = 'green';
if (c > 0) {
stopCount()
c = 0;
}
};
c = c + 10;
if (c == 500) {
if (tr == 0) {
vibrate();
document.getElementById("switch").style.background = "silver";
tr = 1;
} else {
vibrate();
document.getElementById("switch").style.background = "#16A085";
tr = 0;
}
} else {
document.addEventListener("touchend", function() {
stopCount()
c = 0;
});
}
t = setTimeout(function() {
timedCount()
}, 10);
} else
document.addEventListener("touchend", function() {
stopCount()
c = 0;
});
}
function vibrate() {
window.navigator.vibrate(500);
}
function iconLock() {
var check = document.getElementById('icon').className;
if (check == 'fi-unlock') {
if (drop_stat == 0)
menuUp()
document.getElementById('icon').className = "fi-lock";
document.getElementById('slider').className += " disabled";
document.getElementById("switch").style.background = 'red';
lock_stat = 0;
} else {
document.getElementById('icon').className = "fi-unlock";
document.getElementById("slider").className =
document.getElementById("slider").className.replace(/(?:^|\s)disabled(?!\S)/g, '')
document.getElementById("switch").style.background = '#16A085';
lock_stat = 1;
}
}
// document.getElementById("panel").addEventListener("touchmove", function(p){
// p.preventDefault()
// window.navigator.vibrate(15);
// });
// document.getElementById("left").addEventListener("touchstart", function(){
// document.getElementById("qj").innerHTML="levo";
// document.getElementById("left").style.background = "grey";
// window.navigator.vibrate(150);
// });
// document.getElementById("left").addEventListener("touchend", function(){
// document.getElementById("left").style.background = "#DDDDDD";
// });
// document.getElementById("right").addEventListener("touchstart", function(){
// document.getElementById("right").style.background = "grey";
// window.navigator.vibrate(150);
// document.getElementById("qj").innerHTML="desno";
// });
// document.getElementById("right").addEventListener("touchend", function(){
// document.getElementById("right").style.background = "#DDDDDD";
// });
document.getElementById("settings").addEventListener("touchend", function() {
document.body.scrollTop = 0;
});
document.getElementById("off-canvas-prevent").addEventListener("touchmove", function(e) {
e.preventDefault()
});<file_sep><?php
session_start();
include '/var/www/db_params.php';
//if(isset($_SESSION["logged"])){
while(1){
$all_ip= array();
$death_ip=array();
$conn = new mysqli($host, $username, $password, $dbname);
if($stmt = $conn->prepare("SELECT ip FROM incoming_data")){ //vzimam cenata ot db
$stmt->execute();
$stmt->bind_result($col);
$n=0;
while ($stmt->fetch()) {
$all_ip[$n]=$col;
$n++;
}
$stmt->close();
}
$allIp = implode(' ', $all_ip);
exec("fping -u -i 100 $allIp" , $death_ip);
//echo print_r($death_ip);
/* for($i=0;$i<=$n-1;$i++){
if($stmt = $conn->prepare("DELETE FROM incoming_data WHERE ip=?")){ //vzimam cenata ot db
$stmt->bind_param("s",$death_ip[$i]);
$stmt->execute();
$stmt->close();
}
if($stmt = $conn->prepare("DELETE FROM devices WHERE ip=?")){ //vzimam cenata ot db
$stmt->bind_param("s",$death_ip[$i]);
$stmt->execute();
$stmt->close();
}
} */
$conn->close();
sleep(1);
}
//}
?><file_sep># open-automation
Piece of software that provides full control and monitoring over power appliances from around the world over internet
___

<file_sep><?php
session_start();
include '/var/www/db_params.php'; //proverka i vzima na stoinosti ot zaqvkata
$pos=$_GET["pos"];
$id=$_GET["id"];
if(isset($_SESSION["logged"])){
$value="";
$conn = new mysqli($host, $username, $password, $dbname);
if($pos==1){
if($stmt = $conn->prepare("UPDATE devices SET time_on=(?) WHERE id=(?)")){
$stmt->bind_param("ii",$value,$id);
$stmt->execute();
}
if($stmt = $conn->prepare("UPDATE months_consumption SET time_on=(?) WHERE id_hs=(?)")){
$stmt->bind_param("ii",$value,$id);
$stmt->execute();
}
$conn->close();
}
else if($pos==2){
if($stmt = $conn->prepare("UPDATE devices SET time_on_second=(?) WHERE id_second=(?)")){
$stmt->bind_param("ii",$value,$id);
$stmt->execute();
}
if($stmt = $conn->prepare("UPDATE months_consumption SET time_on_second=(?) WHERE id_second_hs=(?)")){
$stmt->bind_param("ii",$value,$id);
$stmt->execute();
}
$conn->close();
}
}
?><file_sep><?php
$fn_type0="lc_btn"; //ime na funkciq za kliuch za lampa
$fn_type1="sct_btn";//za razklonitelq
$fn_type2="video_panel";//kameri
$fn_type3="led_panel";//led panel
$fn_type4="touch_pad";//touch pad
//=======================
$dv_type0="LC";//kratki naimenovaniq
$dv_type1="SCT";
$dv_type2="VIDEO";
$dv_type3="LED";
$dv_type4="TOUCH";
?><file_sep><?php
session_start();
include '/var/www/db_params.php';
if(isset($_SESSION["logged"])){
$ip_cam = array();
$cam_label = array();
$n=0;
$conn = new mysqli($host, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT ip,label FROM cameras"); //vziamm infoto ot db za kamerite
$stmt->execute();
$stmt->bind_result($col,$col1);
while ($stmt->fetch()) {
$array=array(
'cam_ip' => $col, //slagam v masiv
'label' => $col1,
);
$return[]=$array;
}
$stmt->close();
echo json_encode($return); //encodvam v json i prashtam
}
?><file_sep><?php
session_start();//startiram sesiq
include '/var/www/db_params.php';
if(isset($_GET['ip'],$_GET["name"],$_GET["port"],$_GET["stat"])){ //proverqvam za zadadeni stoinosti
$name=$_GET["name"];
$ip=$_GET["ip"];
$port=$_GET["port"];
$stat=$_GET["stat"];
$ip_cam= array();
$port_cam= array();
$label_cam= array();
if(isset($_SESSION["logged"])){ //proverqm dali si lognat
$conn = new mysqli($host, $username, $password, $dbname);
if($stat==0){
$stmt = $conn->prepare("INSERT INTO cameras (ip,label,port) VALUES (?,?,?) ON DUPLICATE KEY UPDATE label=?"); //zapisvam informaciqta
$stmt->bind_param("ssis", $ip,$name,$port,$name);
$stmt->execute();
// echo "Камерата е добавена!";
}
else if($stat==1){
$stmt = $conn->prepare("DELETE FROM cameras WHERE ip=? AND port=?"); //triq informaciq
$stmt->bind_param("si", $ip,$port);
$stmt->execute();
//echo "Камерата е премахната!";
}
$stmt = $conn->prepare("SELECT ip,port,label FROM cameras");
$stmt->execute();
$stmt->bind_result($col,$col1,$col2);
$n=0;
while ($stmt->fetch()) {
$ip_cam[$n]=$col;
$port_cam[$n]=$col1;
$label_cam[$n]=$col2;
$n++;
}
if(array_filter($ip_cam)){
echo <<<EOT
<table style=width:100%>
<tr>
<td>Адрес</td>
<td>Порт</td>
<td>Име</td>
</tr>
EOT;
for($u=0;$u<=$n-1;$u++){
echo <<<EOT
<tr>
<td>$ip_cam[$u]</td>
<td>$port_cam[$u]</td>
<td>$label_cam[$u]</td>
</tr>
EOT;
}
echo "</table>";
}
else
echo "Няма добавени камери!";
$stmt->close();
$conn->close();
}
}
?><file_sep><?php
session_start();
if(isset($_SESSION["logged"])){ //proverka koi e lognat
include '/var/www/db_params.php';
$conn = new mysqli($host, $username, $password, $dbname); //vruzka kum db
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//header("Access-Control-Allow-Origin:*");
if($stmt = $conn->prepare("SELECT ip,data,k1,k2 FROM incoming_data")){ //vzimam vsicko kakvoto e zapisano v db
$stmt->execute();
$stmt->bind_result($col,$col1,$col2,$col3);
while ($stmt->fetch()) {
$array=array( //slagom go v masiv
'ip' => $col,
'data' => $col1,
'k1' => $col2,
'k2' => $col3,
);
$return[]=$array;
}
$stmt->close();
}
$conn->close();
if(!empty($return))
echo json_encode($return); //encodvam i prashtam
}
?>
| 8abbae9e20f6721020f8401a7eeaf8d323aea577 | [
"JavaScript",
"Python",
"Markdown",
"PHP"
] | 22 | PHP | krisstakos/open-automation | bbf303a4d153125894055797c76153cf9655be2f | 88c7af971ecb8a01429dd1000069c32f29cafd62 | |
refs/heads/master | <file_sep>"""知乎图片"""
import re
import json
import requests
import os
import time
from pathlib import Path
path = "./pics"
url = 'https://www.zhihu.com/question/58498720'
class Pics(object):
"""
下载知乎问题下所有回答图片
example:pic = Pics('https://www.zhihu.com/question/270912691', './pics')
pic.run()
"""
def __init__(self, url, path):
self.header = {
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3551.3 Safari/537.36',
'Upgrade-Insecure-Requests':'1',
'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
}
# 问题
self.index_url = url
# 获取问题的json链接
# https://www.zhihu.com/api/v4/questions/58498720/answers?include=content&limit=20&offset=0&sort_by=default
self.url = self.makeUrl(url)
# 存放根目录路径
self.base_dir = Path(path)
self.page = None
self.makeNewSession()
def makeUrl(self, url):
rindex = url.rfind('/') + 1
answers_url = 'https://www.zhihu.com/api/v4/questions/' + url[rindex:] + '/answers'
return answers_url
def makeNewSession(self):
"""用于保持cookies"""
self.session = requests.session()
self.session.headers = self.header
params = {
"include":"content",
"limit":"20",
"offset":"0",
"sort_by":"default",
}
self.session.params = params
self.session.get(self.index_url)
def getContent(self):
"""获取图片"""
print('正在从%s下载'%self.url)
json_str = self.session.get(self.url)
json_obj = json.loads(json_str.content.decode())
data = json_obj.get('data')
if data:
self.url = json_obj.get('paging').get('next')
else:
self.url = ''
for i in data:
self.formatPic(i.get('content'), i.get("id"))
def formatPic(self,content,answer_id):
result = list(set(re.findall(r'data-original="(.+?)"', content))) #正则获取图片 然后去重
answer_id = str(answer_id)
index = 0
for i in result:
path = self.makePicName(i, index, answer_id)
index +=1
pic = self.session.get(i)
if pic.status_code != 200:
print('图片:'+i+'获取失败')
print('状态码:'+pic.status_code)
time.sleep(3)
self.savePic(pic,path)
def savePic(self,pic,name):
with Path(self.base_dir/name).open("wb") as f:
f.write(pic.content)
print('保存图片:'+self.base_dir.parts[-1]+'/'+name)
def makePicName(self,link,index,answer_id):
rindex = link.rfind(".")
name = '{}_{}{}'.format(answer_id,index,link[rindex:])
return name
def run(self):
is_exists = self.base_dir.exists()
if not is_exists:
self.base_dir.mkdir()
while True:
if self.url == '':
break
self.getContent()
print('图片下载完毕')
if __name__ == '__main__':
pic = Pics(url, path)
pic.run()<file_sep># spider
### 抓取知乎问题下所有图片
```
from zhihu_pic import Pics
pic = Pics("问题链接", "存放位置")
```
| 38ce7d9e7ac1dc023a721ff428e8f43d273aa677 | [
"Markdown",
"Python"
] | 2 | Python | fyxw/spider | f8bd80452ba6a76d913d021d310cd317a81ace4f | 3cee1483e3d608a057d631d097b381052c929330 | |
refs/heads/master | <file_sep>$(function() {
var uploadForm = '#uploadForm';
//设置首页边框样式(宽度和高度)
var outerWidth = parseFloat($('.outer').css("width"));
$('.outer').css("height", 0.41*outerWidth);
var innerWidth = parseFloat($('.inner').css("width"));
var innerHeight = 0.62*innerWidth;
$('.inner').css("height", innerHeight);
//设置首页默认图片显示位置
$('.showFront').css("top", 0.25*innerHeight);
$('.showBack').css("top", 0.25*innerHeight);
$('.showOne').css("top", 0.25*innerHeight);
var $img;
var ifEdit = false;
//初始化主界面
$.ajax({
type: 'POST',
url: base + '/cert/queryAll.html',
success: function (data) {
var result = eval('(' + data + ')');
if(result.status == 1){
var data = result.data;
if(data.length > 0){
var arr = new Array();
//先整合首页需要展示的所有框框
for(var i in data){
var type = data[i].certType;
switch (type){
case 1:
arr.push(createObj(data[i].certId, data[i].certType, data[i].certUrl1, data[i].certUrl2, data[i].certName));
$('#showDiv').append(showDiv('showDouble', data[i].certId));
if(i == data.length-1) $('#showDouble').find('.outer').removeAttr('id');
break;
case 2:
arr.push(createObj(data[i].certId, data[i].certType, data[i].certUrl1, data[i].certUrl2, data[i].certName));
$('#showDiv').append(showDiv('showDouble', data[i].certId));
if(i == data.length-1) $('#showDouble').find('.outer').removeAttr('id');
break;
case 3:
arr.push(createObj(data[i].certId, data[i].certType, data[i].certUrl1, data[i].certUrl2, data[i].certName));
$('#showDiv').append(showDiv('showSingle', data[i].certId));
if(i == data.length-1) $('#showSingle').find('.outer').removeAttr('id');
break;
case 4:
arr.push(createObj(data[i].certId, data[i].certType, data[i].certUrl1, data[i].certUrl2, data[i].certName));
$('#showDiv').append(showDiv('showSingle', data[i].certId));
if(i == data.length-1) $('#showSingle').find('.outer').removeAttr('id');
break;
}
}
$('#showDouble').remove();
$('#showSingle').remove();
//在每个框框里填充原始图片
for(var i=0; i < arr.length; i++){
var type = arr[i].type;
if(type == 1 || type == 2){
if(arr[i].url1){
$('#targetId_' + arr[i].id).find('.showFront').replaceWith("<img name='aa'/>");
var src = base + '/' + arr[i].url1;
$img = $('#targetId_' + arr[i].id).find('img[name="aa"]');
$img.attr('src', src);
}
if(arr[i].url2){
$('#targetId_' + arr[i].id).find('.showBack').replaceWith("<img name='bb'/>");
var src = base + '/' + arr[i].url2;
$img = $('#targetId_' + arr[i].id).find('img[name="bb"]');
$img.attr('src', src);
}
} else if(type == 3 || type == 4){
if(arr[i].url1){
$('#targetId_' + arr[i].id).find('.showOne').replaceWith("<img name='cc'/>")
var src = base + '/' + arr[i].url1;
$img = $('#targetId_' + arr[i].id).find('img[name="cc"]');
$img.attr('src', src);
}
}
$('#targetId_' + arr[i].id).find('.spanText').text(arr[i].name?arr[i].name:'(无名称展示)');
}
//延迟一点时间后,调整每个框框中图片的大小和位置
setTimeout(function () {
for(var i=0; i < arr.length; i++){
var type = arr[i].type;
if(type == 1 || type == 2){
if(arr[i].url1){
$img = $('#targetId_' + arr[i].id).find('img[name="aa"]');
editActive($img.parent(), arr[i].id);//显示悬浮编辑栏
ifEdit = false;
autoScaling();
}
if(arr[i].url2){
$img = $('#targetId_' + arr[i].id).find('img[name="bb"]');
editActive($img.parent(), arr[i].id);//显示悬浮编辑栏
ifEdit = false;
autoScaling();
}
}else if(type == 3 || type == 4){
if(arr[i].url1){
$img = $('#targetId_' + arr[i].id).find('img[name="cc"]');
editActive($img.parent(), arr[i].id);//显示悬浮编辑栏
ifEdit = false;
autoScaling();
}
}
}
}, 300);
}
}
},
error: function () {
}
});
//上传框初始页面
var initHtml = getParentHtml('idCard_upload');
var editMap = {};
function editActive(parent, targetId){
parent.append('<div class="file_bar" style="width:' + (innerWidth-2) + 'px;left: 32px;"><div style="padding:5px;"><span class="file_edit" data-target="' + targetId + '" title="编辑"></span></div></div>');
parent.hover(
function (e) {
$(this).find(".file_bar").addClass("file_hover");
//绑定编辑按钮
if($(".file_edit").length>0){
// 编辑方法
$(".file_edit").click(function() {
var editCertId = $(this).attr("data-target");
$.ajax({
type: 'POST',
url: base + "/cert/load.html",
data: {certId: editCertId},
success: function (data) {
var result = eval('(' + data + ')');
if(result.status == 1){
var data = result.data;
var type = data.certType;
$('#addArea').html(initHtml);
//初始化单选按钮的状态(默认将无关的单选按钮设置为禁选)
var radioBtns = $('#uploadForm').find('input[type="radio"]');
for(var i in radioBtns){
var typeVal = radioBtns[i].value;
var _this = $('#uploadForm').find('input[type="radio"][value="' + typeVal + '"]');
if(typeVal == type)
_this.prop("checked", true);
else
_this.attr("disabled", true);
}
$('#uploadForm').find('input[type="radio"][value="' + type + '"]').removeAttr("disabled");
//加载图片
loadImg(type, data);
$("#cachet_modal").modal({show:true, backdrop: 'static'});
}
},
error: function () {
}
});
});
}
},function (e) {
$(this).find(".file_bar").removeClass("file_hover");
}
);
}
function loadImg(type, data){
setUploadArea(850, 355);
switch(type){
case 1:
$('#addArea').find('input[name="certName"]').attr('disabled',true);
$('#police_upload').hide();
$('#signature_upload').hide();
$('#cachet_upload').hide();
$('#idCard_upload').find('input[name="certName"]').removeAttr('disabled');
$('#idCard_upload').show();
var divIds = ["idCard_front", "idCard_back"];
var fileIds = ["fileImage_idCard_front", "fileImage_idCard_back"];
initEdit(divIds, fileIds, "idCard_upload", data);
break;
case 2:
$('#addArea').find('input[name="certName"]').attr('disabled',true);
$('#idCard_upload').hide();
$('#signature_upload').hide();
$('#cachet_upload').hide();
$('#police_upload').find('input[name="certName"]').removeAttr('disabled');
$('#police_upload').show();
var divIds = ["police_front", "police_back"];
var fileIds = ["fileImage_police_front", "fileImage_police_back"];
initEdit(divIds, fileIds, "police_upload", data);
break;
case 3:
$('#addArea').find('input[name="certName"]').attr('disabled',true);
$('#idCard_upload').hide();
$('#police_upload').hide();
$('#cachet_upload').hide();
$('#signature_upload').find('input[name="certName"]').removeAttr('disabled');
$('#signature_upload').show();
var divIds = ["signature_all"];
var fileIds = ["fileImage_signature"];
initEdit(divIds, fileIds, "signature_upload", data);
break;
case 4:
$('#addArea').find('input[name="certName"]').attr('disabled',true);
$('#idCard_upload').hide();
$('#police_upload').hide();
$('#signature_upload').hide();
$('#cachet_upload').find('input[name="certName"]').removeAttr('disabled');
$('#cachet_upload').show();
var divIds = ["cachet_all"];
var fileIds = ["fileImage_cachet"];
initEdit(divIds, fileIds, "cachet_upload", data);
break;
}
}
function initEdit(divIds, fileIds, parentId, data){
for(var i in divIds){
var divId = divIds[i];
editMap[divId] = getParentHtml(divId);
}
if(divIds.length == 2){
if(data.certUrl1){
$('#' + divIds[0]).replaceWith("<img name='aa'/>");
var url1 = base + '/' + data.certUrl1;
$('#' + parentId).find('img[name="aa"]').attr('src', url1);
}
if(data.certUrl2){
$('#' + divIds[1]).replaceWith("<img name='bb'/>");
var url2 = base + '/' + data.certUrl2;
// console.log("url2 = " + data.cachetUrl2);
$('#' + parentId).find('img[name="bb"]').attr('src', url2);
}
}else if(divIds.length == 1){
if(data.certUrl1){
$('#' + divIds[0]).replaceWith("<img name='cc'/>");
var url1 = base + '/' + data.certUrl1;
$('#' + parentId).find('img[name="cc"]').attr('src', url1);
}
}
for(var i in fileIds){
var imgUrl = $('#' + fileIds[i]).parent().children('img').attr('src');
if(imgUrl){
$('#' + fileIds[i]).parent().append('<div class="file_bar" style="width: 358px;left: 40px;"><div style="padding:5px;"><span class="file_del" data-target="' + fileIds[i] + '" data-key="' + divIds[i] + '"title="删除"></span></div></div>');
$('#' + fileIds[i]).parent().hover(function (e) {
$(this).find(".file_bar").addClass("file_hover");
//绑定删除按钮
if($(".file_del").length>0){
// 删除方法
$(".file_del").click(function() {
var delFileId = $(this).attr("data-target");
// console.log("targetId = " + targetId);
var key = $(this).attr("data-key");
var defaultHtml = editMap[key];
$('#' + delFileId).parent().html(defaultHtml);
});
}
},function (e) {
$(this).find(".file_bar").removeClass("file_hover");
});
}
}
//调整图片位置和大小
setTimeout(function () {
$img = $('#' + parentId).find('img');
ifEdit = true;
autoScaling();
}, 300);
$('#certId').val(data.certId);
$('#' + parentId).find('input[name="certName"]').val(data.certName);
}
function autoScaling(){
if (!$.support.leadingWhitespace)//检查是否为IE6-8
$img.get(0).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = "image";
var img_width = $img.width();
var img_height = $img.height();
if(img_width > 0 && img_height > 0){
var div_width = ifEdit?355:innerWidth;
var div_height = ifEdit?218:innerHeight;
var rate = (div_width / img_width < div_height / img_height) ? div_width / img_width : div_height / img_height;
if(rate < 1){
if (!$.support.leadingWhitespace)
$img.get(0).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = "scale";
$img.width(img_width * rate);
$img.height(img_height * rate);
}else{
$img.width(img_width);
$img.height(img_height);
}
var left = (div_width - $img.width()) * 0.5;
var top = (div_height - $img.height()) * 0.5;
$img.css({ "margin-left": left, "margin-top": top });
$img.show();
}
}
$('#delete_button').on('click', function() {
var ids = [];
var cbox = $(':checkbox:checked');
for(var i=0; i<cbox.length; i++){
ids.push(cbox[i].id);
}
var certIds = ids.join();
loading('body');
$.ajax({
type: "POST",
url: base + "/cert/delete.html",
data: {certIds: certIds},
success: function (data) {
var result = eval('(' + data + ')');
if(result.status == 1){
removeLoading('waiting');
parent.location.reload();
}
}
});
});
$('#create_button').on('click', function () {
setTimeout(function () {
var outerUploadWidth = parseFloat($('.outer_upload').css("width"));
$('.outer_upload').css("height", 0.41*outerUploadWidth);
var innerUploadWidth = parseFloat($('.inner_upload').css("width"));
var innerUploadHeight = 0.62*innerUploadWidth;
$('.inner_upload').css("height", innerUploadHeight);
$('.front').css("top", 0.25*innerUploadHeight);
$('.back').css("top", 0.25*innerUploadHeight);
$('.both').css("top", 0.25*innerUploadHeight);
$('.title').css("top", 0.32*innerUploadHeight);
$('.title').css("left", 0.35*innerUploadWidth);
}, 300);
$('input[name="certType"]').on('click', function () {
$('#addArea').html(initHtml);
var type = $(this).attr('value');
typeChecked(type);
//初始化单选按钮的状态(默认全部可选)
var radioBtns = $('#uploadForm').find('input[type="radio"]');
for(var i in radioBtns){
var typeVal = radioBtns[i].value;
if(radioBtns[i].disabled)
$('#uploadForm').find('input[type="radio"][value="' + typeVal + '"]').removeAttr("disabled");
}
});
$('#idCard').click();//默认选中身份证
$("#cachet_modal").modal({show:true, backdrop: 'static'});
});
function typeChecked(type){
var outerUploadWidth = parseFloat($('.outer_upload').css("width"));
var innerUploadWidth = parseFloat($('.inner_upload').css("width"));
setTimeout(setUploadArea(outerUploadWidth, innerUploadWidth), 100);
switch(type){
case '1':
$('#addArea').find('input[name="certName"]').attr('disabled',true);
$('#police_upload').hide();
$('#signature_upload').hide();
$('#cachet_upload').hide();
$('#idCard_upload').find('input[name="certName"]').removeAttr('disabled');
$('#idCard_upload').show();
break;
case '2':
$('#addArea').find('input[name="certName"]').attr('disabled',true);
$('#idCard_upload').hide();
$('#signature_upload').hide();
$('#cachet_upload').hide();
$('#police_upload').find('input[name="certName"]').removeAttr('disabled');
$('#police_upload').show();
break;
case '3':
$('#addArea').find('input[name="certName"]').attr('disabled',true);
$('#idCard_upload').hide();
$('#police_upload').hide();
$('#cachet_upload').hide();
$('#signature_upload').find('input[name="certName"]').removeAttr('disabled');
$('#signature_upload').show();
break;
case '4':
$('#addArea').find('input[name="certName"]').attr('disabled',true);
$('#idCard_upload').hide();
$('#police_upload').hide();
$('#signature_upload').hide();
$('#cachet_upload').find('input[name="certName"]').removeAttr('disabled');
$('#cachet_upload').show();
break;
}
}
//设置证件上传边框宽度、高度,调整默认图片和文字显示位置
function setUploadArea(outerUploadWidth, innerUploadWidth) {
$('.outer_upload').css("height", 0.41*outerUploadWidth);
var innerUploadHeight = 0.62*innerUploadWidth;
$('.inner_upload').css("height", innerUploadHeight);
$('.front').css("top", 0.25*innerUploadHeight);
$('.back').css("top", 0.25*innerUploadHeight);
$('.both').css("top", 0.25*innerUploadHeight);
$('.title').css("top", 0.32*innerUploadHeight);
$('.title').css("left", 0.35*innerUploadWidth);
}
//摸态框关闭事件
$("#cachet_modal").on('hide.bs.modal', function () {
if(!$('#fileSubmit').attr('disabled')) $('#fileSubmit').attr('disabled', 'disabled');
});
});
var fns = new Array();
var blobMap = {};
var arr = new Array(6);
function fileUpload(div) {
$('input[name="certType"]').on('click', function () {
fns = new Array();
blobMap = {};
});
var type = $(div).attr('data-type');
switch(type){
case 'idCard_front'://身份证正面
$('#fileImage_idCard_front').click();
preview('idCard_front', 'fileImage_idCard_front', 0);
break;
case 'idCard_back'://身份证反面
$('#fileImage_idCard_back').click();
preview('idCard_back', 'fileImage_idCard_back', 1);
break;
case 'police_front'://警官证正面
$('#fileImage_police_front').click();
preview('police_front', 'fileImage_police_front', 2);
break;
case 'police_back'://警官证反面
$('#fileImage_police_back').click();
preview('police_back', 'fileImage_police_back', 3);
break;
case 'signature_all'://电子签名
$('#fileImage_signature').click();
preview('signature_all', 'fileImage_signature', 4);
break;
case 'cachet_all'://电子公章
$('#fileImage_cachet').click();
preview('cachet_all', 'fileImage_cachet', 5);
break;
}
}
function preview(divId, fileId, insertIndex){
var fileInput = "#" + fileId;
var $uploadDiv = $(fileInput).parent('.inner_upload');
arr.splice(insertIndex, 1, getParentHtml(divId));
// Preview image
var imgDiv = '#' + divId;
$(fileInput).uploadPreview({
width: 354,
height: 218,
imgDiv: imgDiv
});
// Import image
$(fileInput).change(function () {
var files = this.files;
var _this = $(this);
// var index = _this.attr("data-index");
var fn = _this.attr("name");
//剔除重复后保存(避免出现多次保存同一类型同一照面证件的情况)
var flag = false;
if(fns.length > 0){
for(var i in fns){
if(fn == fns[i]){
flag = true;//说明存在重复值!
break;
}
}
}
if(!flag) fns.push(fn);
loading($uploadDiv);
//加载完图片后显示裁剪框
setTimeout(function () {
removeLoading('waiting');
var $image = $uploadDiv.children('img');
$image.cropper({
checkImageOrigin: true,
aspectRatio: 177 / 109,
autoCropArea: 0.5,
viewMode: 1,
modal: false
});
if(files && files.length){
var cutBtn = $uploadDiv.siblings('.jy-up-ch').children('a[data-ng-click="cutBtn"]');
//给裁剪按钮注册点击事件
cutBtn.on('click', function () {
var canvas = $image.cropper("getCroppedCanvas");
//这里转成base64 image,img的src可直接使用
var imgUrl = canvas.toDataURL("image/png", 1.0);
// var imgUrl = canvas.toDataURL("image/jpeg", 1.0);
// console.log(imgUrl);
var blob = convertBase64UrlToBlob(imgUrl);
blobMap[fn] = blob;
loading($uploadDiv);
setTimeout(function(){
removeLoading('waiting');
//显示悬浮删除栏
if(_this.val()){
$image.cropper("destroy");
//裁剪后预览图片
$image.attr("src", imgUrl);
$image.css("width", 355);
$image.css("height", 218);
$image.css("margin-left", 0);
$image.css("margin-top", 0);
$uploadDiv.append('<div class="file_bar" style="width: 358px;left: 40px;"><div style="padding:5px;"><span class="file_del" data-target="' + fileId + '" data-index="' + insertIndex + '" title="删除"></span></div></div>');
$uploadDiv.hover(
function (e) {
$(this).find(".file_bar").addClass("file_hover");
//绑定删除按钮
if($(".file_del").length > 0){
// 删除方法
$(".file_del").click(function() {
var delFileId = $(this).attr("data-target");
var index = $(this).attr("data-index");
// console.log("insertIndex = " + index);
var defaultHtml = arr[index];
// console.log(defaultHtml);
$('#' + delFileId).parent().html(defaultHtml);
if($(".file_del").length == 0) $('#fileSubmit').attr('disabled', true);
});
}
},function (e) {
$(this).find(".file_bar").removeClass("file_hover");
}
);
//激活上传按钮并绑定点击事件
if($('#fileSubmit').attr('disabled') == 'disabled'){
$('#fileSubmit').removeAttr('disabled');
// $('#fileSubmit').click(function () {
//
// });
}
}
},3000);
});
}
}, 3500);
});
}
function beginUpload(){
$('#fileSubmit').removeAttr('disabled');
var fd = new FormData($('#uploadForm')[0]);
var certId = fd.get("certId");
var certType = fd.get("certType");
console.log("certId = " + certId);
console.log("certType = " + certType);
if(!certId || certId == ''){// 新增
if(certType == 4){// 上传公章
var flag = ifExist();
if(flag) {
toastr.warning("公章只能上传一次!");
return false;
}
}
}
for(var i in fns){
var key = fns[i];
console.log(blobMap[key]);
fd.append("'" + key + "'", blobMap[key]);
}
// return;
var xhr = new XMLHttpRequest();
xhr.open('POST', base + "/cert/upload.html", true);
xhr.send(fd);
$("#cachet_modal").modal('hide');
parent.location.reload();
}
function ifExist(){
var count = 0;
$.ajax({
type: 'POST',
async : false,//必选
url: base + '/cert/queryAll.html',
success: function (result) {
var result = eval('(' + result + ')');
if(result.status == 1){
var data = result.data;
for(var i in data){
if(data[i].certType == 4){
count++;
}
}
}
}
});
console.log("count = " + count);
if(count > 0)
return true;
else
return false;
}
function loading(uploadDiv){
$(uploadDiv).loading({
loadingWidth:120,
title:'',
name:'waiting',
discription:'',
direction:'column',
type:'origin',
originBg:'#71EA71',
originDivWidth:80,
originDivHeight:80,
originWidth:10,
originHeight:10,
smallLoading:false,
loadingBg:'transparent',
flexCenter: true
});
}
//base64转成blob
function convertBase64UrlToBlob(urlData){
var bytes = window.atob(urlData.split(',')[1]);//去掉url的头,并转换为byte
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob( [ia], {type : 'image/png'});
}
//左旋转
function rotateLeft(btn){
var $image = $(btn).parent().siblings('.inner_upload').children('img');
$image.cropper('rotate', -90);
}
//右旋转
function rotateRight(btn){
var $image = $(btn).parent().siblings('.inner_upload').children('img');
$image.cropper('rotate', 90);
}
//缩小
function zoomOut(btn){
var $image = $(btn).parent().siblings('.inner_upload').children('img');
$image.cropper('zoom', -0.5);
}
//放大
function zoomIn(btn) {
var $image = $(btn).parent().siblings('.inner_upload').children('img');
$image.cropper('zoom', 0.5);
}
function createObj(id, type, url1, url2, name){
var obj = new Object();
obj.id = id;
obj.type = type;
obj.url1 = url1;
obj.url2 = url2;
obj.name = name;
return obj;
}
function showDiv(divId, certId){
switch (divId){
case "showDouble":
$('#' + divId).find('.outer').attr('id', 'targetId_' + certId);
var item = $('#' + divId).find('.outer').children('input[name="item"]');
item.attr('id', certId);
item.removeAttr("disabled");
break;
case "showSingle":
$('#' + divId).find('.outer').attr('id', 'targetId_' + certId);
var item = $('#' + divId).find('.outer').children('input[name="item"]');
item.attr('id', certId);
item.removeAttr("disabled");
break;
}
var tempDiv = $('#' + divId).clone(true);
return tempDiv.html();
}
function selectForDelete(cb){
if($(cb).is(':checked')){
$('#delete_button').removeAttr('disabled');
$('#delete_button').removeClass('btn btn-default').addClass('btn btn-success');
}else{
var count = 0;
var items = $('.cb');
for(var i=0; i<items.length; i++){
if(items[i].checked == true) count++;
}
if(count == 0) {
$('#delete_button').attr('disabled', 'disabled');
$('#delete_button').removeClass('btn btn-success').addClass('btn btn-default');
}
}
}
function getParentHtml(id){
var uploadDiv = $('#' + id).parent().clone(true);
return uploadDiv.html();
}<file_sep>/*
Navicat MySQL Data Transfer
Source Server : local
Source Server Version : 50533
Source Host : localhost:3306
Source Database : cachet
Target Server Type : MYSQL
Target Server Version : 50533
File Encoding : 65001
Date: 2017-11-17 16:38:52
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for cert
-- ----------------------------
DROP TABLE IF EXISTS `cert`;
CREATE TABLE `cert` (
`CERT_ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`CERT_NAME` varchar(20) CHARACTER SET gb2312 DEFAULT NULL COMMENT '证件名称',
`CERT_TYPE` varchar(20) DEFAULT NULL COMMENT '证件类型(1:身份证,2:警官证,3:电子签名,4:公章)',
`CERT_URL1` varchar(255) DEFAULT NULL COMMENT '证件存放位置1',
`CERT_URL2` varchar(255) DEFAULT NULL COMMENT '证件存放位置2',
`CREATE_TIME` datetime DEFAULT NULL COMMENT '创建时间',
`SCBZ` varchar(10) DEFAULT NULL COMMENT '删除标识',
PRIMARY KEY (`CERT_ID`),
KEY `<KEY>` (`CERT_NAME`),
KEY `<KEY>` (`CERT_TYPE`),
KEY `<KEY>` (`CERT_URL1`),
KEY `<KEY>` (`CERT_URL2`),
KEY `<KEY>` (`CREATE_TIME`),
KEY `<KEY>` (`SCBZ`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of cert
-- ----------------------------
INSERT INTO `cert` VALUES ('11', '111', '1', '/upload/20171117162938/2017111716293918679236280056', '/upload/20171117162938/2017111716293911215180584541', '2017-11-17 16:29:39', '0');
<file_sep>package com.cachet.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/index")
public class IndexController {
/**
* 主界面
*/
private final String MAIN_URL = "/index";
@RequestMapping(method=RequestMethod.GET)
public String view(ModelMap model) {
model.addAttribute("message", "Hello World");
return MAIN_URL;
}
}
<file_sep>package com.cachet.web.bean.upload;
import com.cachet.web.bean.FileBean;
public class CertUpload {
//身份证正面
private FileBean idCardFrontFile;
//身份证反面
private FileBean idCardBackFile;
//警官证正面
private FileBean policeFrontFile;
//警官证反面
private FileBean policeBackFile;
//电子签名
private FileBean signatureFile;
//电子公章
private FileBean cachetFile;
public FileBean getIdCardFrontFile() {
return idCardFrontFile;
}
public void setIdCardFrontFile(FileBean idCardFrontFile) {
this.idCardFrontFile = idCardFrontFile;
}
public FileBean getIdCardBackFile() {
return idCardBackFile;
}
public void setIdCardBackFile(FileBean idCardBackFile) {
this.idCardBackFile = idCardBackFile;
}
public FileBean getPoliceFrontFile() {
return policeFrontFile;
}
public void setPoliceFrontFile(FileBean policeFrontFile) {
this.policeFrontFile = policeFrontFile;
}
public FileBean getPoliceBackFile() {
return policeBackFile;
}
public void setPoliceBackFile(FileBean policeBackFile) {
this.policeBackFile = policeBackFile;
}
public FileBean getSignatureFile() {
return signatureFile;
}
public void setSignatureFile(FileBean signatureFile) {
this.signatureFile = signatureFile;
}
public FileBean getCachetFile() {
return cachetFile;
}
public void setCachetFile(FileBean cachetFile) {
this.cachetFile = cachetFile;
}
}
<file_sep>使用框架:
Spring + Spring MVC + Hibernate + Bootstrap<file_sep>package com.cachet.web.controller;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cachet.common.bean.Result;
import com.cachet.common.properies.PropertiesItems;
import com.cachet.common.util.StringUtil;
import com.cachet.web.model.Cert;
import com.cachet.web.service.CertService;
@Controller
@RequestMapping("/cert")
public class CertController {
private Logger logger = Logger.getLogger(getClass());
//文件保存目录路径
public String uploadFilePath = "upload";
@Autowired
private CertService certService;
@Autowired
private PropertiesItems propertiesItems;
@RequestMapping(value = "/queryAll", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public @ResponseBody String queryAll() {
Result result = new Result();
result.setStatus(1);
List<Cert> certList = certService.findAll();
result.setData(certList);
String ss = JSONObject.fromObject(result).toString();
return ss;
}
@RequestMapping(value = "/load", method = RequestMethod.POST)
public @ResponseBody String load(int certId) {
Result result = new Result();
Cert cert = certService.get(certId);
if(cert != null){
result.setStatus(1);
result.setData(cert);
}else {
result.setStatus(0);
}
String ss = JSONObject.fromObject(result).toString();
return ss;
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public
@ResponseBody String upload(HttpServletRequest request,HttpServletResponse response) {
Result result = new Result();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String dateName = formatter.format(Calendar.getInstance().getTime());
//上传至项目部署路径下(Tomcat服务器)
String realPath = request.getServletContext().getRealPath("/");
String savePath = realPath + uploadFilePath + "/" + dateName;
//上传到本地磁盘或网络共享盘
// String savePath = propertiesItems.getImgPath() + "/" + dateName;
System.out.println("savePath = " + savePath);
//判断上传文件的保存目录是否存在
File saveDir = new File(savePath);
if(!saveDir.exists()){
saveDir.mkdirs();
}
String fileName = "", url1 = "", url2 = "";
Map<String, String> map = new HashMap<>();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);// 检查输入请求是否为multipart表单数据
if (isMultipart == true) { // 如果是二进制流形式的表单
logger.info("---上传证件开始---");
FileItemFactory factory = new DiskFileItemFactory();// 通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = null;
File savedFile=null;
try {
items = upload.parseRequest(request);
Iterator<FileItem> itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (!item.isFormField()) { //如果提交的是图片
if(StringUtil.isNotNullOrEmpty(item.getName())){
File fullFile = new File(item.getName()); //获取提交的文件
String originName = fullFile.getName();
fileName = rename(originName);
savedFile = new File(savePath, fileName);
if(StringUtil.equals(item.getName(), "blob")) {//获取截图路径
String fName = item.getFieldName();
if(StringUtil.equals(fName, "\'idCardBackFile\'") || StringUtil.equals(fName, "\'policeBackFile\'")) {
url2 = "/" + uploadFilePath + "/" + dateName + "/" + fileName;
}else {
url1 = "/" + uploadFilePath + "/" + dateName + "/" + fileName;
}
}
try {
item.write(savedFile); //写入文件
} catch (Exception e) {
logger.error("---上传证件失败---");
e.printStackTrace();
}
}
}else { //检测是否为普通表单 如果是普通表单项目,将其名字与对应的value值放入map中
try {
String fieldName = item.getFieldName();
map.put(fieldName, item.getString("UTF-8")); //获取表单value时确定数据格式,如果不写,有中文的话会乱码
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
logger.info("---上传证件结束---");
}
String certId = map.get("certId");
if(StringUtil.isNotNullOrEmpty(certId)) {
this.updateRecord(map, url1, url2);
}else {
this.saveRecord(map, url1, url2);
}
result.setStatus(1);
String ss = JSONObject.fromObject(result).toString();
return ss;
}
// public String uploadFile(String savePath, MultipartFile uploadFile){
// //文件名转换
// String originName = uploadFile.getName();
// String fileName = rename(originName);
// //文件所在的路径
// String source = savePath + "/" + fileName;
//
// try{
// logger.info("---上传证件开始---");
// InputStream inputStream = uploadFile.getInputStream();
// OutputStream outputStream = new FileOutputStream(new File(source));
//
// byte[] bt = new byte[1024];
// int len = 0;
// while ((len = inputStream.read(bt)) != -1) {
// outputStream.write(bt, 0, len);
// }
// // 关闭流
// outputStream.close();
// inputStream.close();
// logger.info("---上传证件结束---");
// }catch (IOException e){
// e.printStackTrace();
// logger.error("---上传证件失败---");
// }
//
// return fileName;
// }
public void saveRecord(Map<String, String> certMap, String url1, String url2){
Cert cert = new Cert();
cert.setCertName(certMap.get("certName"));
cert.setCertType(Integer.parseInt(certMap.get("certType")));
cert.setCertUrl1(url1);
cert.setCertUrl2(url2);
cert.setCreateTime(new Date());
cert.setScbz("0");
certService.saveCert(cert);
}
public void updateRecord(Map<String, String> certMap, String url1, String url2){
Cert record = certService.get(Integer.parseInt(certMap.get("certId")));
record.setCertName(certMap.get("certName"));
if(StringUtil.isNotNullOrEmpty(url1))
record.setCertUrl1(url1);
if(StringUtil.isNotNullOrEmpty(url2))
record.setCertUrl2(url2);
certService.updateCert(record);
}
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public @ResponseBody String delete(String certIds) {
Result result = new Result();
String[] ids = certIds.split(",");
if(ids != null && ids.length > 0){
for(String id: ids){
int certId = Integer.parseInt(id);
Cert cert = certService.get(certId);
certService.deleteCert(cert);
}
}
result.setStatus(1);
String ss = JSONObject.fromObject(result).toString();
return ss;
}
/*
* 将上传的文件进行重命名
*/
private static String rename(String name) {
Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
Long random = (long) (Math.random() * now);
String fileName = now + "" + random;
if (name.indexOf(".") != -1) {
fileName += name.substring(name.lastIndexOf("."));
}
return fileName;
}
}
| 7d271c46377d1a1fdb4b63e9f3173800bbbb3857 | [
"JavaScript",
"SQL",
"Java",
"Text"
] | 6 | JavaScript | tanbinh123/cachet2 | 4d4633ef4b280ddf8223936c92ced5e3945cb18e | f8c37162d0dbeb30ef33a4cf479a881f828d0fb6 | |
refs/heads/main | <repo_name>kyleb-herts/sentimental-analysis<file_sep>/sentimental-analysis-plot-scatter-group.py
#!/usr/bin/python
#this code uses examples from https://nealcaren.org/lessons/wordlists/
import pandas as pd
from afinn import Afinn
import matplotlib.pyplot as plt
from datetime import datetime
def get_month(text_string):
date = datetime.strptime(text_string, '%d/%m/%Y')
return date.month
afinn = Afinn(language='en', emoticons=True)
pd.set_option('display.max_rows', None)
data = pd.read_csv("reviews_pseudoanonymised.csv")
data['month'] = data['date'].apply(get_month)
data['afinn_score'] = data['comment'].apply(afinn.score)
d = {"month":data['month'].array, "score":data['afinn_score'].array}
df = pd.DataFrame(data=d)
dk = df.groupby('month').sum()
dk.plot.bar()
plt.show()
<file_sep>/sentimental-analysis-plot-scatter.py
#!/usr/bin/python
#this code uses examples from https://nealcaren.org/lessons/wordlists/
import pandas as pd
from afinn import Afinn
import matplotlib.pyplot as plt
def modify_helpful_value(text_string):
# NaN value reurn 1.0
if text_string != text_string:
return 1.0
else:
return text_string
afinn = Afinn(language='en', emoticons=True)
pd.set_option('display.max_rows', None)
data = pd.read_csv("reviews_pseudoanonymised.csv")
data['helpful'] = data['helpful'].apply(modify_helpful_value)
data['afinn_score'] = data['comment'].apply(afinn.score)
d = {"comment":data['afinn_score'].index.tolist(), "score":data['afinn_score'].array}
df = pd.DataFrame(data=d)
df.plot.scatter(x="comment", y="score")
plt.show()
d2 = {"comment":data['afinn_score'].index.tolist(), "helpful":data['helpful'].array}
df2 = pd.DataFrame(data=d2)
df2.plot.scatter(x="comment", y="helpful")
plt.show()
# df = pd.DataFrame({"x":keys, "score":values})
# ax = df.plot.scatter(x='x', y='score')
# plt.show()
# columns_to_display = ['comment', 'afinn_score']
# filtered_data = data.sort_values(by='afinn_score', ascending=False)[columns_to_display]
#print("\n")
#print(filtered_data)
#print("\n")
#print("Afinn Score From Comments Summary")
#print(data['afinn_score'].describe())
# filtered_data.to_csv('reviews_pseudoanonymised_afinn_score_applied.csv')
# data['afinn_score'].describe().to_csv('afinn_score_summary.csv')
# print("Sentiment Analyis completed - AFINN score applied")
<file_sep>/plot_chart.py
def add_chart():
print("hello_world")
<file_sep>/standard_deviation_graph.py
#this code uses examples from https://nealcaren.org/lessons/wordlists/
import pandas as pd
from afinn import Afinn
import matplotlib.pyplot as plt
from datetime import datetime
afinn = Afinn(language='en', emoticons=True)
pd.set_option('display.max_rows', None)
data = pd.read_csv("reviews_pseudoanonymised.csv")
data['afinn_score'] = data['comment'].apply(afinn.score)
#Sets up blank y_co_ords array
y_co_ords=[]
#Iterates over data in panda array and adds it to python array
for i in data['afinn_score']:
y_co_ords.append(i)
#Sorts the elements of the data into order
y_co_ords.sort()
#Sets minimum value as -14 (as this was established from previous analysis)
val=-14.0
#Array to be appended to depending on the frequency of each value
scores=[]
#Ready to store the x values of each score
x_values=[]
#Iterates 59 times due to range of scores that were established in previous analysis
for i in range(59):
#Adds the frequency of a score to the scores array
scores.append(y_co_ords.count(val))
#Adds the x value that is to be corresponding to that score
x_values.append(val)
#Increments the val by 1 every iteration
val=val+1
#Plots the frequency for the relevant scores
plt.scatter(x_values, scores)
#Labels the axes frequency and Score value
plt.xlabel('Score value', fontsize=18)
plt.ylabel('Frequency', fontsize=18)
#Displays the graph on the screen
plt.show()
<file_sep>/sentimental-analysis.py
#!/usr/bin/python
#this code uses examples from https://nealcaren.org/lessons/wordlists/
#import pandas an open source data analysis and manipulation tool - https://pandas.pydata.org/
import pandas as pd
#import afinn to utilise afinn wordlist for sentimental analysis - https://github.com/fnielsen/afinn
from afinn import Afinn
def modify_helpful_value(text_string):
# NaN value reurn 1.0
if text_string != text_string:
return 1.0
else:
return text_string
#set afinn language to English and enable afinn score of emoticons
afinn = Afinn(language='en', emoticons=True)
#in pandas set option to display all table rows
pd.set_option('display.max_rows', None)
#read data from provided csv file
data = pd.read_csv("reviews_pseudoanonymised.csv")
# Add the helpful column as the factor of the overall score
# if helpful column is nothing, return 1; otherwise, return original value
data['helpful'] = data['helpful'].apply(modify_helpful_value)
#apply afinn score to comments
data['afinn_score'] = data['comment'].apply(afinn.score)
#find word that match in afinn wordlist
data['afinn_triggers'] = data['comment'].apply(afinn.find_all)
#find scores of words matching afinn wordlist
data['afinn_trigger_words_scores'] = data['comment'].apply(afinn.scores_with_pattern)
#set column output to only be the comment and afinn score
columns_to_display = ['comment', 'afinn_score', 'afinn_triggers', 'afinn_trigger_words_scores']
#set rows to be sorted by afinn score
filtered_data = data.sort_values(by='afinn_score', ascending=False)[columns_to_display]
#set top 10 positive and top 10 negative comments as outputs
filtered_data_top_ten_positive = filtered_data.head(10)
filtered_data_top_ten_negative = filtered_data.sort_values(by='afinn_score', ascending=True).head(10)
#send outputs to terminal for testing
#print("\n")
#print(filtered_data)
#print("\n")
#print("Afinn Score From Comments Summary")
#print(data['afinn_score'].describe())
#print(filtered_data.head(10))
#print(filtered_data.sort_values(by='afinn_score', ascending=True).head(10))
#output data to csv files
filtered_data.to_csv('reviews_pseudoanonymised_afinn_score_applied.csv')
data['afinn_score'].describe().to_csv('afinn_score_summary.csv')
filtered_data_top_ten_positive.to_csv('afinn_score_top_ten_positive.csv')
filtered_data_top_ten_negative.to_csv('afinn_score_top_ten_negative.csv')
#notify user script has finished processing
print("Sentiment Analyis completed - AFINN score applied")
| 359fda54be8399127180057e85878dda4c3651f3 | [
"Python"
] | 5 | Python | kyleb-herts/sentimental-analysis | 330212c9ee360e288e348c27e2499e658ee42e69 | 241289a75fc404f0f156a43851fc4fdeb96c1b31 | |
refs/heads/master | <file_sep>class Snake {
constructor() {
this.verticalDirction = 0;
this.horizontalDirction = 0;
this.bodyLength = [];
this.bodyLength[0] = createVector(floor(w/2), floor(h/2));
this.tailLength = 0;
}
move(xDirection, yDirection) {
this.verticalDirction = xDirection;
this.horizontalDirction = yDirection;
}
update() {
let mouth = this.bodyLength[this.bodyLength.length-1].copy();
this.bodyLength.shift();
mouth.x += this.verticalDirction;
mouth.y += this.horizontalDirction;
this.bodyLength.push(mouth);
}
grow(){
let mouth = this.bodyLength[this.bodyLength.length-1].copy();
this.tailLength++;
this.bodyLength.push(mouth);
}
gameOver() {
if (this.bodyLength[0].x >= w || this.bodyLength[0].y >= h || this.bodyLength[0].x < 0 || this.bodyLength[0].y < 0) {
console.log('True');
return true;
}
else {
console.log('False');
return false;
}
}
eat(foodLocation) {
let snakeXLocation = this.bodyLength[this.bodyLength.length -1].x;
let snakeYLocation = this.bodyLength[this.bodyLength.length - 1].y;
if(snakeXLocation == foodLocation.x && snakeYLocation == foodLocation.y){
this.grow();
console.log('grow');
return true;
}else {
return false;
}
}
show() {
for(let i = 0; i < this.bodyLength.length; i++) {
fill(255);
noStroke();
rect(this.bodyLength[i].x, this.bodyLength[i].y, 1, 1);
}
}
}<file_sep>let snake;
let food;
let resolution = 30;
let w;
let h;
function setup()
{
let canvas = createCanvas(windowWidth - 16, windowHeight- 16);
canvas.style('display', 'block');
w = floor(width / resolution);
h = floor(height / resolution);
frameRate(5);
snake = new Snake();
createFood();
}
function createFood() {
let x = floor(random(w));
let y = floor(random(h));
food = createVector(x, y);
}
function keyPressed() {
if (keyCode === DOWN_ARROW) {
snake.move(0,1);
} else if (keyCode === UP_ARROW) {
snake.move(0,-1);
} else if (keyCode === RIGHT_ARROW) {
snake.move(1,0);
} else if (keyCode === LEFT_ARROW) {
snake.move(-1,0);
}else if (keyCode === ENTER) {
snake.move(0,0);
}
}
function draw()
{
scale(resolution);
background(0);
if(snake.eat(food)) {
snake.grow();
createFood();
}
snake.update();
snake.show();
if(snake.gameOver()){
print("Game Over");
background(255,0,255);
noLoop();
}
noStroke();
fill(255,0,255);
rect(food.x, food.y, 1, 1);
} | 839b04077f46a7d5832ad48c737d39947d5415c6 | [
"JavaScript"
] | 2 | JavaScript | Bcantrell1/snake-with-p5 | c08c619502abffa6c0bb43c3656bec422e8e52a0 | 9a9af0c2c2d2bc8f8bd4e2458291aa1b45cda6aa | |
refs/heads/master | <file_sep>package com.member.model;
import java.util.List;
import com.friendList.model.FriendListVO;
public class MemberService {
private MemberDAO_interface dao;
public MemberService() {
// dao = new MemberJBDCDAO();
dao = new MemberDAO();
}
public MemberVO addMember(String account, String password, String name, String idNumber, java.sql.Date birthDate, String phone,
String email, Integer memberState, byte[] memberPic, byte[] liscePic1, byte[] liscePic2, byte[] liscePic3,String lisceName1,String lisceName2,String lisceName3) {
MemberVO memberVO = new MemberVO();
memberVO.setAccount(account);
memberVO.setPassword(<PASSWORD>);
memberVO.setName(name);
memberVO.setIdNumber(idNumber);
memberVO.setBirthDate(birthDate);
memberVO.setPhone(phone);
memberVO.setEmail(email);
memberVO.setMemberState(memberState);
memberVO.setMemberPic(memberPic);
memberVO.setLiscePic1(liscePic1);
memberVO.setLiscePic2(liscePic2);
memberVO.setLiscePic3(liscePic3);
memberVO.setLisceName1(lisceName1);
memberVO.setLisceName2(lisceName2);
memberVO.setLisceName3(lisceName3);
dao.insert(memberVO);
return memberVO;
}
public MemberVO updateMmeber(Integer memberNo, String account, String password, String name, String idNumber, java.sql.Date birthDate, String phone,
String email, Integer memberState, byte[] memberPic, byte[] liscePic1, byte[] liscePic2, byte[] liscePic3,String lisceName1,String lisceName2,String lisceName3) {
MemberVO memberVO = new MemberVO();
memberVO.setMemberNo(memberNo);
memberVO.setAccount(account);
memberVO.setPassword(<PASSWORD>);
memberVO.setName(name);
memberVO.setIdNumber(idNumber);
memberVO.setBirthDate(birthDate);
memberVO.setPhone(phone);
memberVO.setEmail(email);
memberVO.setMemberState(memberState);
memberVO.setMemberPic(memberPic);
memberVO.setLiscePic1(liscePic1);
memberVO.setLiscePic2(liscePic2);
memberVO.setLiscePic3(liscePic3);
memberVO.setLisceName1(lisceName1);
memberVO.setLisceName2(lisceName2);
memberVO.setLisceName3(lisceName3);
dao.update(memberVO);
return memberVO;
}
// public void deleteMember(Integer memberNo) {
// dao.delete(memberNo);
// }
public MemberVO getOneMember(Integer memberNo) {
return dao.findByPrimaryKey(memberNo);
}
public List<MemberVO> getAllByName(String name) {
return dao.findByName(name);
}
public MemberVO getOneByEmail(String email) {
return dao.findByEmail(email);
}
public List<FriendListVO> getAllByNameForFreinds(Integer memNO, String name) {
return dao.findByNameForFreinds(memNO, name);
}
public List<MemberVO> getAll() {
return dao.getAll();
}
}
| 718bacb8e88318c79f11c46b572757156d27b11a | [
"Java"
] | 1 | Java | qzwse08252/CEA102G3_project | ddddf83c76ecc46393370bd9614a9c34a44f1002 | 29f9460579b777093cb343db23bdf83892b7e22a | |
refs/heads/master | <repo_name>qijuweni/WbuddyDemo<file_sep>/src/Salloc.cpp
/*************************************************************************
> File Name: Salloc.h
> Author: qijunwei
> Mail: <EMAIL>
> Created Time: Mon 12 Dec 2016 01:50:59 PM CST
************************************************************************/
#include "Salloc.h"
#include <string.h>
#include <stdlib.h>
SallocManager* Init(int orderNums, unsigned char **pSallocArray)
{
SallocManager *pSallocManager = (SallocManager*)malloc(sizeof(SallocManager));
pSallocManager->orderNums_ = orderNums;
pSallocManager->pSallocArray_ = pSallocArray;
return pSallocManager;
}
void SetBit(unsigned char *pChar, int bitIndex, bool bIsSet1 = true)
{
unsigned char mask = 1;
mask = mask << bitIndex;
if(bIsSet1 == true)
{
*pChar = (*pChar) | mask;
}
else
{
mask = ~mask;
*pChar = (*pChar) & mask;
}
}
void SetBits(unsigned char *pChar, int endBitIndex, bool bIsSet1 = true)
{
unsigned char mask = 1;
mask = (mask << (endBitIndex + 1)) - 1;
if(bIsSet1 == true)
{
*pChar = (*pChar) | mask;
}
else
{
unsigned char tmp = 0xff;
mask = tmp - mask;
*pChar = (*pChar) & mask;
}
}
int IsFirstParaMax(unsigned char *pFirst, unsigned char *pScend, int charNums)
{
for(int i = charNums - 1; i >= 0; i--)
{
if((unsigned char)pFirst[i] > (unsigned char)pScend[i])
return 1;
else if((unsigned char)pFirst[i] < (unsigned char)pScend[i])
return -1;
}
return 0;
}
void SetChunkAllocted(SallocManager *pSallocManager, int order, unsigned int chunkNumb, bool isAllocted, unsigned char *pSetSalloc)
{
unsigned char *pSalloc = pSallocManager->pSallocArray_[order];
int perChunkBits = order + 1;
int modByChar = perChunkBits % 8;
int perChunkSallocSpaceBytes = -1;
if(modByChar != 0)
perChunkSallocSpaceBytes = perChunkBits / 8 + 1;
else
perChunkSallocSpaceBytes = perChunkBits / 8;
unsigned long OffsetByChar = perChunkSallocSpaceBytes * chunkNumb;
unsigned char *pChunkSalloc = pSalloc + OffsetByChar;
unsigned int broChunkNumb = -1;
unsigned char *pBroChunkSalloc = NULL;
int result = -2;
if(order != pSallocManager->orderNums_ - 1)
{
broChunkNumb = (chunkNumb % 2) ? (chunkNumb - 1):(chunkNumb + 1);
OffsetByChar = broChunkNumb * perChunkSallocSpaceBytes;
pBroChunkSalloc = pSalloc + OffsetByChar;
result = IsFirstParaMax(pChunkSalloc, pBroChunkSalloc, perChunkSallocSpaceBytes);
}
if(pSetSalloc != NULL)
{
// strncpy(pChunkSalloc, pSetSalloc, pSetSallocLength);因为pSetSalloc 没多大,所以不必用函数
int pSetSallocLength = 0;
if((perChunkBits - 1) % 8 == 0)
pSetSallocLength = perChunkSallocSpaceBytes -1;
else
pSetSallocLength = perChunkSallocSpaceBytes;
if(pSetSalloc[pSetSallocLength - 1] == 0 )//意味着要修改最高位为1
{
if(pSetSallocLength == perChunkSallocSpaceBytes - 1)
{
if(isAllocted)
pChunkSalloc[perChunkSallocSpaceBytes - 1] = 1;
else
{
if(pChunkSalloc[perChunkSallocSpaceBytes -2] == 0)
pChunkSalloc[perChunkSallocSpaceBytes - 1] = 0;
}
}
else
{
int bitSetIndex = -1;
if(modByChar == 0)
bitSetIndex = 7;
else
bitSetIndex = modByChar - 1;
if(isAllocted)
SetBit(&pChunkSalloc[perChunkSallocSpaceBytes - 1], bitSetIndex, true);
else if(pChunkSalloc[perChunkSallocSpaceBytes - 1] == (1 << bitSetIndex))
SetBit(&pChunkSalloc[perChunkSallocSpaceBytes - 1], bitSetIndex, false);
}
}
for(int i = pSetSallocLength - 2; i >= 0; i--)
{
if(pChunkSalloc[i] == 0 && pSetSalloc[i] == 0)
{
break;
}
pChunkSalloc[i] = pSetSalloc[i];
}
if(pSetSallocLength == perChunkSallocSpaceBytes)
{
if(isAllocted)
{
pChunkSalloc[pSetSallocLength - 1] = (pChunkSalloc[pSetSallocLength - 1] | pSetSalloc[pSetSallocLength - 1]);//=的话会有bug
}
else
{
unsigned char mask = 1;
int tmp = 0;
if(modByChar == 0)
tmp = 7;
else
tmp = modByChar - 1;
mask = (unsigned char)0xff - ((mask << tmp) - 1);
pChunkSalloc[pSetSallocLength - 1] = (pChunkSalloc[pSetSallocLength - 1] & (pSetSalloc[pSetSallocLength - 1] | mask));//=的话会有bug
}
}
else
pChunkSalloc[pSetSallocLength - 1] = pSetSalloc[pSetSallocLength - 1];
}
else
{
int setCharNum = -1;
if(modByChar == 1)
{
if(isAllocted)
pChunkSalloc[perChunkSallocSpaceBytes - 1] = 1;
else
pChunkSalloc[perChunkSallocSpaceBytes - 1] = 0;
}
else
{
int bitSetIndex = -1;
if(modByChar == 0)
bitSetIndex = 7;
else
bitSetIndex = modByChar - 1;
if(isAllocted)
SetBits(&pChunkSalloc[perChunkSallocSpaceBytes - 1], bitSetIndex, true);
else
SetBits(&pChunkSalloc[perChunkSallocSpaceBytes - 1], bitSetIndex, false);
}
setCharNum = perChunkSallocSpaceBytes - 1;
for(int i = 0; i < setCharNum; i++)
{
if(isAllocted)
pChunkSalloc[i] = 0xff;
else
pChunkSalloc[i] = 0x0;
}
}
if(order != pSallocManager->orderNums_ - 1)
{
if(isAllocted)
{
if(result == -1 || (result == 0 && pBroChunkSalloc[perChunkSallocSpaceBytes - 1] == 0 ))
{
unsigned char *pUpSetChunk = pBroChunkSalloc;
if(result != 0 && pSetSalloc != NULL)
{
result = IsFirstParaMax(pChunkSalloc, pBroChunkSalloc, perChunkSallocSpaceBytes);
if(result == -1)
pUpSetChunk = pChunkSalloc;
}
SetChunkAllocted(pSallocManager, order + 1, chunkNumb / 2, isAllocted, pUpSetChunk);
}
}
else
{
if(result == 1)
{
result = IsFirstParaMax(pChunkSalloc, pBroChunkSalloc, perChunkSallocSpaceBytes);
if(result != 1)
{
if(!(result == 0 && (pBroChunkSalloc[perChunkSallocSpaceBytes - 1] != 0)))
SetChunkAllocted(pSallocManager, order + 1, chunkNumb / 2, isAllocted, pChunkSalloc);
}
}
else //我原来都比你小或者等于你,释放后肯定比你更小了
{
SetChunkAllocted(pSallocManager, order + 1, chunkNumb / 2, isAllocted, pChunkSalloc);
}
}
}
}
<file_sep>/include/Salloc.h
/*************************************************************************
> File Name: Salloc.h
> Author: qijunwei
> Mail: <EMAIL>
> Created Time: Mon 12 Dec 2016 01:50:59 PM CST
************************************************************************/
#ifndef SALLOC_H_
#define SALLOC_H_
#include "stdio.h"
struct SallocManager
{
int orderNums_;
unsigned char **pSallocArray_;
};
struct SallocManager* Init(int orderNums, unsigned char **pSallocArray);
void SetBit(unsigned char *pChar, int bitIndex, bool bIsSet1);
void SetBits(unsigned char *pChar, int endBitIndex, bool bIsSet1);
int IsFirstParaMax(unsigned char *pFirst, unsigned char *pScend, int charNums);
void SetChunkAllocted(SallocManager *pSallocManager, int order, unsigned int chunkNumb, bool isAllocted, unsigned char *pSetSalloc = NULL);
#endif
<file_sep>/test/SallocTester.c
/*************************************************************************
> File Name: SallocTester.c
> Author: qijunwei
> Mail: <EMAIL>
> Created Time: Mon 12 Dec 2016 10:45:11 PM CST
************************************************************************/
#include "stdio.h"
#include <gtest/gtest.h>
#include "Salloc.h"
#include <string.h>
#define PAGE_SIZE 4096
#define SPACE 4096 * 256 * 4 * 256
static struct SallocManager* SallocManagerForTest()
{
int MaxChunkNumb = SPACE / PAGE_SIZE;
int orderNums = 1;
int tmpChunkNumb = MaxChunkNumb;
while(tmpChunkNumb/2 != 0)
{
orderNums++;
tmpChunkNumb = tmpChunkNumb / 2;
}
unsigned char **pSallocArr = (unsigned char**)malloc(sizeof(char*) * orderNums);
for(int i = 0; i < orderNums; i++)
{
int bits = i + 1;
int perSallocSize = (bits % 8 ) ? bits / 8 + 1 : bits / 8;
pSallocArr[i] = (unsigned char*)malloc(perSallocSize * MaxChunkNumb);
memset(pSallocArr[i], 0, perSallocSize * MaxChunkNumb);
MaxChunkNumb = MaxChunkNumb / 2;
}
return Init(orderNums, pSallocArr);
}
//2^x个page时,则 orderNums = x + 1, 例如一个page对应的orderNum为1,对应的位向量为1位
static SallocManager* pManager = SallocManagerForTest();
TEST(Salloc, SetBit)
{
unsigned char a = 6;
SetBit(&a, 3, true);
EXPECT_EQ(a, 14);
unsigned char b = 0;
SetBit(&b, 0, true);
EXPECT_EQ(b, 1);
unsigned char c = 7;
SetBit(&c, 7, true);
EXPECT_EQ(c, (unsigned char)135);
unsigned char f = 2;
SetBit(&f, 0, true);
EXPECT_EQ(f, (unsigned char)3);
unsigned char d = 15;
SetBit(&d, 2, false );
EXPECT_EQ(d, 11);
unsigned char e = 255;
SetBit(&e, 7, false);
EXPECT_EQ(e,255 - 128);
unsigned char g = 255;
SetBit(&g, 0, false);
EXPECT_EQ(g, 255 - 1);
}
TEST(Salloc, SetBits)
{
unsigned char a = 6;
SetBits(&a, 3, true);
EXPECT_EQ(a, 15);
unsigned char b = 0;
SetBits(&b, 0, true);
EXPECT_EQ(b, 1);
unsigned char c = 7;
SetBits(&c, 7, true);
EXPECT_EQ(c, (unsigned char)255);
unsigned char d = 255;
SetBits(&d, 7, false);
EXPECT_EQ(d, 0);
unsigned char e = 23;
SetBits(&e, 2, false);
EXPECT_EQ(e, 16);
unsigned char f = 23;
SetBits(&f, 0, false);
EXPECT_EQ(f, 22);
unsigned char g = 22;
SetBits(&g, 0, true);
EXPECT_EQ(g, 23);
}
TEST(Salloc, IsFirstParaMax)
{
unsigned char a[2] = {0};
a[1] = (unsigned char)128 + 64;
unsigned char b[2] = {0};
b[1] = (unsigned char)128;
EXPECT_EQ(1,IsFirstParaMax(a, b, 2));
a[0] = 12;
b[0] = 8;
EXPECT_EQ(1,IsFirstParaMax(a, b, 1));
}
TEST(Salloc, SetChunkAllocted)
{
//这个test是在 SetChunkAllocted 没有加上递归修改功能的测试代码
/* SetChunkAllocted(pManager, 2, 3, true);
EXPECT_EQ(pManager->pSallocArray_[2][3], 7);
SetChunkAllocted(pManager, 0, 14, true);
EXPECT_EQ(pManager->pSallocArray_[0][14], 1);
SetChunkAllocted(pManager, 1, 5, true);
EXPECT_EQ(pManager->pSallocArray_[1][5], 3);
SetChunkAllocted(pManager, 3, 1, true);
EXPECT_EQ(pManager->pSallocArray_[3][1], 15);
SetChunkAllocted(pManager, 9, 0, true);//因为order9对应10bit的位向量,所以一个位向量占两个字节
EXPECT_EQ(pManager->pSallocArray_[9][1], 3);//下标越大,代表越高位的字节
EXPECT_EQ(pManager->pSallocArray_[9][0], (unsigned char)255);
SetChunkAllocted(pManager, 8, 1, true);//同上
EXPECT_EQ(pManager->pSallocArray_[8][3], 1);
EXPECT_EQ(pManager->pSallocArray_[8][2], (unsigned char)255);
SetChunkAllocted(pManager, 4, 5, true);//模拟的是order4的第6个组(下标为5)被用,然后第5个组可以用,这时候需要向上更新
SetChunkAllocted(pManager, 5, 2, &pManager->pSallocArray_[4][4]);
EXPECT_EQ(pManager->pSallocArray_[5][2], (unsigned char)32);
SetChunkAllocted(pManager, 10, 0, &pManager->pSallocArray_[9][2]);//模拟order为9的第一个组(下标为0,位向量占两个字节)被用了,第二组可用,向上更新
EXPECT_EQ(pManager->pSallocArray_[10][1], (unsigned char)4);
EXPECT_EQ(pManager->pSallocArray_[10][0], (unsigned char)0);
SetChunkAllocted(pManager, 7, 2, true);//模拟的是order7的第3个组(下标为2)被用,然后第4个组可以用,这时候需要向上更新
SetChunkAllocted(pManager, 8, 1, &pManager->pSallocArray_[7][3]);//为了走到if(pSetSallocLength == perChunkSallocSpaceBytes - 1)
EXPECT_EQ(pManager->pSallocArray_[8][3], (unsigned char)1);
EXPECT_EQ(pManager->pSallocArray_[8][2], (unsigned char)0);
*/
SallocManager *pSalloc = SallocManagerForTest();
SetChunkAllocted(pSalloc, 0, 0, true);
unsigned char value = 1;
int num = pSalloc->orderNums_;
for(int i = 0; i < 8; i++)
{
if( i >= num )
break;
EXPECT_EQ(pSalloc->pSallocArray_[i][0], (unsigned char)value);
value *= 2;
}
value = 1;
for(int i = 8; i < 16; i++)
{
if( i >= num )
break;
EXPECT_EQ(pSalloc->pSallocArray_[i][1], (unsigned char)value);
EXPECT_EQ(pSalloc->pSallocArray_[i][0], (unsigned char)0);
value *= 2;
}
value = 1;
for(int i = 16; i < 24; i++)
{
if( i >= num )
break;
EXPECT_EQ(pSalloc->pSallocArray_[i][2], (unsigned char)value);
EXPECT_EQ(pSalloc->pSallocArray_[i][1], (unsigned char)0);
EXPECT_EQ(pSalloc->pSallocArray_[i][0], (unsigned char)0);
value *= 2;
}
printf("ordr num is %d\n", num);
SetChunkAllocted(pSalloc, 2, 1, true);
EXPECT_EQ(pSalloc->pSallocArray_[3][0], (unsigned char)12);
EXPECT_EQ(pSalloc->pSallocArray_[4][0], (unsigned char)16);
/*
SetChunkAllocted(pSalloc, 3, 1, true);
EXPECT_EQ(pSalloc->pSallocArray_[4][0], (unsigned char)28);
EXPECT_EQ(pSalloc->pSallocArray_[5][0], (unsigned char)32);
*/
SetChunkAllocted(pSalloc, 2, 2, true);
EXPECT_EQ(pSalloc->pSallocArray_[3][1], (unsigned char)8);
EXPECT_EQ(pSalloc->pSallocArray_[4][0], (unsigned char)24);
SetChunkAllocted(pSalloc, 4, 1, true);
EXPECT_EQ(pSalloc->pSallocArray_[5][0], (unsigned char)56);
EXPECT_EQ(pSalloc->pSallocArray_[6][0], (unsigned char)64);
SetChunkAllocted(pSalloc, 7, 1, true);
EXPECT_EQ(pSalloc->pSallocArray_[8][0], (unsigned char)128);
EXPECT_EQ(pSalloc->pSallocArray_[8][1], (unsigned char)1);
/* SetChunkAllocted(pSalloc, 7, 3, true);
EXPECT_EQ(pSalloc->pSallocArray_[8][3], (unsigned char)1);
EXPECT_EQ(pSalloc->pSallocArray_[8][2], (unsigned char)0);
EXPECT_EQ(pSalloc->pSallocArray_[9][1], (unsigned char)3);
*/
SetChunkAllocted(pSalloc, 8, 1, true);
EXPECT_EQ(pSalloc->pSallocArray_[9][0], (unsigned char)128);
EXPECT_EQ(pSalloc->pSallocArray_[9][1], (unsigned char)3);
SetChunkAllocted(pSalloc, 0, 0, false);
EXPECT_EQ(pSalloc->pSallocArray_[0][0], (unsigned char)0);
EXPECT_EQ(pSalloc->pSallocArray_[1][0], (unsigned char)0);
EXPECT_EQ(pSalloc->pSallocArray_[2][0], (unsigned char)0);
EXPECT_EQ(pSalloc->pSallocArray_[3][0], (unsigned char)8);
EXPECT_EQ(pSalloc->pSallocArray_[4][0], (unsigned char)24);
EXPECT_EQ(pSalloc->pSallocArray_[5][0], (unsigned char)56);
SetChunkAllocted(pSalloc, 2, 1, false);
EXPECT_EQ(pSalloc->pSallocArray_[0][0], (unsigned char)0);
EXPECT_EQ(pSalloc->pSallocArray_[4][0], (unsigned char)16);
EXPECT_EQ(pSalloc->pSallocArray_[5][0], (unsigned char)48);
EXPECT_EQ(pSalloc->pSallocArray_[6][0], (unsigned char)64);
SetChunkAllocted(pSalloc, 7, 1, false);
EXPECT_EQ(pSalloc->pSallocArray_[8][0], (unsigned char)0);
EXPECT_EQ(pSalloc->pSallocArray_[8][1], (unsigned char)1);
EXPECT_EQ(pSalloc->pSallocArray_[9][0], (unsigned char)0);
SetChunkAllocted(pSalloc, 8, 1, false);
EXPECT_EQ(pSalloc->pSallocArray_[9][0], (unsigned char)0);
EXPECT_EQ(pSalloc->pSallocArray_[9][1], (unsigned char)2);
EXPECT_EQ(pSalloc->pSallocArray_[10][1], (unsigned char)4);
EXPECT_EQ(pSalloc->pSallocArray_[4][0], (unsigned char)16);
SetChunkAllocted(pSalloc, 2, 2, false);
EXPECT_EQ(pSalloc->pSallocArray_[3][0], (unsigned char)0);
EXPECT_EQ(pSalloc->pSallocArray_[3][1], (unsigned char)0);
EXPECT_EQ(pSalloc->pSallocArray_[4][0], (unsigned char)0);
EXPECT_EQ(pSalloc->pSallocArray_[5][0], (unsigned char)32);
SetChunkAllocted(pSalloc, 4, 1, false);
for(int i = 0; i < pSalloc->orderNums_ ; i++)
{
EXPECT_EQ(pSalloc->pSallocArray_[i][0], (unsigned char)0);
}
}
<file_sep>/include/CLChunkGroup.h
/*************************************************************************
> File Name: ChunkGroup.h
> Author: qijunwei
> Mail: <EMAIL>
> Created Time: Sun 11 Dec 2016 06:44:13 PM CST
************************************************************************/
#ifndef CHUNKGROUP_H_
#define CHUNKGROUP_H_
class ChunkGroup
{
public:
ChunkGroup(int order, unsigned int chunkNum);
~ChunkGroup();
unsigned int GetChunk();
private:
unsigned int *pulArrayOfChunkUsedCount;
char *pcGroupSalloc;
}
#endif
<file_sep>/include/ChunkGroup.h
/*************************************************************************
> File Name: ChunkGroup.h
> Author: qijunwei
> Mail: <EMAIL>
> Created Time: Sun 11 Dec 2016 07:24:35 PM CST
************************************************************************/
#ifndef CHUNKGROUP_H_
#define CHUNKGROUP_H_
struct ChunkGroup
{
unsigned int *pulArrayOfChunkUsedCount;
char *pcGroupSalloc;
int order;
unsigned int chunkNum;
};
ChunkGroup* InitChunkGroup(int order, unsigned int chunkNum);
unsigned int GetFitChunkNumbInBuddyChunks(ChunkGroup *pChunkGroup, unsigned int beginChunkNumb,int wantedOrder);
void SetChunkUesd(ChunkGroup *pChunkGroup, unsigned int ChunkNumb);
#endif
<file_sep>/test/CMakeLists.txt
PROJECT(main)
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
set(CMAKE_C_COMPILER "g++")
include_directories( ../include /home/qijunwei/googletest/googletest/include)
add_definitions(-g)
#link_directories(../lib/gtest-1.7.0)
AUX_SOURCE_DIRECTORY(. dir_srcs)
aux_source_directory(../src dir_srcs)
#option (cover_test "cover_test build" ON)
#if(cover_test)
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage")
#endif()
#OPTION (ENABLE_COVERAGE "Use gcov" ON)
#MESSAGE(STATUS ENABLE_COVERAGE=${ENABLE_COVERAGE})
#IF(ENABLE_COVERAGE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage")
#ENDIF()
add_executable(main ${dir_srcs})
#target_compile_options(main PRIVATE -fprofile-arcs -ftest-coverage)
#这句话必须放在add_executable的后面
target_link_libraries(main libgtest.a libgtest_main.a pthread)
| 99d42dfdbecff717e0db323b4f1b8a55f2926dd7 | [
"C",
"CMake",
"C++"
] | 6 | C++ | qijuweni/WbuddyDemo | cbeb7eb1d32a876ebfb7d3637e901585f8a7dcb7 | a66403e793417e2243a1d12a4c23b511c91b3521 | |
refs/heads/master | <repo_name>blankyao/omniauth-qq<file_sep>/lib/omniauth-qq/version.rb
module OmniAuth
module Qq
VERSION = "0.1.0"
end
end
<file_sep>/README.md
OmniAuth-Qq
===
为omniauth实现的 [QQ登录](http://connect.qq.com/intro/login/) 策略
Basic Usage
---
In your Gemfile:
```ruby
gem 'omniauth-qq', :git => 'git://github.com/blankyao/omniauth-qq.git'
```
A sample app:
```ruby
# encoding: utf-8
require 'sinatra'
require 'omniauth-qq'
use Rack::Session::Cookie
use OmniAuth::Builder do
provider :qq, ENV['APP_KEY'], ENV['APP_SECRET']
end
get '/' do
<<-HTML
<a href="/auth/qq">Login Using QQ</a>
HTML
end
get '/auth/qq/callback' do
auth = request.env['omniauth.auth']
<<-HTML
<ul>
<li>qq_openid: #{auth.uid}</li>
<li>nickname: #{auth.info.nickname}</li>
<li>gender: #{auth.info.gender}</li>
<li>avatar: <img src="#{auth.info.avatar}"/></li>
</ul>
HTML
end
``` | c15de639b0e392dcf9392d6f213d9b9f7d4d3afe | [
"Markdown",
"Ruby"
] | 2 | Ruby | blankyao/omniauth-qq | dc08e9161ac39ecd88263861e7fa850c4c6a68a2 | 39ef982e1051aa17af1a8f0900c2a840da5b64ed | |
refs/heads/master | <file_sep>console(-1 >>> 1)
if( file("hiragana.res", 0) != 1 ){
console("Could not find resources!");
exit();
}
const list = [
"a","e","i","o","u","n",
"chi","fu","ha","he","hi","ho",
"ka","ke","ki","ko","ku","ma",
"me","mi","mo","mu","na","ne",
"ni","no","nu","ra","re","ri",
"ro","ru","sa","se","shi","so",
"su","ta","te","to","tsu","wa",
"we","wo","ya","yo","yu","ba",
"be","bi","bo","bu","da","de",
"do","ga","ge","gi","go","gu",
"ja","ji","jo","ju","pa","pe",
"pi","po","pu","za","ze","zo",
"zu","bya","byo","byu","cha",
"cho","chu","gya","gyo","gyu",
"hya","hyo","hyu","kya","kyo",
"kyu","mya","myo","myu","nya",
"nyo","nyu","pya","pyo","pyu",
"rya","ryo","ryu","sha","sho",
"shu"
];
const UI = file("interface", 0);
const heart = builtin("sHeart");
const rightEmote = builtin("happyEmote");
const wrongEmote = builtin("dohEmote");
const boredEmote = builtin("boredEmote");
const words = [0,0,0,0];
var X;
var Y;
var stateTime = 0;
var level = 0;
var streak = 0;
var score = 0;
var maxStreak = 0;
var num = 0;
var img = null;
var state = nop;
var nextState = null;
var emote = rightEmote;
var lives = 3;
const spriteX = 80;
const spriteY = 16;
const waitColor = 23;
const rightColor = 7;
const wrongColor = 175;
var bgColor = 17;
var uiColor = 18;
var spriteColor = bgColor;
var targetColor = waitColor;
fill(bgColor);
color(10);
pick();
function nop(){}
function pick(){
if((lives < 0) || !UI)
exit();
var newnum = random(0, level);
if(newnum == num) newnum = random(0, level);
num = newnum;
img = file(list[num], img);
for(var i in words){
words[i] = random(0, level);
}
words[random(0, 4)] = num;
targetColor = waitColor;
state = tween;
nextState = waitForInput;
stateTime = 0;
}
function wrongFeedback(){
if(stateTime == 0) stateTime = 60;
else if(--stateTime == 0){
targetColor = bgColor;
nextState = pick;
state = tween;
}
color(172);
if(words[0] == num){
cursor(25 + 2, 25 + 4);
print(list[words[0]]);
}
if(words[1] == num){
cursor(25 + 2, 73 + 4);
print(list[words[1]]);
}
if(words[2] == num){
cursor(5 + 2, 49 + 4);
print(list[words[2]]);
}
if(words[3] == num){
cursor(44 + 2, 49 + 4);
print(list[words[3]]);
}
}
function makeChoice(choice){
if((choice != 4) && (words[choice] == num)){
if(++level > length(list)) level = length(list) - 1;
if(++streak > maxStreak){
emote = rightEmote;
}
score += streak + 1;
highscore(score);
nextState = pick;
state = tween;
targetColor = bgColor;
io("OVERDRIVE", 0);
io("VOLUME", 128);
io("DURATION", 100);
sound(44);
}else{
io("OVERDRIVE", 1);
io("VOLUME", 255);
io("DURATION", 750);
sound(20);
--lives;
level -= 4;
if(level < 0) level = 0;
streak = 0;
targetColor = wrongColor;
nextState = wrongFeedback;
state = tween;
stateTime = 0;
emote = boredEmote;
}
}
function waitForInput(){
var choice = -1;
if(stateTime == 0) stateTime = 60;
else if(--stateTime == 0) choice = 4;
if(justPressed("UP")){
choice = 0;
} else if(justPressed("DOWN")){
choice = 1;
} else if(justPressed("LEFT")){
choice = 2;
} else if(justPressed("RIGHT")){
choice = 3;
}
if(justPressed("B")){
uiColor = 12;
bgColor = 10;
level = length(list);
}
if(pressed("C"))
exit();
if(choice > -1){
makeChoice(choice);
} else {
color(22);
cursor(25 + 2, 25 + 4);
print(list[words[0]]);
cursor(25 + 2, 73 + 4);
print(list[words[1]]);
cursor(5 + 2, 49 + 4);
print(list[words[2]]);
cursor(44 + 2, 49 + 4);
print(list[words[3]]);
}
}
function tween(){
var block = spriteColor >> 3;
var lum = spriteColor & 7;
var tblock = targetColor >> 3;
var tlum = targetColor & 7;
if(block != tblock){
if(lum > 0) --spriteColor;
else spriteColor = tblock << 3;
} else {
if(lum < tlum) ++spriteColor;
else if(lum == tlum) state = nextState;
else --spriteColor;
}
}
function update(){
color(uiColor - 7);
sprite(0, 0, UI);
if(emote == wrongEmote)
color(91);
else
color(0);
sprite(96, 146, emote);
cursor(116, 148);
color(22);
printNumber(score);
state();
color(spriteColor - 7);
sprite(spriteX, spriteY, img);
color(0);
for(var i = 0; i<lives; ++i){
sprite(84 + (i * 8), 20, heart);
}
}
<file_sep>
const abilities = file("save/abilities", 0);
const choices = [4];
const prefixes = [" \n ", " \n->"];
var roll;
var abilityPoints;
var choice = 0;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
function f_goto(page, caption){
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print("Rolled ");
print(roll);
print("+");
print(abilityPoints);
print(". ");
print(caption);
exec(page);
}
function success(ability){
f_goto("Book1/562.js", "Success!");return;
}
function fail(){
f_goto("Book1/438.js", "Failure!");return;
}
function update(){
cursor(0,0);
print("Make a SCOUTING roll at a difficulty of 12");
print(prefixes[choice == 0]); print(" scouting: "); print(abilities[4]);
cursor(15, 10);
print(" ");
cursor(15, 10);
roll = random(2, 13);
print(roll);
choice = max(0, min(0, choice + justPressed("DOWN") - justPressed("UP")));
if(!justPressed("A"))
return;
var ability = choices[ choice ];
abilityPoints = abilities[ ability ];
if((roll + abilityPoints) >= 12){
success(ability);
} else {
fail();
}
}
<file_sep>save("save/bookmark", "Book1/546.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
With a heroic effort, you manage
to get to the woman. Gathering her
up, you run for the door, and
stagger out into the cool night
air, smoke and flame licking at
your heels. The townsfolk give you
a rousing cheer and the girl
thanks you effusively for saving
her mother.
Later, it transpires that the
woman is actually a powerful
sorceress whose experiments in
fire magic went slightly wrong.
Her name is <NAME>
and she gives you a gift - a pale
moonstone. Note _ The War-Torn
Kingdom _ , * 650 *`,
GOTO,
"Book1/650.js",
`go to 650`,
`on`,
MARK,
`your Adventure Sheet.
Elissia tells that you can use
the moonstone by rubbing it, and
you will be instantly teleported
to the vicinity of the sunstone -
which she carries on a necklace.
'I will be here in Marlock City.
Whenever you are desperate, at the
end of your tether, or just want
to get here fast, use the
moonstone and you will appear
beside me. I will do everything in
my power to aid you, and then my
debt to you will be repaid.'
Whenever you want to use the
moonstone, turn to * 650 * in this
book. Now`,
GOTO,
"Book1/100.js",
`go to 100`,
`.`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep>save("save/bookmark", "Book1/454.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
If there is a tick in the box,`,
GOTO,
"Book1/188.js",
`go
to 188`,
`. If not, and read on.
You are thrown into a stinking
prison cell. Your cell-mate, a
half-dead old man with long white
hair tells you his tale: 'The lair
of the gorlock! A hideous beast
that has backward-pointing feet -
Krine and I, fleeing with our
stolen treasure sought refuge in
the cave near Blessed Springs. The
tracks led us to believe it had
just left its cave, but we didn't
know about its feet - in fact it
was at home. It took Krine but I
managed to escape with my life,
only to be taken by the militia. I`,
MARK,
`will never live to see the
treasure but you, forewarned, may
defeat the gorlock and take the
riches it guards...'
Gain the codeword Apache .
A few days later, you learn your
own fate. You are to be sold into
slavery, and taken to <NAME>
to work in the tin mines.`,
GOTO,
"Book1/118.js",
`go to
118`,
`.`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep>if ( file("images.res", 0) != 1 ){
console("Could not find resources!");
exit();
}
var playerY1 = 150;
var score1 = 0;
var playerY2 = 150;
var score2 = 0;
var Chicken1Anim = 0;
// CHANGED
const CAR_IDX = 8;
const PLAYER1_IDX = 1;
const PLAYER2_IDX = 2;
const vCars = 4;//each car has 4 varialbes
const nCars = 12;
const cCars = vCars * nCars;// we have 12 cars and each car has 4 variables each (x, y, speed, type, show)
var tCars = Array( cCars );
//var carLength = [32, 32, 64];
//initialize cars
for(var carid = 0; carid < nCars; carid++) {
var i = carid * vCars; //determine the starting index in array for target car
var lane = carid / 2;
var speed = random(2, 5);
var offset = 0;
if (carid % 2 == 1) {
offset = 150;
}
else {
offset = 0;
}
if (carid < 6) {
tCars[i] = 0 - offset;
tCars[i+1] = 22 +(lane * 21);//set Car (cardid) Y coordinate - 22,43,64
tCars[i+2] = -speed;//set Car (cardid) XSPEED
}
else {
tCars[i] = 220 + offset;
tCars[i+1] = 92 + ((lane-3) * 21);//set Car (cardid) Y coordinate - 92,113,134
tCars[i+2] = speed;//set Car (cardid) XSPEED
}
// console( tCars[i]);
tCars[i+3] = random(1, 3); //show
}
var start = time()
const StreetBG = file("StreetBG", 0);
const carImages =
[
file("FreewayCar2", 0), // Red car
file("FreewayCar1", 0), // Green car
file("FreewayCar3", 0) // Truck
];
const playerOne = file("FreewayChicken_F1", 0);
const playerOneF2 = file("FreewayChicken_F2", 0);
const playerTwo = file("FreewayChicken2_F1", 0);
const playerTwoF2 = file("FreewayChicken2_F2", 0);
const Chicken1box = file("Chicken1box", 0);
const Chicken2box = file("Chicken2box", 0);
function reset() {
start = time();
playerY1 = 150;
score1 = 0;
playerY2 = 150;
score2 = 0;
}
function waitForInput()
{
// Player One Input
if ((pressed("UP")) && (playerY1 > 0)) playerY1-=2;
if ((pressed("DOWN")) && (playerY1 < 150)) playerY1+=2;
// Player Two Input
if ((pressed("A")) && (playerY2 > 0)) playerY2-=2;
if ((pressed("B")) && (playerY2 < 150)) playerY2+=2;
if (pressed("C")) exit();
}
// CHANGED
function collide(carIdx, playerIdx)
{
if (playerIdx == 1) { music("pouletjade.raw"); playerY1 = 150}
if (playerIdx == 2) { music("pouletpapa.raw"); playerY2 = 150}
}
function background()
{
for( var x = 0; x < 220; x+=30 ) { sprite(x, 0, StreetBG); }
}
function scoreDisplay()
{
color(7);
cursor(15,5)
print(score1);
cursor(200,5)
print(score2);
color(0);
}
function playerRender()
{
io("COLLISION", PLAYER1_IDX, CAR_IDX, collide);
sprite(50, playerY1 + 6, Chicken1box);
Chicken1Anim++;
if((Chicken1Anim/3)%2==0) {
sprite(50, playerY1, playerOne);
}
else {
sprite(50, playerY1, playerOneF2);
}
io("COLLISION", PLAYER2_IDX, CAR_IDX, collide);
sprite(150, playerY2 + 6, Chicken2box);
//Chicken1Anim++;
if((Chicken1Anim/3)%2==0)
sprite(150, playerY2, playerTwo);
else
sprite(150, playerY2, playerTwoF2);
//sprite(150, playerY2, playerTwo);
}
function updateCars(){
for( var carid = 0; carid < nCars; carid++ ) {
var i = carid * vCars;//determine the starting index in array for target car
var offset = -4;
if (carid % 2 == 0) {
offset = 4;
}
else {
offset = -4;
}
var otherCarX = tCars[i + offset];
var x = tCars[i] + tCars[i+2];
if (tCars[i+2] > 0) {//car is moving to the right
if (x + 80 < otherCarX || otherCarX < x) {
tCars[i] = x; //move target cars x coordinate by the cars speed
}
else {
tCars[i] = otherCarX - 80;
}
launchCar_Right(i, offset);
}
if (tCars[i+2] < 0) { //car must be moving left
if (x - 80 > otherCarX || otherCarX > x) {
tCars[i] = x; //move target cars x coordinate by the cars speed
}
else {
tCars[i] = otherCarX + 80;
}
launchCar_Left(i, offset);
}
}
}
function launchCar_Right(i, offset) {
if(tCars[i] > 220) {//car i x coordinate is greater than right edge of screen
tCars[i] = tCars[i + offset] - 250;
tCars[i+2] = random(2, 5);// set car speed to a random number between 2 and 4
tCars[i+3] = random(1, 4);// set car type to a random number between 1 and 3
}
}
function launchCar_Left(i, offset) {
if(tCars[i] < -64){
tCars[i] = tCars[i + offset] + 250;
tCars[i+2] = -random(2, 5);// set car speed to a random number between 2 and 4 negative
tCars[i+3] = random(1, 4);// set car type to a random number between 1 and 3
}
}
function carRender() {
for( var carid = 0; carid < nCars; carid++) {
var i = carid * vCars;//determine the starting index in array for target car
if(tCars[i+2]>0){//car is moving to the right
mirror( false );
}
else {
mirror( true );
}
io("COLLISION", CAR_IDX, 0); // CHANGED
var carType = tCars[i+3] - 1;
sprite(tCars[i], tCars[i+1], carImages[carType]);
}
}
function checkForPoint() {
if (playerY1 <= 0) {
score1 +=1;
playerY1 = 150;
playSound();
}
if (playerY2 <= 0) {
score2 +=1;
playerY2 = 150;
playSound();
}
}
function playSound() {
io("VOLUME", 127);
io("DURATION", 70);
sound(random(44, 47));
}
function gameOver() {
highscore(max(score1, score2))
background();
updateCars();
carRender();
color(7);
if (score1 > score2) {
cursor(55,75);
print("PLAYER 1 WINS!")
}
else if (score1 == score2) {
cursor(45,75);
print("IT'S A TIED GAME!")
}
else {
cursor(55,75);
print("PLAYER 2 WINS!")
}
cursor(15,95);
print("B TO RESTART / C TO EXIT")
color(0);
if (timeSinceStart >=60) timeSinceStart = 60;
if (pressed("C")) exit();
if (justPressed("B")) reset();
}
function update() {
var timeSinceStart = (time() - start) / 1000;
if(timeSinceStart >= 60) {
gameOver();
}
else {
checkForPoint();
waitForInput();
background();
updateCars();
carRender();
playerRender();
color(175); cursor(105,5); print(60 - timeSinceStart); //color(0);
}
scoreDisplay();
} <file_sep>save("save/bookmark", "Book1/166.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
You are on the road between
Marlock City and the Shadar Tor.
Along most of the length of the
road, a thin sliver of a shanty
town has grown up. Tents and
lean-to's line the way. You find
out that the people living here
are refugees from Trefoille. The
city was burnt to the ground
during the recent civil war, in
which the old king was overthrown.
Roll a die . A pick-pocket! You
lose 10 Shards Nothing happens You
find a by the side of the road
When you are finished, you can:
`,
GOTO,
"Book1/100.js",
`Go to Marlock City`,
`
`,
GOTO,
"Book1/35.js",
`Head for the Shadar Tor`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep>save("save/bookmark", "Book1/427.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
If you have the codeword Attar,`,
GOTO,
"Book1/578.js",
`
go to 578`,
`immediately. If not, read
on.
Venefax is a strange-looking
village. It looks like a single
gigantic building. All the houses
are joined together to form a
jumbled mass, and none of the
houses have doors - the only way
in is through holes in the
rooftop. Ladders lead up to the
roof, which in effect forms a
network of streets that the
inhabitants travel across to get
to certain buildings.
'We had to build it that way, for`,
MARK,
`defence,' says a passing farmer.
'You see, the scorpion men from
the south cannot climb, so they
can't get inside the town!'
`,
GOTO,
"Book1/152.js",
`Visit the market`,
`
`,
GOTO,
"Book1/497.js",
`Visit the Scorpion's Sting
Tavern`,
`
`,
GOTO,
"Book1/338.js",
`Visit the village healer`,
`
`,
GOTO,
"Book1/63.js",
`Chat to villagers on the rooftop`,
`
`,
GOTO,
"Book1/492.js",
`Go south into Scorpion Bight`,
`
`,
GOTO,
"Book1/87.js",
`Take the road north to Blessed
Springs`,
`
`,
GOTO,
"Book1/621.js",
`South west on the road to
Yellowport`,
`
`,
GOTO,
"Book1/278.js",
`North into open countryside`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep># LoveRush-Pine2k
Pine2K version of Love Rush for Pokitto
<file_sep>save("save/bookmark", "Book1/637.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
Somehow you manage to evade the
creature's jaws, and swim back to
shore. Hauling yourself up on to
the beach, you are assaulted by an
angry villager.
'Where's my boat?' he cries,
'You've sunk it, haven't you? You
city types don't know a thing!
Well, you'll have to pay me back -
fifty Shards at least!'
'Hah!' you reply, 'The cost of
hiring it was more than its worth
in any case. As far as I'm
concerned, that boat was mine to
do with as I liked!'
`,
MARK,
` The argument goes on all the way
back to the village but eventually
the fisherman gives up and storms
off.
`,
GOTO,
"Book1/135.js",
`go to 135`,
`.`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep>autoAccelerate true
name Player
pod 0
color 5
<file_sep>save("save/bookmark", "Book1/122.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
If you have the codeword Acid,`,
GOTO,
"Book1/543.js",
`go
to 543`,
`immediately. If not, but
you have a * copper amulet * ,`,
GOTO,
"Book1/384.js",
`go
to 384`,
`immediately. Otherwise,
read on.
Guildmaster Vernon of Yellowport
is surprisingly eager to see you.
He is a hugely fat and bejewelled
merchant, and he tells you that a
group of ratmen have made a base
in the sewers beneath the city.
They come out at night to raid the
warehouses and homes of the
merchants of Yellowport.
'We need an adventurer like
yourself to destroy their king,'`,
MARK,
`explains the guildmaster. 'Without
him, the ratmen wouldn't be able
to organize a feast in a larder.
We will pay you 450 Shards if you
succeed.'
Vernon tells you that the sewers
can be entered via an old disused
well in the poor quarter.
Whenever you are ready to enter
the sewers, and you are in
Yellowport, turn to * 460 * .`,
GOTO,
"Book1/460.js",
`Note
this option`,
`on your Adventure
Sheet. Now you can return to the
city centre,`,
GOTO,
"Book1/10.js",
`go to 10`,
`, or`,
GOTO,
"Book1/460.js",
`go down
the sewers straight away`,
`.`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep>save("save/bookmark", "Book1/596.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
You thread your way through the
ranks of trees. In places, the
forest canopy almost blocks out
the sunlight completely, and you
are wandering in deep shadow,
haunted by the cries of the
creatures of the forest. If you
have an * oak staff * ,`,
GOTO,
"Book1/653.js",
`go to 653`,
`
immediately. If not, read on.
You hack your way through the
undergrowth until you stumble
across an old ruin. Creepers, and
forest moss have grown over most
of it, but you can see mask-like
faces set into the walls, glaring
down at you as if in angry outrage
at your intrusion. You come to a`,
MARK,
`massive stone slab - clearly a
door. Set into the middle of it is
a round, granite face, the visage
of a sleeping demon. Suddenly, an
eye pops open, and regards you
curiously.
'By the Tentacles of Tantallon!'
exclaims the face in a gravelly
voice. 'A human! I haven't seen
one of you lot for a hundred
years.' An expression of suspicion
forms on its rocky features. 'What
do you want, anyway?'
'Just passing through,' you
comment airily.
'Well you can't pass through me
unless you know the password. And`,
MARK,
`that was given to me by Astrallus
the Wizard King, umm... let me
see, now... a thousand years ago,
by Ebron! This is his tomb, you
know.'
If you have the codeword Crag,`,
GOTO,
"Book1/160.js",
`go
to 160`,
`. Otherwise, read on.
'How do I find the password
then?' you ask.
'Well,' says the demon door,
'Astrallus was a wizard, so why
don't you ask some wizards?'
'Where would I find some
wizards?' you ask.
'How would I know?' replies the`,
MARK,
`door testily. 'I've been stuck
here for a thousand years!'
You decide it is time to leave.
`,
GOTO,
"Book1/110.js",
`North to the Bronze Hills`,
`
`,
GOTO,
"Book1/333.js",
`West to the River Grimm`,
`
`,
GOTO,
"Book1/560.js",
`South into the country`,
`
`,
GOTO,
"Book1/387.js",
`East to the road`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep>const minX = 6, maxX = 22;
const minY = 0, maxY = 20;
const boardWidth = maxX - minX;
const boardHeight = maxY - minY;
const heart = builtin("sHeart");
const lvl = builtin("sLvl");
const pts = builtin("sPts");
const ledOFF = builtin("shape2");
const ledON = builtin("sBtn");
const snakeColor = 112;
const bgColor = 113;
const appleColor = 87;
const maxLen = 100;
var snake = new Array(maxLen);
var begin;
var end;
var currentLen;
var len;
var x, y, vx, vy, ax, ay;
var dead, won = 0;
var stepTime;
var delay = 0;
var level = 0;
var inputEnabled = true;
var score = 0;
var prevScore = 0;
var lives = 3;
window(44, 0, 176, 176);
tileshift(2, 0);
io("DURATION", 50);
reset();
function reset(){
if(lives < 0){
highscore(score);
exit();
return;
}
color(bgColor);
for(y = 0; y < boardHeight; ++y){
for(x = 0; x < boardWidth; ++x){
tile(x + minX, y + minY, ledOFF);
}
}
t = 0;
delay = 100 - (level * 5);
x = boardWidth / 2;
y = boardHeight / 2;
currentLen = 1;
len = 5;
vx = 0;
vy = 0;
dead = false;
end = 0;
begin = end;
snake[begin] = (x << 16) + y;
ax = random(0, boardWidth);
ay = random(0, boardHeight);
inputEnabled = true;
}
function pattern(x, y, imgName){
var img = builtin(imgName);
var w = peek(img++);
var h = peek(img++);
x += minX;
y += minY;
for(var ty = 0; ty < h; ++ty){
for(var tx = 0; tx < w; ++tx){
var c = peek(img, tx);
if(c){
color(c - 7);
tile(x + tx, y + ty, ledOFF);
}
}
img += w;
}
}
function plot(i, img){
var c = snake[i];
var ty = (c << 16) >> 16;
tile((c >> 16) + minX, ty + minY, img);
}
function hud(){
color(47);
sprite(50, 165, lvl);
cursor(60, 165);
printNumber(level + 1);
sprite(110, 165, pts);
cursor(120, 165);
printNumber(score);
color(0);
for(var i=0; i<lives; ++i)
sprite(80 + (i * 8), 165, heart);
}
function update(){
if(pressed("C"))
exit();
hud();
if(inputEnabled){
if(pressed("LEFT") && (vx != 1)){
vx = -1;
vy = 0;
inputEnabled = false;
}
if(pressed("RIGHT") && (vx != -1)){
vx = 1;
vy = 0;
inputEnabled = false;
}
if(pressed("UP") && (vy != 1)){
vx = 0;
vy = -1;
inputEnabled = false;
}
if(pressed("DOWN") && (vy != -1)){
vx = 0;
vy = 1;
inputEnabled = false;
}
}
if((time() - stepTime) < delay)
return;
stepTime = time();
inputEnabled = true;
if(won){
vx = 0;
vy = 0;
--won;
if(!won){
++level;
reset();
return;
}
} else {
x += vx;
y += vy;
if(x < 0) x = boardWidth - 1;
else if(x >= boardWidth) x = 0;
if(y < 0) y = boardHeight - 1;
else if(y >= boardHeight) y = 0;
if((x == ax) && (y == ay)){
++score;
len += 3;
if(len >= ((5 + level) * 5)){
highscore(score);
prevScore = score;
delay = 20;
won = 10;
pattern(0, 2, "happyEmote");
return;
}
ax = random(0, boardWidth);
ay = random(0, boardHeight);
}
}
color(bgColor);
plot(begin, ledOFF);
if(dead){
vx = 0;
vy = 0;
if(score > prevScore) --score;
--len;
if(!len){
score = prevScore;
--lives;
reset();
return;
}
currentLen = len;
if(++begin == maxLen) begin = 0;
}
var growing = !dead;
if(vx || vy){
if(++end == maxLen) end = 0;
snake[end] = (x << 16) + y;
if(++currentLen > len){
growing = false;
if(++begin == maxLen) begin = 0;
currentLen--;
}else{
sound(40, 0);
}
}
color(snakeColor);
for(var i = begin; i != end;){
if(growing)
color(random(0, 255));
if(snake[i] == snake[end]){
delay = 20;
if(!dead){
dead = true;
sound(60, 0);
pattern(4, 7, "sSkull");
}
}
plot(i, ledON);
if(++i == maxLen) i = 0;
}
color(snakeColor-1);
plot(end, ledON);
color(appleColor);
tile(ax + minX, ay + minY, ledON);
}
<file_sep>save("save/bookmark", "Book1/256.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
The king is overjoyed with the
news. 'Excellent! At this rate I
will be able to take my rightful
place in the throne room of Old
Sokar.'
He rewards you with the title .
Note this in the Titles and
Honours box on your Adventure
Sheet. The title comes with a cash
gift of as well.
You also go up one Rank . Roll
one die - the result is the number
of Stamina points you gain
permanently. Note the increase on
your Adventure Sheet. Also, don't
forget to increase your Defence by`,
MARK,
`1 as a result of your gain in
Rank.
The king has another mission for
you. He explains that an army of
steppe Nomads, Trau, Mannekyn
people, and Sokaran troops still
loyal to Nergan, have gathered on
the steppes, and are moving to
siege the Citadel of Velis Corin,
which guards the Pass of Eagles
through the Spine of Harkun.
Nergan tells you that an alliance
of northern nations has declared
war on the new Sokaran regime. A
certain General Beladai leads the
Northern Alliance, and King Nergan
has joined forces with him. He
asks you to travel to the Steppes
and talk to General Beladai.`,
MARK,
`
'An adventurer like yourself
might be able to steal into the
citadel, and bring about its
downfall from within, or some
such. If the citadel falls we will
have Sokara at our mercy.'
If you want to take up this
mission for the King, record the
codeword Assault . When you are
ready, you are led back down to
the foothills of the mountains.`,
GOTO,
"Book1/474.js",
`go
to 474`,
`.`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep>var bookmark = file("save/bookmark", 0);
if( !bookmark ){
exec("Book1/New.js");
} else {
io("FILLER", 3, "TEXT", "5x7");
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
cursor(1, 21);
print(bookmark);
exec(bookmark);
}
<file_sep>save("save/bookmark", "Book1/400.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
<NAME> is a medium-sized
town, that acts as a way-station
between the citadel to the north,
and the rich towns of the south.
It is a garrison town; many
supplies, arms, and soldiers move
through <NAME> on the
north-south trail. Shops, temples,
traders, and the like have sprung
up here to serve the needs of the
military. There is also a sizeable
mining community, for the mines of
Sokara lie in the Bronze Hills,
just outside town, and a slave
market where poor unfortunates,
sold into slavery, are bought for
work in the mines.
`,
MARK,
` You can buy a town house in Caran
Baru for 200 Shards. Owning a town
house gives you a place to rest,
and to store equipment. If you buy
one , tick the box by the town
house option.
If you have the codeword
Barnacle,`,
GOTO,
"Book1/418.js",
`go to 418`,
`immediately.
Otherwise, pick from the following
options.
`,
GOTO,
"Book1/215.js",
`Visit the marketplace`,
`
`,
GOTO,
"Book1/112.js",
`Visit the merchants' guild`,
`
`,
GOTO,
"Book1/473.js",
`Visit the slave market`,
`
`,
GOTO,
"Book1/282.js",
`Visit the temple of Tyrnai`,
`
`,
GOTO,
"Book1/615.js",
`Visit the temple of Lacuna`,
`
`,
GOTO,
"Book1/86.js",
`Visit the temple of the Three
Fortunes`,
`
`,
GOTO,
"Book1/177.js",
`Visit your town house {box} (if
box ticked)`,
MARK,
` `,
GOTO,
"Book1/184.js",
`Visit the Blue Griffon Tavern`,
`
`,
GOTO,
"Book1/201.js",
`Follow the road north to the
citadel`,
`
`,
GOTO,
"Book1/110.js",
`Go west into the Bronze Hills`,
`
`,
GOTO,
"Book1/60.js",
`Travel north east into the
country`,
`
`,
GOTO,
"Book1/458.js",
`Take the east road to Fort
Mereth`,
`
`,
GOTO,
"Book1/474.js",
`Head south east into the
mountains`,
`
`,
GOTO,
"Book1/347.js",
`Take the south road`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep>if (!file("resources.res")) {
exit();
}
////////////////
// ANIMATIONS //
////////////////
// struct Animation
// {
// AnimationStep* steps;
// }
// struct AnimationStep
// {
// int untilTimer; // [0] - This steps is applied until timer reaches this value.
// Bitmap spriteBitmap; // [1] - The bitmap to show. If null, the animation timer is reset.
// }
const animationStepSize = 2 * 4;
const EndAnimation =
[
4, file("End1:8", null),
8, file("End2:8", null),
12, file("End3:8", null),
99999, null
];
function renderAnimation(x256, y256, animation, animationTimer)
{
var animation = animation;
var animationStep = animation;
while (animationTimer >= animationStep[0])
animationStep += animationStepSize;
var animationBitmap = animationStep[1];
if (animationBitmap == null)
{
animationTimer = 0;
animationBitmap = animation[1];
}
sprite(x256 >> 8 - 7, y256 >> 8 - 15, animationBitmap);
return animationTimer;
}
////////////////
// CINEMATICS //
////////////////
var cinematicsTimer = 0;
const END_X256 = ((220 - 60) / 2 + 7) * 256;
const END_Y256 = ((176 - 25) / 2 + 15) * 256;
function cinematicsUpdateEnd()
{
bubbleTimer = renderAnimation(END_X256, END_Y256, EndAnimation, bubbleTimer + 1);
}
var cinematicsUpdate = cinematicsUpdateEnd;
///////////////////
// INIT & UPDATE //
///////////////////
color(0);
function update()
{
cinematicsUpdate();
}<file_sep>////////////
// LEVELS //
////////////
// struct Level
// {
// STRING filename; // [0] - Name of the level's file.
// int finishedTime; // [1] - Run Timestamp of the completion.
// bool collectedCatnip; // [2] - If true, the Catnip was collected.
// int reserved; [3] - ???
// };
const Level_SIZE = 4 * 4;
const levelsStart = file("_run.tmp", null);
const levelsEnd = levelsStart + length(levelsStart) * 4;
if (!file("resources.res")) {
exit();
}
/////////////
// RESULTS //
/////////////
// An important end item.
var collectedCatnips = 0;
var availableCatnips = 0;
for (var level = levelsStart, levelNumber = 1; level[0] != null; level += Level_SIZE, levelNumber++)
{
collectedCatnips += level[2];
availableCatnips += level[3];
}
///////////
// TOOLS //
///////////
var timer = 0;
function clear()
{
for (var i = 0; i < 30; i++)
print(" \n");
cursor(0, 0);
}
//////////////////
// STORY ENGINE //
//////////////////
var currentStep = steps;
function goToStep(step)
{
currentStep = steps + step * 8 * 4;
timer = 0;
}
////////////////////
// STEPS HANDLERS //
////////////////////
const stepsHandlers = [
null,
null,
null,
null,
null,
null,
null,
null,
null
]
// Infinite loop.
// - All parameters are ignored.
const STEP_HANDLER_INFINITE = 0;
function infiniteStepHandler(step)
{
}
stepsHandlers[STEP_HANDLER_INFINITE] = infiniteStepHandler;
// Progressive Text appears, waiting A press..
// - Parameter 1 is the next step index.
// - Parameters 2-7 are used as text, until the first null.
// - If COMMAND_CLEAR appears as a text, the screen will be cleared instead.
const TEXT_CLEAR = "<clear>";
const STEP_HANDLER_TEXT_PRESS = 1;
const TIMER_STEP = 5;
function textPressStepHandler(step)
{
var expectedTimer = 0;
for (var paramI = 2; (paramI < 8) && (step[paramI] != null); paramI++, expectedTimer += TIMER_STEP)
if (expectedTimer == timer)
if (step[paramI] == TEXT_CLEAR)
clear();
else
print(step[paramI]);
if ((timer > expectedTimer) && (justPressed("A")))
goToStep(step[1]);
else
timer++;
}
stepsHandlers[STEP_HANDLER_TEXT_PRESS] = textPressStepHandler;
// Progressive Text appears.
// - Parameter 1 is the next step index.
// - Parameters 2-7 are used as text, until the first null.
// - If COMMAND_CLEAR appears as a text, the screen will be cleared instead.
const STEP_HANDLER_TEXT = 2;
function textStepHandler(step)
{
var expectedTimer = 0;
for (var paramI = 2; (paramI < 8) && (step[paramI] != null); paramI++, expectedTimer += TIMER_STEP)
if (expectedTimer == timer)
if (step[paramI] == TEXT_CLEAR)
clear();
else
print(step[paramI]);
if (timer > expectedTimer)
goToStep(step[1]);
else
timer++;
}
stepsHandlers[STEP_HANDLER_TEXT] = textStepHandler;
// Button to branch.
// - Parameters are mapped to a button press (justPressed) each:
// - RIGHT, DOWN, LEFT, UP, A, B, C
// - Each null or 0 parameter is ignored.
// - Otherwise, when pressing said button, it'll branch to the corresponding step.
const STEP_HANDLER_PRESS_TO_BRANCH = 3;
const branchButtons = [
"RIGHT",
"DOWN",
"LEFT",
"UP",
"A",
"B",
"C"
];
function textPressToBranchHandler(step)
{
for (var buttonI in branchButtons)
if ((step[buttonI + 1] != null) && (justPressed(branchButtons[buttonI])))
{
goToStep(step[buttonI + 1]);
return ;
}
}
stepsHandlers[STEP_HANDLER_PRESS_TO_BRANCH] = textPressToBranchHandler;
const STEP_HANDLER_END_DIRECT = 4;
function endDirectHandler(step)
{
exec("blueend.js");
}
stepsHandlers[STEP_HANDLER_END_DIRECT] = endDirectHandler;
const STEP_HANDLER_RED_END = 5;
function redEndDirectHandler(step)
{
exec("end.js");
}
stepsHandlers[STEP_HANDLER_RED_END] = redEndDirectHandler;
// Progressive Text appears, but only with catnips.
const STEP_HANDLER_TEXT_IF_CATNIPS = 6;
function textIfCatnipsStepHandler(step)
{
if (collectedCatnips == 0)
goToStep(step[1]);
else
textStepHandler(step);
}
stepsHandlers[STEP_HANDLER_TEXT_IF_CATNIPS] = textIfCatnipsStepHandler;
// Progressive Text appears, but only with full catnips.
const STEP_HANDLER_TEXT_IF_ALLCATNIPS = 7;
function textIfAllCatnipsStepHandler(step)
{
if (collectedCatnips != availableCatnips)
goToStep(step[1]);
else
textStepHandler(step);
}
stepsHandlers[STEP_HANDLER_TEXT_IF_ALLCATNIPS] = textIfAllCatnipsStepHandler;
// Jumps to the step indicated:
// - param1 if all catnips,
// - param2 if a few catnips,
// - param3 if no catnips.
const STEP_HANDLER_IF_CATNIPS = 8;
function ifCatnipsHandler(step)
{
if (collectedCatnips == availableCatnips)
goToStep(step[1]);
else if (collectedCatnips > 0)
goToStep(step[2]);
else
goToStep(step[3]);
}
stepsHandlers[STEP_HANDLER_IF_CATNIPS] = ifCatnipsHandler;
///////////
// STORY //
///////////
const STEP_INITIAL = 0;
const STEP_ROOMCHOICE_INIT = STEP_INITIAL + 1;
const STEP_ROOMCHOICE_CATNIPS = STEP_ROOMCHOICE_INIT + 1;
const STEP_ROOMCHOICE_CHOICES = STEP_ROOMCHOICE_CATNIPS + 1;
const STEP_ROOMCHOICE_BRANCHES = STEP_ROOMCHOICE_CHOICES + 1;
const STEP_CHECKGREYDOOR = STEP_ROOMCHOICE_BRANCHES + 1;
const STEP_CHECKREDDOOR_INIT = STEP_CHECKGREYDOOR + 1;
const STEP_CHECKREDDOOR_BRANCHES = STEP_CHECKREDDOOR_INIT + 1;
const STEP_CHECKBLUEDOOR_INIT = STEP_CHECKREDDOOR_BRANCHES + 1;
const STEP_CHECKBLUEDOOR_BRANCHES = STEP_CHECKBLUEDOOR_INIT + 1;
const STEP_CHECKWINDOW = STEP_CHECKBLUEDOOR_BRANCHES + 1;
const STEP_BLUE_FORCE_CHECK = STEP_CHECKWINDOW + 1;
const STEP_BLUE_FORCE_LAST = STEP_BLUE_FORCE_CHECK + 1;
const STEP_BLUE_EXIT_INIT = STEP_BLUE_FORCE_LAST + 1;
const STEP_BLUE_EXIT_CATNIPS = STEP_BLUE_EXIT_INIT + 1;
const STEP_BLUE_EXIT_LAST = STEP_BLUE_EXIT_CATNIPS + 1;
const STEP_BLUE_END = STEP_BLUE_EXIT_LAST + 1;
const STEP_RED_EXIT_INIT = STEP_BLUE_END + 1;
const STEP_RED_EXIT_CATNIPS = STEP_RED_EXIT_INIT + 1;
const STEP_RED_EXIT_ALLCATNIPS = STEP_RED_EXIT_CATNIPS + 1;
const STEP_RED_EXIT_LAST = STEP_RED_EXIT_ALLCATNIPS + 1;
const STEP_RED_END = STEP_RED_EXIT_LAST + 1;
// A step consists of a handler (see STEP_HANDLER_*) and 7 parameters (not all them are used.)
const steps =
[
// STEP_INITIAL
STEP_HANDLER_TEXT_PRESS,
STEP_ROOMCHOICE_INIT,
"You do not hear any more meows;\n",
"merely some faint howling.\n\n",
"Having fed all these cats leaves you\nsatisfied.\n",
" \n",
"... but hungry as well.\n \n",
" \n [A - Continue]",
// STEP_ROOMCHOICE_INIT
STEP_HANDLER_TEXT,
STEP_ROOMCHOICE_CATNIPS,
TEXT_CLEAR,
"You are in the middle of a quite\ndark room.\n \n",
null,
null,
null,
null,
// STEP_ROOMCHOICE_CATNIPS
STEP_HANDLER_TEXT_IF_CATNIPS,
STEP_ROOMCHOICE_CHOICES,
"Your pocket is full of catnips.\n \n",
null,
null,
null,
null,
null,
// STEP_ROOMCHOICE_CHOICES
STEP_HANDLER_TEXT,
STEP_ROOMCHOICE_BRANCHES,
" [UP - Grey Door]\n",
"[< - Red Door] [> - Blue Door]\n",
" [DOWN - Window]\n",
null,
null,
null,
// STEP_ROOMCHOICE_BRANCHES
STEP_HANDLER_PRESS_TO_BRANCH,
STEP_CHECKBLUEDOOR_INIT, // RIGHT
STEP_CHECKWINDOW, // DOWN
STEP_CHECKREDDOOR_INIT, // LEFT
STEP_CHECKGREYDOOR, // UP
null, // A
null, // B
null, // C
// STEP_CHECKGREYDOOR
STEP_HANDLER_TEXT_PRESS,
STEP_ROOMCHOICE_INIT,
TEXT_CLEAR,
"You're looking at the grey door.\n \n",
"You came from there, but it won't\nbudge anymore.\n \n",
"Anyway, coming here was quite\ndangerous.\n",
"Unlike cats, you got only one live, after all.\n",
" \n [A - Back]",
// STEP_CHECKREDDOOR_INIT
STEP_HANDLER_TEXT,
STEP_CHECKREDDOOR_BRANCHES,
TEXT_CLEAR,
"You're looking at the red door.\n \n",
"It is covered with intricate golden patterns and surrounded by a\npowerful aura.\n",
" \n[A - Back] [C - Enter]",
null,
null,
// STEP_CHECKREDDOOR_BRANCHES
STEP_HANDLER_PRESS_TO_BRANCH,
null, // RIGHT
null, // DOWN
null, // LEFT
null, // UP
STEP_ROOMCHOICE_INIT, // A
null, // B
STEP_RED_EXIT_INIT, // C
// STEP_CHECKBLUEDOOR_INIT
STEP_HANDLER_TEXT,
STEP_CHECKBLUEDOOR_BRANCHES,
TEXT_CLEAR,
"You're looking at the blue door.\n \n",
"It is a very nice door, finely\ncrafted.\n\n",
"You can hear the city bustling\nthrough it.\n",
"It's probably the fastest way to go home.\n",
" \n[A - Back] [C - Enter]",
// STEP_CHECKBLUEDOOR_BRANCHES
STEP_HANDLER_PRESS_TO_BRANCH,
null, // RIGHT
null, // DOWN
null, // LEFT
null, // UP
STEP_ROOMCHOICE_INIT, // A
null, // B
STEP_BLUE_FORCE_CHECK, // C
// STEP_CHECKWINDOW
STEP_HANDLER_TEXT_PRESS,
STEP_ROOMCHOICE_INIT,
TEXT_CLEAR,
"You're checking the window.\n \n",
"While the immediate neighborhood is quiet, you can see the city being\nlively far away.\n \n",
"However, it is way too high to exit this way.\n",
" \n [A - Continue]",
null,
// STEP_BLUE_FORCE_CHECK
STEP_HANDLER_IF_CATNIPS,
STEP_BLUE_FORCE_LAST, // All catnips
STEP_BLUE_EXIT_INIT, // Some catnips
STEP_BLUE_EXIT_INIT, // No catnips.
null,
null,
null,
null,
// STEP_BLUE_FORCE_LAST
STEP_HANDLER_TEXT_PRESS,
STEP_ROOMCHOICE_INIT,
TEXT_CLEAR,
"... But somehow, you cannot resolve yourself into opening that door.\n \n",
"You cannot explain why, but you know\nyou still got some business left to\ndo here.\n",
" \n [A - Continue]",
null,
null,
// STEP_BLUE_EXIT_INIT
STEP_HANDLER_TEXT,
STEP_BLUE_EXIT_CATNIPS,
TEXT_CLEAR,
"You open the door.\n \n",
"After a long walk, you're finally\nback at your home, enjoying a good\nmeal.\n",
" ",
" ",
" ",
// STEP_BLUE_EXIT_CATNIPS
STEP_HANDLER_TEXT_IF_CATNIPS,
STEP_BLUE_EXIT_LAST,
" ",
" ",
" ",
" ",
" \n",
"Though you're still wondering what\nyou're going to do with all these\ncatnips...\n",
// STEP_BLUE_EXIT_LAST
STEP_HANDLER_TEXT_PRESS,
STEP_BLUE_END,
" ",
" ",
" ",
" ",
" \n",
" \n [A - Continue]",
// STEP_BLUE_END
STEP_HANDLER_END_DIRECT,
null,
null,
null,
null,
null,
null,
null,
// STEP_RED_EXIT_INIT
STEP_HANDLER_TEXT,
STEP_RED_EXIT_CATNIPS,
TEXT_CLEAR,
"You open the door.\n \n",
"The room inside is huge, and quite\nweird.\nA large hole is present at the\nopposite.\n \n",
"You approach the hole.\n \n",
null,
null,
// STEP_RED_EXIT_CATNIPS
STEP_HANDLER_TEXT_IF_CATNIPS,
STEP_RED_EXIT_ALLCATNIPS,
"The catnips in your pocket start\nvibrating.",
" ",
" ",
" ",
" \n",
"... and suddenly it becomes empty!\n \n",
// STEP_RED_EXIT_ALLCATNIPS
STEP_HANDLER_TEXT_IF_ALLCATNIPS,
STEP_RED_EXIT_LAST,
" ",
" ",
" ",
" ",
" \n",
"The ground is rumbling!\n \n",
// STEP_RED_EXIT_LAST
STEP_HANDLER_TEXT_PRESS,
STEP_RED_END,
" \n [A - Continue]",
null,
null,
null,
null,
null,
// STEP_RED_END
STEP_HANDLER_RED_END,
null,
null,
null,
null,
null,
null,
null,
// (Last)
STEP_HANDLER_INFINITE,
null,
null,
null,
null,
null,
null,
null
];
if (length(steps) % 8 != 0)
{
// Steps must contain a multiple of 8 items.
console("mismatching steps!\n");
while(true);
}
///////////////////
// INIT & UPDATE //
///////////////////
io("FORMAT", 0, 0);
io("FILLER", 1, "TEXT", "5x7");
cursor(0, 0);
color(7);
goToStep(STEP_INITIAL);
function update()
{
var stepUpdate = stepsHandlers[currentStep[0]];
stepUpdate();
}<file_sep>if ( file("images.res", 0) != 1 ){
console("Could not find resources!");
exit();
}
var playerX = 60;
var playerY = 140;
var level = 4;
const NUMBER_OF_ENTITIES = 10;
const NUMBER_OF_HEARTS = 4;
const enemiesX = new Array(NUMBER_OF_ENTITIES);
const enemiesY = new Array(NUMBER_OF_ENTITIES);
const enemiesD = new Array(NUMBER_OF_ENTITIES); // Direction where 0 = left, 1 = straight fown, 2 = right
const enemiesL = new Array(NUMBER_OF_ENTITIES); // Length of travel
const bulletsX = new Array(NUMBER_OF_ENTITIES);
const bulletsY = new Array(NUMBER_OF_ENTITIES);
const heartsX = new Array(NUMBER_OF_HEARTS);
const heartsY = new Array(NUMBER_OF_HEARTS);
var bgLY = 0;
var topBgLY = 0;
var score = 0;
var lives = 59;
var shipAnim = 0;
var big = 0;
var timer = 0;
const HUD_BG = file("HUD_BG", 0);
const gameOverImg = file("GameOver", 0);
const playerSprites =
[
file("PlayerShip_F1", 0), // load the ship frame1
file("PlayerShip_F2", 0) // load the ship frame 2
];
const playerShip_shadow = file("PlayerShip_shadow", 0); // load the ship shadow
const Bullet = file("Bullet", 0); // Bullet
const enemyImg = file("Enemy", 0); // load the enemy gfx
const heartImg = builtin("icon21");
const hudHeartImg = builtin("sHeart"); //Hearts for lives
const bgL = file("bgL", 0); // load the Left Background bottom layer image
const bgR = file("bgR", 0); // load the right Background bottom layer image
const topBgL = file("TopBgL",0); // load the Left Background Top layer image
const topBgR = file("TopBgR",0); // load the right Background Top layer image
//------------------------------------------------------------------------
// Position enemies and bullets before start of game ..
io("LOOP", 1);
music("lrmusicNew.raw");
fill(65);
for (var i = 0; i < NUMBER_OF_ENTITIES; ++i) {
heartsY[i&3] = 200;
bulletsY[i] = -5;
enemySpawn(i);
}
//------------------------------------------------------------------------
function somethingHitBullet(otherIndex, bulletIndex) {
if(otherIndex > 255){
//lives -= 10;
heartsY[otherIndex >> 8 - 1] = 200;
playSound();
score -= 20;
} else {
playSound();
score += 10;
enemySpawn(otherIndex - 1);
}
bulletsY[bulletIndex >> 4 - 1] = -5;
}
function playerHitHeart(playerIndex, heartIndex) {
lives += 10;
playSound();
score += 20;
// heartSpawn(heartIndex >> 8 - 1);
heartsY[heartIndex >> 8 - 1] = 200;
//bulletsY[bulletIndex >> 4 - 1] = -5;
}
function enemyHitPlayer(enemyIndex, playerIndex) {
playSound();
enemySpawn(enemyIndex - 1);
lives -=20;
}
function moveEnemy(enemyIndex) {
// Move down ..
var y = enemiesY[enemyIndex] += (2 + (enemyIndex / 4));
// Move left / right
var direction = enemiesD[enemyIndex];
var enemyX = enemiesX[enemyIndex];
var newX = enemyX + direction;
var newDirection = newX < 30 || newX > 200 || --enemiesL[enemyIndex] <= 0 || y > 176;
// New Direction?
if (newDirection) {
enemySpawn(enemyIndex);
if(y <= 176){
newX = enemyX;
enemiesY[enemyIndex] = y;
} else {
newX = enemiesX[enemyIndex];
}
}
enemiesX[enemyIndex] = newX;
io("SCALE", 1 + (enemyIndex < big));
// Render enemy ..
io("COLLISION", enemyIndex + 1, 0);
sprite(newX, enemiesY[enemyIndex], enemyImg);
}
function enemySpawn(enemyIndex) {
enemiesY[enemyIndex] = -random(16, 64);
enemiesX[enemyIndex] = random(32, 192);
enemiesD[enemyIndex] = random(-2, 3);
enemiesL[enemyIndex] = random(16, 32);
}
function playSound() {
io("VOLUME", 127);
io("DURATION", 70);
sound(random(44, 47));
}
function fireBullet() {
for (var i = 0; i < NUMBER_OF_ENTITIES; ++i) {
if (bulletsY[i] <= 0) {
bulletsX[i] = playerX + 6;
bulletsY[i] = playerY - 2;
break;
}
}
}
function bgScroll() {
for(var yOffset = -220; yOffset < (8 * 55 - 220); yOffset += 55) {
var y = yOffset + bgLY;
sprite(32, y, bgL);
sprite(172, y, bgR);
y = yOffset + topBgLY;
sprite(0, y, topBgL);
sprite(188, y, topBgR);
}
bgLY+=2;
if (bgLY > 55) {bgLY = 0;}
topBgLY+=4;
if (topBgLY > 55) {topBgLY = 0;}
}
function HUD() {
sprite(0, 0, HUD_BG);
var x = 110;
var heartsToDraw = lives / 10;
while(heartsToDraw > 5){
sprite(x, -1, heartImg);
x += 16;
heartsToDraw -= 5;
}
while(heartsToDraw--) {
sprite(x, 4, hudHeartImg);
x += 8;
}
color(7);
cursor(8,4)
print(("SCORE "));
print(score);
color(0);
}
function update() {
bgScroll();
var px = playerX + ((pressed("RIGHT") - pressed("LEFT")) << 2);
if(px>20 && px<190) playerX = px;
var py = playerY + ((pressed("DOWN") - pressed("UP")) << 2);
if(py>18 && py<160) playerY = py;
if (justPressed("A")) fireBullet();
if (pressed("C")) exit();
if (lives < 1) {
highscore(score);
sprite(45, 75, gameOverImg);
HUD();
return;
}
// Decrement the lives using the counter ..
timer++;
if (timer % 32 == 0) lives--;
// Update the level based on the score ..
if (score > 240){ level = 10; big = (score - 240) >> 7; }
else if (score > 140) level = 8;
else if (score > 40) level = 6;
for(var i = 0; i < level; ++i)
moveEnemy(i); io("SCALE", 1);
// Render the player ..
++shipAnim;
io("COLLISION", 1024, 0x0F, enemyHitPlayer);
i = playerSprites[(shipAnim>>2)&1];
sprite(playerX, playerY, i);
sprite(playerX+20, playerY+20, playerShip_shadow);
// Move and render the hearts ..
for (var i = 0; i < NUMBER_OF_HEARTS; ++i){
// Move down ..
if (heartsY[i] > 176) {
// heartSpawn(i);
heartsY[i] = -random(0, 128);
heartsX[i] = random(32, 192);
}
var y = heartsY[i]+=2;
var x = heartsX[i];
// Make hearts wobble
x += sin(y+(i<<2)<<4) >> 5;
// Render heart ..
io("COLLISION", (i + 1) << 8, 1024, playerHitHeart);
sprite(x, y, heartImg);
}
// Move and render the bullets ..
for(var i = 0; i < level; ++i){
bulletsY[i]-=5;
io("COLLISION", (1 + i) << 4, 0xF0F, somethingHitBullet);
sprite(bulletsX[i], bulletsY[i], Bullet);
}
if (score < 0) score = 0;
if (lives < 0) lives = 0;
HUD();
}
<file_sep>save("save/bookmark", "Book1/20.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
'Well, well, well, what have we
here, friends?' asks the old man.
He seems to be talking to someone
next to him, although you are
certain he is alone. 'Looks like a
washed up adventurer to me!' he
says in answer to his own
question, 'all wet and out of
luck.'
He carries on having a
conversation - a conversation that
quickly turns into a heated
debate. He is clearly quite mad.
'Excuse me, umm, EXCUSE ME!,' you
shout above the hubbub in an
attempt to grab the old man's`,
MARK,
`attention. He stops and stares at
you.
'Is this the Isle of the Druids?'
you ask impatiently.
'Indeed it is,' says the old man,
'I see that you are from a far
land, so it is up to me to welcome
you to Harkuna. But I think you
may have much to do here as it is
written in the stars that someone
like you would come. Your destiny
awaits you! Follow me, young
adventurer.'
The old man turns smartly about
and begins walking up a path
towards some hills. You can just
see some sort of monolithic stone`,
MARK,
`structure atop one of them.
'Come on, come on, I'll show you
the Gates of the World,' the old
man babbles.
`,
GOTO,
"Book1/192.js",
`Follow him`,
`
`,
GOTO,
"Book1/128.js",
`Explore the coast`,
`
`,
GOTO,
"Book1/257.js",
`Head into the nearby forest`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep>save("save/bookmark", "Book1/522.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
That night several sea centaurs
emerge from the waters, their
spiny skins glittering with
phosphorescent flashes of light.
One of them speaks in a burbling
voice. 'Where is our brother, whom
you caught in your cruel nets,
this day?'
'He is dead, I'm afraid', you
reply, readying yourself for a
fight.
The sea centaurs remain silent
for a few moments, then the leader
says, 'His destiny was always
bleak. We would be grateful if you`,
MARK,
`were to return his body to us.'
You cannot think of a reason not
to, so you pass the body down to
them.
'We thank you,' burbles the sea
centaur. 'If you wish, we will
give you the power to breathe the
waters, so that you may swim down
to the wreck that lies below, and
take its treasures, those things
that the surface-dwellers hold
dear.'
`,
GOTO,
"Book1/513.js",
`Accept the offer`,
`
`,
GOTO,
"Book1/408.js",
`Refuse the offer`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep>save("save/bookmark", "Book1/1.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
The approach of dawn has turned
the sky a milky grey-green, like
jade. The sea is a luminous pane
of silver. Holding the tiller of
your sailing boat, you keep your
gaze fixed on the glittering
constellation known as the Spider.
It marks the north, and by keeping
it to port you know you are still
on course.
The sun appears in a trembling
burst of red fire at the rim of
the world. Slowly the chill of
night gives way to brazen warmth.
You lick your parched lips. There
is a little water sloshing in the
bottom of the barrel by your feet,`,
MARK,
`but not enough to see you through
another day.
Sealed in a scroll case tucked
into your jerkin is the parchment
map your grandfather gave you on
his death-bed. You remember his
stirring tales of far sea voyages,
of kingdoms beyond the western
horizon, of sorcerous islands and
ruined palaces filled with
treasure. As a child you dreamed
of nothing else but the magical
quests that were in store if you
too became an adventurer.
You never expected to die in an
open boat before your adventures
even began.
`,
MARK,
` Securing the tiller, you unroll
the map and study it again. You
hardly need to. Every detail is
etched into your memory by now.
According to your reckoning, you
should have reached the east coast
of Harkuna, the great northern
continent, days ago.
A pasty grey blob splatters on to
the map. After a moment of stunned
surprise, you look up and curse
the seagull circling directly
overhead. Then it strikes you -
where there's a seagull, there may
be land.
You leap to your feet and scan
the horizon. Sure enough, a line
of white cliffs lie a league to`,
MARK,
`the north. Have you been sailing
along the coast all this time
without realising the mainland was
so close?
Steering towards the cliffs, you
feel the boat judder against rough
waves. A howling wind whips plumes
of spindrift across the sea.
Breakers pound the high cliffs.
The tiller is yanked out of your
hands. The little boat is spun
around, out of control, and goes
plunging in towards the coast.
You leap clear at the last
second. There is the snap of
timber, the roaring crescendo of
the waves - and then silence as
you go under. Striking out wildly,`,
MARK,
`you try to swim clear of the
razor-sharp rocks. For a while the
undertow threatens to drag you
down, then suddenly a wave catches
you and flings you contemptuously
up on to the beach.
Battered and bedraggled you lie
gasping for breath until you hear
someone walking along the shore
towards you. Wary of danger, you
lose no time in getting to your
feet. Confronting you is an old
man clad in a dirty loin-cloth.
His eyes have a feverish bright
look that is suggestive of either
a mystic or a madman.
Now`,
GOTO,
"Book1/20.js",
`go to 20`,
`.`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep># Charlotte et les 64 Miauleurs
## Introduction
Charlotte was walking back to her home.
That day, she decided to take a shortcut through the old industrial area.
It's a district with a lot of abandoned buildings, made mostly out of bricks, devoid of life.
... or so she thought.
She heard a lot of meowing inside an old factory. Cats kept calling her.
After a short passage through the pet store, She decided to enter the factory. Well-prepared.
It's time to feed those 64 cats!
But the old factories aren't exactly a safe place...
## Controls
- LEFT/RIGHT - Move Charlotte to the left or right.
- A - Charlotte will jump.
## Gameplay
Guide Charlotte through 10 levels in increasing difficulty!
Each level will features the following elements:
- Charlotte is your character. She'll appear out of a door.
- Meowing Cats are the one that should be visited.
- Just touch them briefly with Charlotte to do so!
- They'll purr and sleep after a few instants.
- The Cat Door is your exit to the next level.
- It'll open when all the Cats are sleeping.
- Just touch them after!
- Catnips are bonus items.
- They're usually trickier to get.
- There are 13 of them to retrieve.
- They're worth a lot of points!
- Pits are bad things to fall into.
- If you do, it'll reload the current level, so you'll have to redo it!
## Scoring
A timer is launched when you first move your character in Level 1.
When you're through the Level 10, you'll have a summary about your times, collected catnips - and the resulting score.
- The par-time is 4 minutes for the 10 levels.
- Each 2ms below the par-time is worth a point.
- Each collected catnip is worth 5000 points.
- So you probably don't want to spend more than 10s getting a single catnip!
Falling in a pit will not reset the current level's timer!
## Important Notes
- The game will take a long time to compile in Pine2K.
- 13s on my own device, we've seen 40s as well. It depends a lot on the SD card.
- On the Pine2K version it's designed to run for, it'll use 2040 bytes of PROGMEM.
- Needless to say, chances are it might break in upcoming Pine2K updates.
- The game cannot be run after another game - some corruptions will ensue.
- Because of that, it cannot run itself again either, so the only way to exit it is to restart the Pokitto.
## Tech Notes & Tools
- FemtoIDE, Aseprite, Tiled were used to create this game.
- It was really challenging to pack that many features into 2K of compiled bytecode (PROGMEM).
- The whole code relies a lot on the weird pointer arithmetics that can be done in Pine2K.
- A lot of weird tricks were also used, on the basis that they would save 4, 8, 12, 16, 24 or more PROGMEM bytes.
- Such as converting a `if (a && b)` into two if.
- Or moving around the `var` declaration out of their loops because somehow it saves a bit.
- The Character Entity is always at the end of the entities array, and it saved a lot of bytes to do so (a fixed pointer costs less than a pointer as parameter).
- The same animation structure was used wherever the entity was animated or not.
- The collision detection is based on the tile identifier - if it's above or equal to 20, it's colliding.
## Special Thanks
- FManga (https://github.com/felipemanga/FemtoIDE) for making Pine2K and FemtoIDE.
- Torbuntu (https://github.com/Torbuntu) for playtesting it.
- Jonne for the amazing device that is the Pokitto (https://pokitto.com - get this cute little device!).
- The Pokitto Community for their general support and enthusiasm.
- The Aseprite team. (https://www.aseprite.org/)
- The Tiled team. (https://www.mapeditor.org/)
- Anyone who contributed from faraway to the involved tools.
## References
- Github Repository - https://github.com/carbonacat/miaou-p2k
<file_sep>save("save/bookmark", "Book1/431.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
You notice that Oliphard has
erected his pavillion over a
verdigris trapdoor set into the
floor.
'Ah, you have the key, I see!'
says Oliphard. 'Please, be my
guest - use the door.'
You open it up and climb some
short stairs into a square chamber
with three doors.
'They are doors of teleportation
- step through and you will be
taken to whatever land is
displayed!' says Oliphard.
`,
MARK,
` The first door leads to a teeming
city of merchants - Metriciens in
Golnir.`,
GOTO,
"Book2/48.js",
`Turn to paragraph 48 in
Cities of Gold and Glory`,
`if you
enter this door.
The second door leads to a huge
mountain - Sky Mountain in the
Great Steppes, far to the north.`,
GOTO,
"Book4/185.js",
`
Turn to paragraph 185 in The Plains
of Howling Darkness`,
`if you enter
this door.
The third door leads to Dweomer,
the City of Sorcerers, on
Sorcerers' Isle.`,
GOTO,
"Book3/100.js",
`Turn to paragraph
100 in Over the Blood-Dark Sea`,
`if
you open this door.
If you don't want to step through`,
MARK,
`any of the doors,`,
GOTO,
"Book1/656.js",
`go to 656`,
`and
choose again.`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep>////////////
// LEVELS //
////////////
// struct Level
// {
// STRING filename; // [0] - Name of the level's file.
// int finishedTime; // [1] - Run Timestamp of the completion.
// bool collectedCatnip; // [2] - If true, the Catnip was collected.
// int reserved; [3] - ???
// };
const Level_SIZE = 4 * 4;
const levelsStart = file("_run.tmp", null);
const levelsEnd = levelsStart + length(levelsStart) * 4;
if (!file("resources.res")) {
exit();
}
/////////////
// RESULTS //
/////////////
var collectedCatnips = 0;
var availableCatnips = 0;
for (var level = levelsStart, levelNumber = 1; level[0] != null; level += Level_SIZE, levelNumber++)
{
collectedCatnips += level[2];
availableCatnips += level[3];
}
var foundAllCatnips = collectedCatnips == availableCatnips;
/////////////
// SPRITES //
/////////////
// Otherwise the previous file might corrupt the CatGod.
const CatGod1Bitmap = file("CatGod1:8", null);
const CatGod2Bitmap = file("CatGod2:8", null);
////////////////
// ANIMATIONS //
////////////////
// struct Animation
// {
// AnimationStep* steps;
// }
// struct AnimationStep
// {
// int untilTimer; // [0] - This steps is applied until timer reaches this value.
// Bitmap spriteBitmap; // [1] - The bitmap to show. If null, the animation timer is reset.
// }
const animationStepSize = 2 * 4;
const CharacterWalkAnimation =
[
4, file("Character1:8", null),
8, file("Character2:8", null),
12, file("Character3:8", null),
16, file("Character4:8", null),
20, file("Character5:8", null),
24, file("Character6:8", null),
99999, null
];
const CatNipAnimation =
[
1, file("CatNip:8", null),
99999, null
];
const BubbleMiaouAnimation =
[
4, file("BubbleMiaou1", null),
8, file("BubbleMiaou2", null),
12, file("BubbleMiaou3", null),
99999, null
];
const ThreeDotsAnimation =
[
4, file("ThreeDots1:8", null),
8, file("ThreeDots2:8", null),
12, file("ThreeDots3:8", null),
99999, null
];
const EndAnimation =
[
4, file("End1:8", null),
8, file("End2:8", null),
12, file("End3:8", null),
99999, null
];
function renderAnimation(x256, y256, animation, animationTimer)
{
var animation = animation;
var animationStep = animation;
while (animationTimer >= animationStep[0])
animationStep += animationStepSize;
var animationBitmap = animationStep[1];
if (animationBitmap == null)
{
animationTimer = 0;
animationBitmap = animation[1];
}
sprite(x256 >> 8 - 7, y256 >> 8 - 15, animationBitmap);
return animationTimer;
}
/////////
// MAP //
/////////
const mapTiles = [
// 0-3
file("MiaouEndTiles1:8", null),
file("MiaouEndTiles2:8", null),
file("MiaouEndTiles3:8", null),
file("MiaouEndTiles4:8", null),
// 4-7
file("MiaouEndTiles5:8", null),
file("MiaouEndTiles6:8", null),
file("MiaouEndTiles7:8", null),
file("MiaouEndTiles8:8", null),
// 8-11
file("MiaouEndTiles9:8", null),
file("MiaouEndTiles10:8", null),
file("MiaouEndTiles11:8", null),
file("MiaouEndTiles12:8", null)
];
const mapWidth = 28;
const mapHeight = 22;
const levelMapData = file("end.map", null);
const levelMap = levelMapData + 4;
function loadMap()
{
var levelMapI = levelMap;
for (var tileJ = 0; tileJ < mapHeight; tileJ++)
for (var tileI = 0; tileI < mapWidth; tileI++, levelMapI++)
tile(tileI, tileJ, mapTiles[peek(levelMapI)]);
}
////////////////
// CINEMATICS //
////////////////
var cinematicsTimer = 0;
function cinematicsUpdateStage1()
{
if (mainCharacterX256 < MC_STAGE2X256)
{
mainCharacterX256 += MC_WALKSPEED;
if (mainCharacterX256 >= MC_STAGE2X256)
{
mainCharacterX256 = MC_STAGE2X256;
catnipsEnd = catnipsStart + min(catnipsCapacity, collectedCatnips) * Catnip_SIZE;
cinematicsUpdate = cinematicsUpdateStage2;
}
mainCharacterAnimationTimer++;
}
}
function cinematicsUpdateStage2()
{
// Are all the catnips stable enough?
for (var catnip = catnipsStart; catnip != catnipsEnd; catnip += Catnip_SIZE)
{
// If a catnip is too fast, or too high, we don't proceed.
if ((abs(catnip[3]) > 128) || (catnip[2] > 1*256))
return ;
}
if (foundAllCatnips)
cinematicsUpdate = cinematicsUpdateStage3;
else
cinematicsUpdate = cinematicsUpdateStage3A;
}
function cinematicsUpdateStage3()
{
catGodY256 = CATGOD_FINALY256 + (catGodY256 - CATGOD_FINALY256) * 31 / 32;
if (abs(catGodY256 - CATGOD_FINALY256) < 256)
{
cinematicsTimer = 0;
cinematicsUpdate = cinematicsUpdateStage4;
}
}
function cinematicsUpdateStage4()
{
cinematicsTimer++;
if (cinematicsTimer > 30)
{
catGodBitmap = CatGod2Bitmap;
cinematicsTimer = 0;
cinematicsUpdate = cinematicsUpdateStage5;
}
}
const THREEDOTS_X256 = 152 * 256;
const THREEDOTS_Y256 = 170 * 256;
function cinematicsUpdateStage3A()
{
bubbleTimer = renderAnimation(THREEDOTS_X256, THREEDOTS_Y256, ThreeDotsAnimation, bubbleTimer + 1);
cinematicsTimer++;
if (cinematicsTimer > 30)
{
cinematicsTimer = 0;
cinematicsUpdate = cinematicsUpdateStage4A;
}
}
function cinematicsUpdateStage4A()
{
mainCharacterMirrored = true;
if (mainCharacterX256 > MC_INITIALX256)
{
mainCharacterX256 -= MC_WALKSPEED;
if (mainCharacterX256 <= MC_INITIALX256)
{
mainCharacterX256 = MC_INITIALX256;
cinematicsUpdate = cinematicsUpdateStage5;
}
mainCharacterAnimationTimer++;
}
}
function cinematicsUpdateStage5()
{
cinematicsTimer++;
if (cinematicsTimer > 30)
{
// Clears the tilemap.
color(0);
for (var tileJ = 0; tileJ < mapHeight; tileJ++)
for (var tileI = 0; tileI < mapWidth; tileI++)
tile(tileI, tileJ, null);
if (foundAllCatnips)
cinematicsUpdate = cinematicsUpdateStage6;
else
cinematicsUpdate = cinematicsUpdateStage7;
cinematicsTimer = 0;
update2 = updateBlackScene;
}
}
var bubbleTimer = 0;
const BUBBLE_X256 = 130 * 256;
const BUBBLE_Y256 = 39 * 256;
function cinematicsUpdateStage6()
{
cinematicsTimer++;
if (cinematicsTimer == 30)
music("miaouslow.raw");
if (cinematicsTimer >= 30)
{
io("SCALE", 2);
bubbleTimer = renderAnimation(BUBBLE_X256, BUBBLE_Y256, BubbleMiaouAnimation, bubbleTimer + 1);
io("SCALE", 1);
}
// At 60fps, it's roughly a bit more 2s.
if (cinematicsTimer >= 130)
{
cinematicsUpdate = cinematicsUpdateStage7;
cinematicsTimer = 0;
}
}
const END_X256 = ((220 - 60) / 2 + 7) * 256;
const END_Y256 = ((176 - 25) / 2 + 15) * 256;
function cinematicsUpdateStage7()
{
bubbleTimer = renderAnimation(END_X256, END_Y256, EndAnimation, bubbleTimer + 1);
}
var cinematicsUpdate = cinematicsUpdateStage1;
////////////////////
// MAIN CHARACTER //
////////////////////
const MC_INITIALX256 = -16 * 256;
const MC_Y256 = 165 * 256;
const MC_STAGE2X256 = 40 * 256;
const MC_WALKSPEED = 128;
var mainCharacterX256 = MC_INITIALX256;
var mainCharacterY256 = 165 * 256;
var mainCharacterAnimation = CharacterWalkAnimation;
var mainCharacterAnimationTimer = 0;
var mainCharacterMirrored = false;
function updateMainCharacter()
{
mirror(mainCharacterMirrored);
mainCharacterAnimationTimer = renderAnimation(mainCharacterX256, mainCharacterY256, mainCharacterAnimation, mainCharacterAnimationTimer);
mirror(false);
}
/////////////
// CATNIPS //
/////////////
// struct CatNip
// {
// int x256; // [0] - X on the screen *256.
// int y256; // [1] - Y on the screen *256, for z256 = 0.
// int z256; // [2] - Height of the catnip.
// int dz256; // [3] - Altitude velocity of the catnip.
// }
const Catnip_SIZE = 4 * 4;
const catnipsStart = [
61*256, 153*256, 351*256, 0,
93*256, 155*256, 403*256, 0,
73*256, 157*256, 282*256, 0,
77*256, 159*256, 335*256, 0,
83*256, 161*256, 240*256, 0,
66*256, 163*256, 256*256, 0,
98*256, 163*256, 392*256, 0,
55*256, 165*256, 327*256, 0,
73*256, 167*256, 210*256, 0,
80*256, 169*256, 309*256, 0,
91*256, 171*256, 403*256, 0,
67*256, 174*256, 512*256, 0
];
var catnipsEnd = catnipsStart;
const catnipsCapacity = length(catnipsStart) / 4;
const CN_GRAVITY_ACCEL = -64;
const CN_BOUNCE_256 = 64;
const CN_BUMP_Z256MIN = 512;
function updateCatNips()
{
for (var catnip = catnipsStart; catnip != catnipsEnd; catnip += Catnip_SIZE)
{
catnip[3] += CN_GRAVITY_ACCEL;
catnip[2] += catnip[3];
if (catnip[2] < 0)
{
catnip[2] = - catnip[2];
if (catnip[3] < -CN_BUMP_Z256MIN)
music("bump.raw");
catnip[3] = -catnip[3] * CN_BOUNCE_256 / 256;
}
renderAnimation(catnip[0], catnip[1] - catnip[2], CatNipAnimation, 0);
}
}
/////////////
// CAT GOD //
/////////////
const CATGOD_X256 = 130 * 256;
const CATGOD_INITIALY256 = 177 * 256;
const CATGOD_FINALY256 = 54 * 256;
var catGodX256 = CATGOD_X256;
var catGodY256 = CATGOD_INITIALY256;
var catGodBitmap = CatGod1Bitmap;
function updateCatGod()
{
io("SCALE", 2);
sprite(catGodX256 >> 8, catGodY256 >> 8, catGodBitmap);
io("SCALE", 1);
}
///////////////////
// INIT & UPDATE //
///////////////////
color(0);
tileshift(0, 0);
loadMap();
var update2 = updateScene;
function updateScene()
{
cinematicsUpdate();
updateMainCharacter();
updateCatGod();
updateCatNips();
}
function updateBlackScene()
{
cinematicsUpdate();
}
function update()
{
update2();
}<file_sep>io("FORMAT", 0, 0);
////////////
// LEVELS //
////////////
// struct Level
// {
// STRING filename; // [0] - Name of the level's file.
// int finishedTime; // [1] - Run Timestamp of the completion.
// bool collectedCatnip; // [2] - If true, the Catnip was collected.
// int reserved; [3] - ???
// };
const Level_SIZE = 4 * 4;
const levelsStart = file("_run.tmp", null);
const levelsEnd = levelsStart + length(levelsStart) * 4;
////////////
// SCORES //
////////////
const SCORE_CATNIP_POINTS = 5000;
const SCORE_PAR_TIME_MS = 240000;
const SCORE_EXTRA_MS_DIVIDER = 2;
const TIMER_STEP_DURATION = 5;
var timer = 0;
var collectedCatnips = 0;
var availableCatnips = 0;
var score = 0;
function init()
{
var cumulatedTime = 0;
for (var level = levelsStart, levelNumber = 1; level[0] != null; level += Level_SIZE, levelNumber++)
{
collectedCatnips += level[2];
availableCatnips += level[3];
cumulatedTime = level[1];
}
score = collectedCatnips * SCORE_CATNIP_POINTS;
if (cumulatedTime < SCORE_PAR_TIME_MS)
score += (SCORE_PAR_TIME_MS - cumulatedTime) / SCORE_EXTRA_MS_DIVIDER;
highscore(score);
}
io("FILLER", 1, "TEXT", "5x7");
cursor(0, 0);
color(7);
init();
function update()
{
var cumulatedTime = 0
var expectedTimer = TIMER_STEP_DURATION;
if (timer == 0)
print("You fed of all the cats!\n\n");
expectedTimer += TIMER_STEP_DURATION;
if (timer == 0)
print("Times:\n");
expectedTimer += TIMER_STEP_DURATION;
for (var level = levelsStart, levelNumber = 1; level[0] != null; level += Level_SIZE, levelNumber++, expectedTimer += TIMER_STEP_DURATION)
{
if (timer == expectedTimer)
{
print("- #"); printNumber(levelNumber); print(": ");
printNumber(level[1] - cumulatedTime);print("ms\n");
}
cumulatedTime = level[1];
}
expectedTimer += TIMER_STEP_DURATION;
if (timer == expectedTimer)
{
print(" \nTOTAL: "); printNumber(cumulatedTime); print("ms");
}
expectedTimer += TIMER_STEP_DURATION;
if ((collectedCatnips) && (timer == expectedTimer))
{
print(" \n ... and "); printNumber(collectedCatnips); print("/"); printNumber(availableCatnips); print(" catnips!\n\n");
}
expectedTimer += TIMER_STEP_DURATION;
if (timer == expectedTimer)
{
print("FINAL SCORE: "); printNumber(score); print(" \n\n");
}
expectedTimer += TIMER_STEP_DURATION;
if (timer == expectedTimer)
print("Press A to continue.\n");
timer++;
if ((justPressed("A")) && (timer >= expectedTimer))
exec("preend.js");
}<file_sep>if (!file("resources.res")) {
exit();
}
//////////
// MAPS //
//////////
// struct Level
// {
// STRING filename; // [0] - Name of the level's file.
// int finishedTime; // [1] - Run Timestamp of the completion.
// int collectedCatnip; // [2]
// int availableCatnips; [3]
// };
const Level_SIZE = 4 * 4;
// List of Levels.
// This list is also sent to results.js and end.js.
const levels = [
// "debug01.map", 0, 0, 0,
// "debug02.map", 0, 0, 0,
"level01.map", 0, 0, 0,
"level02.map", 0, 0, 0,
"level03.map", 0, 0, 0,
"level04.map", 0, 0, 0,
"level05.map", 0, 0, 0,
"level06.map", 0, 0, 0,
"level07.map", 0, 0, 0,
"level08.map", 0, 0, 0,
"level09.map", 0, 0, 0,
"level10.map", 0, 0, 0,
null, 0, 0, 0
];
var currentLevel = levels;
////////////////
// OBJECTIVES //
////////////////
var catsCount;
var sleepingCatsCount;
var beginTime = 0;
////////////////
// ANIMATIONS //
////////////////
// struct AnimationStep
// {
// int untilTimer; // [0] - This steps is applied until timer reaches this value.
// Bitmap spriteBitmap; // [1] - The bitmap to show. If null, the animation timer is reset.
// }
const AnimationStep_SIZE = 2*4;
const characterWalkAnimation =
[
4, file("Character1:8", null),
8, file("Character2:8", null),
12, file("Character3:8", null),
16, file("Character4:8", null),
20, file("Character5:8", null),
24, file("Character6:8", null),
99999, null
];
const catIdleAnimation =
[
8, file("Cat1:8", null),
16, file("Cat2:8", null),
24, file("Cat3:8", null),
32, file("Cat4:8", null),
99999, null
];
const catFallingAsleepAnimationEnd = 40;
const catFallingAsleepAnimation =
[
8, file("Cat5:8", null),
16, file("Cat6:8", null),
24, file("Cat7:8", null),
catFallingAsleepAnimationEnd, file("Cat8:8", null),
99999, null
];
const catSleepingAnimation =
[
8, file("Cat9:8", null),
16, file("Cat10:8", null),
24, file("Cat11:8", null),
32, file("Cat12:8", null),
40, file("Cat13:8", null),
48, file("Cat14:8", null),
56, file("Cat15:8", null),
99999, null
];
const bubbleMiaouAnimation =
[
4, file("BubbleMiaou1", null),
8, file("BubbleMiaou2", null),
12, file("BubbleMiaou3", null),
99999, null
];
const bubbleRonronAnimation =
[
4, file("BubbleRonron1", null),
8, file("BubbleRonron2", null),
12, file("BubbleRonron3", null),
99999, null
];
const bubbleDeathAnimation =
[
4, file("BubbleDeath1", null),
8, file("BubbleDeath2", null),
12, file("BubbleDeath3", null),
99999, null
];
const doorClosedAnimation =
[
1, file("Door1:8", null),
99999, null
];
const catNipAnimation =
[
1, file("CatNip:8", null),
99999, null
];
const doorOpeningAnimationEnd = 8;
const doorOpeningAnimation =
[
2, file("Door3:8", null),
4, file("Door4:8", null),
6, file("Door5:8", null),
doorOpeningAnimationEnd, file("Door6:8", null),
99999, null
];
const doorOpenAnimation =
[
1, file("Door7:8", null),
2, file("Door8:8", null),
99999, null
];
/////////
// MAP //
/////////
const TILE_MC = 16;
const TILE_CAT = 17;
const TILE_DOOR = 18;
const TILE_TREASURE = 19;
const TILE_FREE_MAX = 20;
const emptyBGTile = file("MiaouTiles1:8", null);
const defaultBGTile = file("MiaouTiles2:8", null);
const closedToorBLTile = file("MiaouTiles11:8", null);
const mapTiles = [
// 0-3
emptyBGTile,
defaultBGTile,
file("MiaouTiles3:8", null),
file("MiaouTiles4:8", null),
// 4-7
file("MiaouTiles5:8", null),
file("MiaouTiles6:8", null),
file("MiaouTiles7:8", null),
file("MiaouTiles8:8", null),
// 8-11
file("MiaouTiles9:8", null),
file("MiaouTiles10:8", null),
closedToorBLTile,
file("MiaouTiles12:8", null),
// 12-15
file("MiaouTiles13:8", null),
file("MiaouTiles14:8", null),
file("MiaouTiles15:8", null),
file("MiaouTiles16:8", null),
//16-19
closedToorBLTile, // Main Character
defaultBGTile, // Cat
defaultBGTile, // Door
defaultBGTile, // (Reserved)
// 20-23
emptyBGTile, // This is an invisible block tile.
file("MiaouTiles22:8", null),
file("MiaouTiles23:8", null),
file("MiaouTiles24:8", null),
// 24-27
file("MiaouTiles25:8", null),
file("MiaouTiles26:8", null),
file("MiaouTiles27:8", null),
file("MiaouTiles28:8", null),
// 28-31
file("MiaouTiles29:8", null),
file("MiaouTiles30:8", null),
file("MiaouTiles31:8", null),
file("MiaouTiles32:8", null),
// 32-35
file("MiaouTiles33:8", null),
file("MiaouTiles34:8", null),
file("MiaouTiles35:8", null),
file("MiaouTiles36:8", null),
// 36-39
file("MiaouTiles37:8", null),
file("MiaouTiles38:8", null),
file("MiaouTiles39:8", null),
file("MiaouTiles40:8", null),
// 40-43
file("MiaouTiles41:8", null),
file("MiaouTiles42:8", null),
file("MiaouTiles43:8", null),
file("MiaouTiles44:8", null)
];
const entityAnimationForTile = [
// 0-3
null,
null,
null,
null,
// 4-7
null,
null,
null,
null,
// 8-11
null,
null,
null,
null,
// 12-15
null,
null,
null,
null,
//16-19
characterWalkAnimation,
catIdleAnimation,
doorClosedAnimation,
catNipAnimation,
// 20-23
null,
null,
null,
null,
// 24-27
null,
null,
null,
null,
// 28-31
null,
null,
null,
null,
// 32-35
null,
null,
null,
null,
// 36-39
null,
null,
null,
null
];
const mapWidth = 28;
const mapHeight = 22;
const mapFullHeight = 26;
const mapPitY256 = 192 * 256;
const levelMapData = new Array(1 + (mapWidth * mapFullHeight + 3) / 4); // 4 (header) + 28*22
const levelMap = levelMapData + 4;
function loadMap()
{
var levelName = currentLevel[0];
if (levelName == null)
{
save("_run.tmp", levels);
exec("results.js");
return ;
}
var levelMapI = levelMap;
file(levelName, levelMapData);
catsCount = 0;
sleepingCatsCount = 0;
currentLevel[2] = 0;
currentLevel[3] = 0;
for (var i = 0; i < length(entitiesStart); i++)
entitiesStart[i] = 0;
for (var tileJ = 0; tileJ < mapHeight; tileJ++)
for (var tileI = 0; tileI < mapWidth; tileI++, levelMapI++)
{
var tileIdentifier = peek(levelMapI);
var entityUpdate = null;
if (tileIdentifier == TILE_MC)
entityUpdate = updateMainCharacter;
if (tileIdentifier == TILE_CAT)
{
entityUpdate = updateCat;
catsCount++;
}
if (tileIdentifier == TILE_DOOR)
entityUpdate = updateDoor;
if (tileIdentifier == TILE_TREASURE)
{
currentLevel[3]++;
entityUpdate = updateTreasure;
}
// If we're using a null entityUpdate, it won't be adding any actual entity.
// addEntity(entityUpdateForTile[tileIdentifier], (tileI * 8 + 3) * 256, (tileJ * 8 + 7) * 256, entityAnimation);
addEntity(entityUpdate, (tileI << 3 + 7) << 8, (tileJ << 3 + 7) << 8, entityAnimationForTile[tileIdentifier]);
tile(tileI, tileJ, mapTiles[tileIdentifier]);
}
}
//////////////
// ENTITIES //
//////////////
// struct Entity
// {
// function Update; // [0] - Function called at each frame.
// int x256; // [1] - Center of the entity.
// int y256; // [2] - Bottom of the entity.
// int dx256; // [3] - Horizontal velocity.
// int dy256; // [4] - Vertical velocity.
// Animation animation; // [5] - Animation compound.
// int animationTimer; // [6] - Timer for the animation.
// bool mirror; // [7] - If true, the sprite will be mirrored.
// Unknown reserved[4]; // [8-11] - For extended structures.
// }
// Note: To search for field call, search for ntity[0] for ntity.update, ntity[1] for ntity.x256, etc.
const Entity_FIELDS = 10;
const Entity_SIZE = Entity_FIELDS * 4;
const entitiesCapacity = 24;
const entitiesStart = Array(entitiesCapacity * Entity_FIELDS);
const entitiesEnd = entitiesStart + entitiesCapacity * Entity_SIZE;
const mcEntity = entitiesEnd - Entity_SIZE;
// Every entity got its distance to the MC calculated even if they're not using it - costs less PROGMEM that way.
var distanceToMC256 = 0;
function addEntity(update, x256, y256, entityAnimation)
{
for (var i = 0; i < entitiesCapacity * Entity_FIELDS; i += Entity_FIELDS)
if (entitiesStart[i] == null)
{
if (update == updateMainCharacter)
i = entitiesCapacity * Entity_FIELDS - Entity_FIELDS;
// We're asserting we always have enough free entities!
for (var j = 0; j < Entity_FIELDS; j++)
entitiesStart[i + j] = 0;
entitiesStart[i] = update;
entitiesStart[i + 1] = x256;
entitiesStart[i + 2] = y256;
entitiesStart[i + 5] = entityAnimation;
break ;
}
}
function renderEntity(entity)
{
var animation = entity[5];
var animationStep = animation;
while (entity[6] >= animationStep[0])
animationStep += AnimationStep_SIZE;
var animationBitmap = animationStep[1];
if (animationBitmap == null)
{
entity[6] = 0;
animationBitmap = animation[1];
}
mirror(entity[7]);
sprite(entity[1] >> 8 - 7, entity[2] >> 8 - 15, animationBitmap);
}
////////////////////
// MAIN CHARACTER //
////////////////////
// struct Player: Entity
// {
// int jumpTimer; // [8] - Extra.
// }
// struct TestPoint
// {
// int rx256; [0]
// int ry256; [1]
// }
const characterTestPointsStart = [
-3*256, 0*256,
-3*256, -8*256,
-3*256, -14*256,
+3*256, 0*256,
+3*256, -8*256,
+3*256, -14*256
];
const MC_JUMP_ACCEL256 = -512;
const MC_JUMP_MAINTAINED_ACCEL256 = -32;
const MC_JUMP_MAX = 9;
const MC_GRAVITY_ACCEL256 = 32;
const MC_VERT_BRAKE256 = 256;
const MC_HORIZ_ACCEL256 = 32;
const MC_HORIZ_BRAKE256 = 240;
const MC_DEATH_DURATION = 30;
function mcIsColliding(movementX256, movementY256)
{
var entityX256 = mcEntity[1] + movementX256;
var entityY256 = mcEntity[2] + movementY256;
for (var i = 0; i < length(characterTestPointsStart); i += 2)
{
var tileI = (entityX256 + characterTestPointsStart[i]) >> 11; // / (8 * 256)
var tileJ = (entityY256 + characterTestPointsStart[i + 1]) >> 11; // / (8 * 256)
var tileIndex = tileJ * mapWidth + tileI;
if (peek(levelMap + tileIndex) >= TILE_FREE_MAX)
return true;
}
return false;
}
// Assumes mcEntity == entity.
function updateMainCharacter()
{
var entityDX256 = mcEntity[3];
var entityDY256 = mcEntity[4];
var entityJumpTimer = mcEntity[8];
for (var frame = 0; frame < 2; frame++)
{
var accel256 = (pressed("RIGHT") - pressed("LEFT")) * MC_HORIZ_ACCEL256;
if (accel256 != 0)
mcEntity[7] = accel256 < 0;
entityDX256 += accel256;
if (abs(entityDX256) >= 32)
{
mcEntity[6]++;
if (beginTime == 0)
beginTime = time();
}
// gravity
entityDY256 += MC_GRAVITY_ACCEL256;
// Maintained jump.
if (entityJumpTimer > 0)
{
entityJumpTimer--;
if (pressed("A"))
entityDY256 += MC_JUMP_MAINTAINED_ACCEL256;
}
if (mcIsColliding(entityDX256, 0))
entityDX256 = 0;
else
{
mcEntity[1] += entityDX256;
entityDX256 = entityDX256 * MC_HORIZ_BRAKE256 / 256;
}
if (mcIsColliding(0, entityDY256))
{
entityDY256 = 0;
// Cancels any jump maintenance.
entityJumpTimer = 0;
}
else
{
mcEntity[2] += entityDY256;
entityDY256 = entityDY256 * MC_VERT_BRAKE256 / 256;
}
// Jump ?
// && costs more.
if (mcIsColliding(0, 1*256))
{
if (entityDY256 >= 0)
{
if (pressed("A"))
{
entityDY256 = MC_JUMP_ACCEL256;
entityJumpTimer = MC_JUMP_MAX;
}
}
}
}
if (mcEntity[2] > mapPitY256)
{
mcEntity[0] = updateDeadMainCharacter;
addTempDecoration(mcEntity, bubbleDeathAnimation);
music("fall.raw");
}
mcEntity[3] = entityDX256;
mcEntity[4] = entityDY256;
mcEntity[8] = entityJumpTimer;
if (mcEntity[9])
{
currentLevel[1] = time() - beginTime;
currentLevel += Level_SIZE;
loadMap();
}
}
function updateDeadMainCharacter()
{
mcEntity[8]++;
if (mcEntity[8] > MC_DEATH_DURATION)
loadMap();
}
//////////
// CATS //
//////////
// struct Cat: Entity
// {
// int meowTimer; // [8] - Extra.
// }
const CAT_MC_DISTANCE256 = 8 * 256;
const CAT_MEOW_TIMER_MAX = 90;
const CAT_OFFSET_TO_MEOW = 16 * 256;
var entityMeowTimer = 0;
function updateCat(entity)
{
var entityAnimation = entity[5];
var entityAnimationTimer = entity[6];
entityAnimationTimer++;
// && costs more.
if (entityAnimation == catIdleAnimation)
{
if (entityMeowTimer <= 0)
if (!random(0, 8))
{
entityMeowTimer = CAT_MEOW_TIMER_MAX;
music("miaou.raw");
addTempDecoration(entity, bubbleMiaouAnimation);
}
if (distanceToMC256 <= CAT_MC_DISTANCE256)
{
entityAnimation = catFallingAsleepAnimation;
entityAnimationTimer = 0;
}
}
// && costs more.
if (entityAnimation == catFallingAsleepAnimation)
{
if (entityAnimationTimer == catFallingAsleepAnimationEnd)
{
entityAnimation = catSleepingAnimation;
sleepingCatsCount++;
addTempDecoration(entity, bubbleRonronAnimation);
}
}
entity[5] = entityAnimation;
entity[6] = entityAnimationTimer;
}
///////////
// DOORS //
///////////
// struct Door: Entity
// {
// }
const DOOR_MC_DISTANCE256 = 8 * 256;
function updateDoor(entity)
{
var entityAnimation = entity[5];
var entityAnimationTimer = entity[6];
entityAnimationTimer++;
// && costs more.
if (entityAnimation == doorClosedAnimation)
{
if (sleepingCatsCount == catsCount)
{
entityAnimation = doorOpeningAnimation;
entityAnimationTimer = 0;
}
}
// && costs more.
if (entityAnimation == doorOpeningAnimation)
if (entityAnimationTimer == doorOpeningAnimationEnd)
entityAnimation = doorOpenAnimation;
// Assigning it directly would save 4 bytes, but at the cost of not having multiple doors.
// && costs more.
if (entityAnimation == doorOpenAnimation)
if (distanceToMC256 < DOOR_MC_DISTANCE256)
mcEntity[9] = true; // Tells to go to the next level.
entity[5] = entityAnimation;
entity[6] = entityAnimationTimer;
}
/////////////////////
// TEMP DECORATION //
/////////////////////
// // A decoration that vanishes after a while.
// struct TempDecoration: Entity
// {
// int deathTimer; // [8] - If less than 30, the deco will vanish.
// }
function updateTempDecoration(entity)
{
entity[6]++;
entity[8]--;
if (entity[8] < -30)
entity[0] = null;
}
function addTempDecoration(entity, animation)
{
addEntity(updateTempDecoration, entity[1], entity[2] - CAT_OFFSET_TO_MEOW, animation);
}
//////////////
// TREASURE //
//////////////
// // A treasure that vanishes after being picked up by the MC
// struct Treasure: Entity
// {
// }
const TREASURE_MC_DISTANCE256 = 8 * 256;
function updateTreasure(entity)
{
if (distanceToMC256 < TREASURE_MC_DISTANCE256)
{
entity[0] = null;
currentLevel[2]++;
}
}
///////////////////
// INIT / UPDATE //
///////////////////
color(0);
tileshift(0, 0);
loadMap();
function update()
{
entityMeowTimer--;
for (var entity = entitiesStart; entity != entitiesEnd; entity += Entity_SIZE)
if (entity[0] != null)
{
distanceToMC256 = abs(entity[1] - mcEntity[1]) + abs(entity[2] - mcEntity[2]);
entity[0](entity);
renderEntity(entity);
}
}<file_sep>save("save/bookmark", "Book1/100.js");
const MARK = 0;
const GOTO = 1;
const text = [
MARK,
`
Marlock City is a huge sprawling
metropolis, enclosed in a
fortified wall said to have been
built one thousand years ago by
the ancient Shadar Empire. It is
the capital city of Sokara.
Marlock City was once known as
Sokar, until General Grieve
Marlock led the army in bloody
revolt against the old king, Corin
VII, and had him executed. The
general renamed the city after
himself - it is now a crime to
call it Sokar.
The general lives in the old
king's palace, and calls himself
the Protector-General of all`,
MARK,
`Sokara. Whereas the old king was
corrupt, the general rules with a
fist of iron. Some people like the
new regime; others are royalists,
still loyal to Nergan, the heir to
the throne, who has gone into
hiding somewhere.
Outside the city gates hang the
bodies of many dead people -
labels around their necks read:
'Rebels, executed by the state for
the good of the people'.
'You'd best behave yourself if
you don't want to end up like one
of them,' grates a guardsman,
nodding towards the swinging
corpses, as you pass through the
great eagle-headed gates of`,
MARK,
`Marlock City.
You can buy a town house in
Marlock City for 200 Shards.
Owning a house gives you a place
to rest, and to store equipment.
If you buy one, cross off 200
Shards and tick the box by the
town house option.
To leave Marlock City by sea, or
to buy or sell ships and cargo, go
the harbourmaster.
`,
GOTO,
"Book1/158.js",
`Visit the Three Rings Tavern`,
`
`,
GOTO,
"Book1/154.js",
`Visit the temple of Alvir and
Valmir`,
`
`,
GOTO,
"Book1/71.js",
`Visit the temple of Nagil`,
`
`,
GOTO,
"Book1/235.js",
`Visit the temple of Sig`,
`
`,
GOTO,
"Book1/568.js",
`Visit the temple of Elnir`,
`
`,
GOTO,
"Book1/396.js",
`Visit the market`,
MARK,
` `,
GOTO,
"Book1/142.js",
`Visit the harbourmaster`,
`
`,
GOTO,
"Book1/571.js",
`Go to the merchants' guild`,
`
`,
GOTO,
"Book1/138.js",
`Explore the city`,
`
`,
GOTO,
"Book1/434.js",
`Visit your town house {box} (if
box ticked)`,
`
`,
GOTO,
"Book1/535.js",
`Visit the House of Priests`,
`
`,
GOTO,
"Book1/601.js",
`Visit the general's palace`,
`
`,
GOTO,
"Book1/377.js",
`Travel east towards Trefoille`,
`
`,
GOTO,
"Book1/166.js",
`Head south-east towards the
Shadar Tor`,
`
`,
GOTO,
"Book1/99.js",
`Follow the River Grimm north`,
`
`,
GOTO,
"Book1/175.js",
`Journey north into the Curstmoor`,
`
`,
GOTO,
"Book1/579.js",
`Head west to the River Grimm
delta`,
MARK
];
const funcs = new Array(5);
funcs[MARK] = f_mark;
funcs[GOTO] = f_goto;
window(0, 0, 220, 176);
io("FILLER", 3, "TEXT", "5x7");
io("FORMAT", 0, 0);
var index, selection = 0;
var position = 1, mark = 0;
var isLastMark = false;
render();
function f_mark(){
position = index + 1;
mark = index;
}
function f_goto(trigger){
var page = text[index + 1];
var caption = text[index + 2];
var selected = ((index - mark) == selection);
if(selected) print("[");
else print(" ");
print(caption);
if(selected) print("]");
else print(" ");
index += 2;
if(trigger){
position = -1;
splash(0, 0, "splash.565");
window(0, 166, 220, 176);
io("CLEARTEXT");
cursor(1, 21);
print(caption);
exec(page);
}
}
function isText(i){
var line = text[i];
return line < 0 || line >= length(funcs);
}
function render(){
if(position < 0)
return;
io("CLEARTEXT");
fill(0);
cursor(0,0);
color(32);
index = position;
for(; text[index] != MARK; ++index){
var line = text[index];
if(isText(index)) print(line);
else funcs[line](false);
}
isLastMark = index == length(text) - 1;
color(7);
}
function update(){
if(justPressed("C"))
exit();
if(justPressed("A")){
index = mark + selection;
funcs[text[index]](true);
render();
}
if(!isLastMark){
flip(true);
sprite(220-8, 176-8, builtin("cursor2"));
}
var direction = justPressed("DOWN") - justPressed("UP");
if(direction == 0){
return;
}
var prevPrev = 0;
var prevMark = 0;
var prevSelection = -1;
var curSelection = -1;
var absSelection = mark + selection + (direction > 0);
index = (mark + selection) * (direction > 0);
for( ; (prevSelection != absSelection) && (isText(curSelection) || curSelection < absSelection); ++index){
if(index >= length(text)) return;
if(isText(index)) continue;
prevSelection = curSelection;
curSelection = index;
var line = text[index];
if(line != MARK){
funcs[line](false);
} else {
prevPrev = prevMark;
prevMark = index;
}
}
if(direction > 0){
index = curSelection;
}else{
if(prevSelection < mark){
if(mark == 0)
return;
index = prevPrev;
funcs[MARK](false);
}
index = prevSelection;
}
if(text[index] == MARK){
if(isLastMark && direction > 0){
render();
return;
}
selection = 0;
}else
selection = index - mark;
funcs[text[index]](false);
render();
}
<file_sep>const minX = 6, maxX = 22;
const minY = 0, maxY = 20;
const boardWidth = maxX - minX;
const boardHeight = maxY - minY;
const heart = builtin("sHeart");
const lvl = builtin("sLvl");
const pts = builtin("sPts");
const ledOFF = builtin("shape1");
const ledON = builtin("sBtn");
const paddleColor = 112;
const bgColor = 129;
const ballColor = 119;
var levels = new Array(27);
var paddleX, bx, by, vx, vy;
var dead, won = 0;
var stepTime;
var level = 0;
var score = 0;
var prevScore = 0;
var lives = 3;
var remaining = 0;
var paddleSize = 3;
levels[0] = builtin("icon1");
levels[1] = builtin("icon2");
levels[2] = builtin("icon3");
levels[3] = builtin("icon4");
levels[4] = builtin("icon5");
levels[5] = builtin("icon6");
levels[6] = builtin("icon7");
levels[7] = builtin("icon8");
levels[8] = builtin("icon9");
levels[9] = builtin("icon10");
levels[10] = builtin("icon11");
levels[11] = builtin("icon12");
levels[12] = builtin("icon13");
levels[13] = builtin("icon14");
levels[14] = builtin("icon15");
levels[15] = builtin("icon16");
window(44, 0, 176, 176);
tileshift(2, 0);
reset();
function reset(){
if(lives < 0){
highscore(score);
exit();
return;
}
score = prevScore;
if(level > 15){
paddleSize = 2;
} else if(level > 30){
paddleSize = 1;
}
color(bgColor);
for(y = 0; y < boardHeight; ++y){
for(var x = 0; x < boardWidth; ++x){
tile(x + minX, y + minY, ledOFF);
}
}
remaining = 0;
pattern(0, -3, levels[level & 0xF]);
bx = (boardWidth / 2) << 8;
by = (boardHeight - 2) << 8;
paddleX = boardWidth / 2;
vx = (random(4, 10) + level) * 5;
vy = 0;
dead = false;
won = 0;
}
function pattern(x, y, img){
var w = peek(img++);
var h = peek(img++);
x += minX;
y += minY;
var t = peek(img, 0);
if(y < 0){
img += w * -y;
h += y;
y = 0;
}
for(var ty = 0; ty < h; ++ty){
for(var tx = 0; tx < w; ++tx){
var c = peek(img, tx);
if(c && (c != t)){
color(c - 7);
tile(x + tx, y + ty, ledOFF);
++remaining;
}
}
img += w;
}
}
function hud(){
color(47);
sprite(50, 165, lvl);
cursor(60, 165);
printNumber(level + 1);
sprite(110, 165, pts);
cursor(120, 165);
printNumber(score);
color(0);
for(var i=0; i<lives; ++i)
sprite(80 + (i * 8), 165, heart);
}
function hitBlock(){
var tx = ((bx + 128) >> 8) + minX;
var ty = ((by + 128) >> 8) + minY;
var c = io("COLOR", tx, ty);
if(c == bgColor)
return false;
if(c != paddleColor){
color(bgColor);
tile(tx, ty, ledOFF);
--remaining;
++score;
} else {
by -= 255;
vx += ((bx >> 8) - paddleX) * random(4, 8) << 3;
vx >>= 1;
}
io("VOLUME", 127);
io("DURATION", 100);
sound(random(44, 47));
return true;
}
function update(){
if(pressed("C"))
exit();
hud();
if(pressed("LEFT")){
paddleX--;
if( (paddleX - paddleSize) < 0 ){
paddleX = paddleSize;
}
}else if(pressed("RIGHT")){
paddleX++;
if( (paddleX + paddleSize) >= boardWidth ){
paddleX = (boardWidth - 1) - paddleSize;
}
}else if(pressed("UP") && (vy == 0)){
vy = -(20 + level) * 7;
}
for(var i=0; i<boardWidth; ++i){
var led = ledON;
if( (i < (paddleX - paddleSize)) || (i > (paddleX + paddleSize)) ){
led = ledOFF;
color(bgColor);
}else{
color(paddleColor);
}
tile(i + minX, minY + (boardHeight - 1), led);
}
by += vy;
if( by < 0 ){
by = 0;
vy = -vy;
} else if( ((by + 128) >> 8) >= boardHeight ){
--lives;
reset();
return;
}
if(hitBlock())
vy = -vy;
bx += vx;
if( bx < 0 ){
bx = 0;
vx = -vx;
} else if( bx >= ((boardWidth - 1) << 8) ){
bx = ((boardWidth - 1) << 8);
if(vx > 0)
vx = -vx;
}
if(hitBlock())
vx = -vx;
color(ballColor);
sprite((bx >> 5) + (minX << 3), (by >> 5) + (minY << 3), ledON);
if(remaining <= 0){
prevScore = score;
++level;
if(!(level % 5) && (lives < 3)){
++lives;
}
reset();
}
}
| abc71fff12e25fb039fc88d220eff15ba0b09d17 | [
"JavaScript",
"Markdown",
"INI"
] | 29 | JavaScript | pokitto/GameDisk | 3d1635b4be712e1ff397afa4b0ccb724014cec3f | ce2102dbc6de06710ac457089ca6daa3d0ca36d6 | |
refs/heads/master | <file_sep>from typing import List
if __name__ == "__main__":
nbr_entier = int(input("Entrez un entier strictement positif: "))
nbr_list: List[int] = []
nbr = 1
while nbr < nbr_entier:
nbr = nbr + 1
if nbr_entier % nbr == 0:
nbr_list.append(nbr)
nbr_list.pop(len(nbr_list) - 1)
if len(nbr_list) > 0:
print("Diviseur propre sans répétition de", nbr_entier, ": ", nbr_list)
print("il a ", len(nbr_list), " diviseurs propres")
else:
print("Diviseur propre sans répétition de", nbr_entier, ": aucun")
print("il est deja premier!")
<file_sep>import turtle as tt
def forme(turtle=tt, long_base=5, angle=0, cote=3):
turtle.right(angle)
for x in range(cote):
turtle.forward(long_base)
turtle.right(-360 / cote)
def move(turtle=tt, x=None, y=None):
turtle.up()
if x is None:
x = turtle.pos()[0]
if y is None:
y = turtle.pos()[1]
turtle.setposition(x, y)
turtle.down()
if __name__ == "__main__":
pen = tt.Turtle()
pen.width(5)
pen.speed(40)
pen.color('gray')
move(pen, -400, -300)
pen.forward(800)
move(pen, 350, -300)
pen.color('brown')
pen.left(90)
pen.forward(450)
pen.color('green')
for x in range(0, 6):
forme(turtle=pen, long_base=80, angle=(-60), cote=3)
pen.color('brown')
move(pen, 350, -180)
pen.right(-70)
pen.forward(120)
pen.color('green')
for x in range(0, 6):
forme(turtle=pen, long_base=60, angle=(-60), cote=3)
pen.color('brown')
move(pen, 350, -50)
pen.forward(120)
pen.color('green')
for x in range(0, 6):
forme(turtle=pen, long_base=60, angle=(-60), cote=3)
pen.right(70)
pen.color('cyan')
move(pen, -250, 200)
for x in range(0, 6):
forme(turtle=pen, long_base=40, angle=(-60), cote=3)
move(pen, -150, 120)
for x in range(0, 6):
forme(turtle=pen, long_base=40, angle=(-60), cote=3)
move(pen, -100, 230)
for x in range(0, 6):
forme(turtle=pen, long_base=40, angle=(-60), cote=3)
move(pen, 0, 130)
for x in range(0, 6):
forme(turtle=pen, long_base=40, angle=(-60), cote=3)
move(pen, 50, 240)
for x in range(0, 6):
forme(turtle=pen, long_base=40, angle=(-60), cote=3)
pen.color("yellow")
move(pen, -300, -260)
for x in range(0, 6):
forme(turtle=pen, long_base=40, angle=(-60), cote=3)
pen.color("orange")
pen.right(35)
pen.forward(60)
pen.left(35)
guidon = pen.pos()
pen.color("yellow")
move(pen, -176, -260)
for x in range(0, 6):
forme(turtle=pen, long_base=40, angle=(-60), cote=3)
pen.color("orange")
move(pen, -206, -210)
pen.right(-30)
for x in range(0, 2):
forme(turtle=pen, long_base=60, angle=-60, cote=3)
pen.color("red")
pen.right(-160)
pen.forward(25)
pen.right(40)
pen.backward(25)
move(pen, guidon[0], guidon[1])
pen.left(40)
pen.forward(25)
pen.ht()
tt.done()
<file_sep>import numpy as np
if __name__ == "__main__":
rayon = float(input("Rayon: "))
hauteur = float(input("hauteur: "))
volume = 1/3 * np.pi * rayon**2 * hauteur
print("le volume est: ", volume)
<file_sep>import random as rd
def validator(str="atg"):
nbr_str = 0
for n in str:
for verf in "atgc":
if n == verf:
nbr_str = nbr_str + 1
if len(str) == nbr_str:
return True
else:
return False
def randomSaisie():
list_atcg = "atgc"
output = ""
for e in range(rd.randrange(8,450)):
for i in range(rd.randrange(0, 5)):
output = output + list_atcg[i]
return output
if __name__ == "__main__":
str = randomSaisie()
print(str)
valid = validator(str)
if valid:
print("chaine valide")
else:
print("chaine invalide")
print("{0:.2f}".format(1.35555533), "test")<file_sep>if __name__ == "__main__":
hauteur = int(input("Taille du sapin:\nhauteur:"))
branche = ['^']
space = ' '
for y in range(0, hauteur - 1):
branche.append('^' + branche[y] + '^')
print(int(hauteur-y)*space + branche[y])
<file_sep>import turtle as tt
def forme(turtle=tt, long_base=5, angle=0, cote=3 ):
turtle.right(angle)
for x in range(cote):
turtle.forward(long_base)
turtle.right(-360/cote)
def move(turtle=tt, x=None, y=None):
turtle.up()
if x is None:
x = turtle.pos()[0]
if y is None:
y = turtle.pos()[1]
turtle.setposition(x, y)
turtle.down()
if __name__ == "__main__":
pen = tt.Turtle()
pen.color('red')
pen.width(3)
move(pen, 20)
forme(turtle=pen, long_base=40, angle=0, cote=4)
pen.color('green')
move(pen, 0, 80)
forme(turtle=pen, long_base=80, angle=0, cote=3)
move(pen, 0,0)
pen.color('black')
forme(turtle=pen, long_base=80, angle=0, cote=4)
tt.mainloop()
| 5643bfeefa28cc770cc101d157b9098abaf8c0e9 | [
"Python"
] | 6 | Python | EDU-FRANCK-JUBIN/exercices-sur-python-aerodomigue | 20630ee2131c1519d3abd3d3b90387441c50ebcb | 7702e9b6fe0e7d27401d15121a56d1cf7427d7d0 | |
refs/heads/master | <repo_name>lakshmanreddy725/lucky<file_sep>/.bash_history
cd
grep ssh /etc/services
sudo systemctl stop firewalld.service
systemctl stop firewalld.service
cd
cd /opt
ls
ll
yum -y install wget
wget --version
rpm -qa wget
wget https://github.com/gitbucket/gitbucket/releases/download/4.32.0/gitbucket.war
ls
ip a
sudo systemctl stop firewalld.service
yum -y install firewalld
sudo systemctl stop firewalld.service
java -jar gitbucket.war
sudo yum -y install java-1.8.*
java -version
java -jar gitbucket.war
sudo systemctl stop firewalld.service
firewall-cmd --permanent --add-port=8080/tcp
systemctl start gitbucket systemctl enable gitbucket
systemctl start gitbucket systemctl enable gitbucket.war
sudo systemctl start gitbucket systemctl enable gitbucket.war
sudo systemctl start gitbucket
systemctl status gitbucket
cd /root/.gitbucket/tmp/webapp
cd /root/.gitbucket/tmp/
cd
cd /root/.gitbucket/tmp/
cd /root/
ll
cd /opt/
ll
ip
ip a
port
sudo grep <port> /etc/services
sudo grep 8080 /etc/services
sudo grep 8090 /etc/services
cd
cd /opt/
ll
systemctl stop firewalld.service
java -jar gitbucket.war
update gitbucket.war
yum update -y gitbucket.war
tar -ivh gitbucket.war
tar -xvfz gitbucket.war
java -jar gitbucket.war
git init
cd ..
cd /opt/
ll
git init
git -version
sudo yum -y install git
git init
touch ll.txt
ll
vi ll.txt
git add ll.txt
git status
git commit -m "ll file"
git status
git remote add origin http://ec2-13-232-202-88.ap-south-1.compute.amazonaws.com:8080/git/root/laxm.git
git remote add origin master
git push -u origin master
sudo git push -u origin master
git push -u origin master
ec2 git push -u origin master
git push -u origin master
git push -u origin master
cd /opt/
ls
java -jar gitbucket.war
git remote add origin http://ec2-13-232-202-88.ap-south-1.compute.amazonaws.com:8080/git/root/laxm.git
git push -u origin master
java -jar gitbucket.war
git push -u origin master
java -jar gitbucket.war
cd
cd /opt/
ll
java -jar gitbucket.war
git push -u origin master
git remote add origin http://ec2-13-232-202-88.ap-south-1.compute.amazonaws.com:8080/git/root/laxm.git
push -u origin master
git push -u origi master
git push -u origin master
java -jar gitbucket.war
git push -u origin master
clean
clear
git push -u origin master
ip a
ip a
git push -u origin master
cd
cd
java -jar gitbucket.war
cd /opt/
ll
java -jar gitbucket.war
ls
cd /opt/
ls
java -jar gitbucket.war
clear
ll
java -jar gitbucket.war
cd
pwd
host
host
hostname
su ec2-user
cd
ip a
su
passwd root
users
useradd jenkins
chown -R jenkins:jenkins
chown -R root:jenkins
chown -R jenkins:root
chown --help
usermod -aG JENKINS
usermod -aG jenkins
usermod -aG wheel jenkins
chown -R jenkins:root
chown -R root:jenkins
vi .ssh/authorized_keys
cd .ssh/
ll
chown u+x authorized_keys
chown 700 authorized_keys
ll
chown 777 authorized_keys
ll
chown -R jenkins
chown -R jenkins authorized_keys
ll
chown -R jenkins:jenkins authorized_keys
ll
chown 777 authorized_keys
ll
exit
cd
useradd jenkins
passwd jenkins
su - jenkins
ls
ls -al
cd
ls
cd /opt/
ls
ll
systemctl stop firewalld.service
systemctl status firewalld.service
java -jar gitbucket.war
cd
git init
ll
vi laxman.txt
chmod u+x laxman.txt
git add laxman.txt
git commit -m "commited file"
git remote add origin <EMAIL>:lakshmanreddy725/tomcatdeploy.git
git push -u origin master
sudo git push -u origin master
ll
chmod 777 laxman.txt
ll
sudo git push -u origin master
cd
| 38e7e3240c24b415511870f999be92e09a51a05b | [
"Shell"
] | 1 | Shell | lakshmanreddy725/lucky | a4a0d14eb8011e5727c18c9e70b97efc30e55e2b | fad085b397343d330b1e0cf03f6a053ece578e1f | |
refs/heads/master | <repo_name>jzorjnz/ST_SENSOR_JS_DEMO<file_sep>/mbedos5/build.py
import os
import subprocess
from subprocess import call
import sys
# default board name
board_name = "NUCLEO_F429ZI"
# get the input argument
if len(sys.argv) != 2:
print 'usage : build.py <BOARD> \ne.g build.py ' + board_name +'\nYou must specify which board to target'
sys.exit(1)
else:
board_name = sys.argv[1]
# mbed configuration
call("mbed config root .", shell=True)
call("mbed toolchain GCC_ARM", shell=True)
call("mbed target " + board_name, shell=True)
#call("mbed deploy", shell=True)
# make dirs
if not os.path.exists("./source"):
os.makedirs("./source")
if not os.path.exists("./js"):
os.makedirs("./js")
# generate target.js
target_board = subprocess.check_output(['mbed', 'target']).split( )
if(len(target_board) != 2):
print 'Error generating target!'
sys.exit(1)
with open("js/target.js", "w") as text_file:
text_file.write("var TARGET = '%s';" % target_board[1])
# generate pins.js
call("python tools/generate_pins.py " + board_name, shell=True)
call("python ../../tools/js2c.py --dest ./source --js-source js --ignore pins.js", shell=True)
# compile using mbed cli
call("mbed compile -j0 --source . --source ../../ -D \"CONFIG_MEM_HEAP_AREA_SIZE=(1024*16)\" -t GCC_ARM", shell=True)
<file_sep>/mbedos5/source/main.cpp
var timeOut = 1000;
var timeStatus = timeOut/10;
var led1 = null;
//led2.write(0);
var i2c = null;
var spi = null;
var hts221 = null;
var lps22hb = null;
var lsm6dsl = null;
var lsm303agr = null;
var acc = null;
var gyr = null;
var acc2 = null;
var mag2 = null;
/*
if(window.TARGET_SENSOR_TILE !== undefined){
print("TARGET_SENSOR_TILE exists!");
}
else{
print("TARGET_SENSOR_TILE does not exist!");
}
*/
//print ("TARGET = " + TARGET);
/*
if(TARGET == "NUCLEO_F429ZI"){
}
else if (TARGET == "NUCLEO_L476RG"){
spi = SPI(PB_15, NC, PB_13);
led1 = DigitalOut(0x6C);
//spi = SPI(31, 4294967295, 29);
}
*/
//var spi = SPI(PB_15, NC, PB_13);
//var spi = SPI(31, 4294967295, 29);
//var TARGET = "NUCLEO";
var count = 0;
var iv = setInterval(function() {
if(count < 2){
print(".");
count = count + 1;
}
else if(count == 2){
count++;
print ("TARGET = " + TARGET);
if(TARGET == "NUCLEO_F429ZI"){
i2c = DevI2C(D14, D15);
led1 = DigitalOut(LED1);
print("Loading HTS221 sensor...");
hts221 = HTS221_JS();
hts221.init_i2c(i2c);
print("Loading complete.");
print("Loading LPS22HB sensor...");
lps22hb = LPS22HB_JS();
lps22hb.init_i2c(i2c);
print("Loading complete.");
print("Loading LSM6DSL sensor...");
lsm6dsl = LSM6DSL_JS();
lsm6dsl.init_i2c(i2c);
print("Loading complete.");
print("Loading LSM303AGR sensor...");
lsm303agr = LSM303AGR_JS();
lsm303agr.init_acc_i2c(i2c);
lsm303agr.init_mag_i2c(i2c);
print("Loading complete.");
}
else if (TARGET == "NUCLEO_L476RG"){
spi = SPI(PB_15, NC, PB_13);
led1 = DigitalOut(0x6C);
print("Loading LPS22HB sensor...");
lps22hb = LPS22HB_JS();
lps22hb.init_spi(spi, PA_3, NC, 3);
print("Loading complete.");
print("Loading LSM6DSL sensor...");
lsm6dsl = LSM6DSL_JS();
lsm6dsl.init_spi(spi, PB_12, NC, PA_2, 3);
print("Loading complete.");
print("Loading LSM303AGR sensor...");
lsm303agr = LSM303AGR_JS();
lsm303agr.init_acc_spi(spi, PC_4);
lsm303agr.init_mag_spi(spi, PB_1);
print("Loading complete.");
}
led1.write(0);
/*
print("Loading LSM303AGR sensor...");
lsm303agr = LSM303AGR_JS(i2c);
print("Loading complete.");
*/
//hts221.led_on(led2);
}
else{
led1.write(led1.read()? 0: 1);
print("");
if(TARGET == "NUCLEO_F429ZI"){
print("HTS221: [Temperature] " + hts221.get_temperature() + " C, [Humidity] " + hts221.get_humidity() + "%");
}
print("LPS22HB: [Temperature] " + lps22hb.get_temperature() + " C, [Pressure] " + lps22hb.get_pressure() + " mbar");
acc = JSON.parse(lsm6dsl.get_accelerometer_axes());
gyr = JSON.parse(lsm6dsl.get_gyroscope_axes());
print("LSM6DSL: [Gyroscope]: " + gyr.x + ", " + gyr.y + ", " + gyr.z +
" [Accelerometer]: " + acc.x + ", " + acc.y + ", " + acc.z);
print("Printing LSM303AGR");
acc2 = JSON.parse(lsm303agr.get_accelerometer_axes());
mag2 = JSON.parse(lsm303agr.get_magnetometer_axes());
print("LSM303AGR: [Magnetometer]: " + mag2.x + ", " + mag2.y + ", " + mag2.z +
" [Accelerometer]: " + acc2.x + ", " + acc2.y + ", " + acc2.z);
print("");
setTimeout(function(){ led1.write(led1.read()? 0: 1) }, timeStatus);
}
}, timeOut);
// Call this function to clear the interval started above
//clearInterval(iv);
print("main.js has finished executing.");
<file_sep>/README.md
# ST_SENSOR_JS_DEMO
Demo for accessing ST sensors using Javascript on Mbed OS.
## Installation
* Before you begin, first follow this tutorial to have a pre built Mbed OS project with Jerryscript here: https://github.com/ARMmbed/mbed-js-example
* After you have built the project, you should have a binary for your board. If not, resolve the errors to continue. If you have errors related to generation of pins, checkout the known issues below.
* Now, clone this repository and copy to the following directory of the mbed-js-example project:
```
mbed-js-example/build/jerryscript/targets/
```
Make sure to replace existing files in mbedos5 directory.
## Build
* When you are building the project for the first time, run this command:
```
cd mbed-js-example/build/jerryscript/targets/mbedos5
python ./build_all.py <BOARD>
```
This makes sure that all the required libraries are downloaded.
* If building next time, run this command:
```
cd mbed-js-example/build/jerryscript/targets/mbedos5
python ./build.py <BOARD>
```
## Development
Your Mbed OS project resides in mbedos5 directory, put js files in mbedos5/js directory. Building will take care of everything.
## Known issues
### Pin generation error
For some boards, pin generation is failing in Jerryscript. For the time being, you can skip some pin expressions in configuration to build for most boards by following these steps:
Open mbed-js-example/jerryscript/targets/mbedos5/tools/generate_pins.py
Put this line in try statement:
```
try:
pins[pin.name] = evaluator.eval(expr.strip())
except:
print("[Warning] Skipping pin name: " + expr.strip())
```
After doing this, do installation again and then try building.
| 70bc5be45d5c13302a3c77524f3fb2b96a72cc12 | [
"Markdown",
"Python",
"C++"
] | 3 | Python | jzorjnz/ST_SENSOR_JS_DEMO | 651653485fd36a380f62ee833478ede2248ac21b | 3e4dcc29968f2ff7e28480fa58003065951a8110 | |
refs/heads/master | <repo_name>napo5/connect4CLI<file_sep>/README.md
# connect4CLI
Java implementation of Connect Four game
<file_sep>/test/com/unicam/cs/pa/player/RandomPlayerTest.java
package com.unicam.cs.pa.player;
import com.unicam.cs.pa.core.Disc;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RandomPlayerTest {
@Test
void getMove() {
RandomPlayer rp = new RandomPlayer("user", Disc.RED);
assertTrue(rp.getMove()>=1);
assertTrue(rp.getMove()<=7);
}
}<file_sep>/src/com/unicam/cs/pa/player/notExistentColumnException.java
package com.unicam.cs.pa.player;
public class notExistentColumnException extends Exception {
@Override
public String getMessage() {
return "The number must be between 1 and 7! Try again.";
}
}
<file_sep>/src/com/unicam/cs/pa/player/RandomPlayer.java
package com.unicam.cs.pa.player;
import com.unicam.cs.pa.core.Disc;
public class RandomPlayer extends COMPlayer {
public RandomPlayer(String username, Disc color) {
super(username, color);
}
@Override
public int getMove() {
return randomMove();
}
}
<file_sep>/src/com/unicam/cs/pa/match/COMVsCOM.java
package com.unicam.cs.pa.match;
import com.unicam.cs.pa.core.Disc;
import com.unicam.cs.pa.core.Utils;
import com.unicam.cs.pa.player.COMFactory;
import com.unicam.cs.pa.player.COMPlayer;
import com.unicam.cs.pa.player.Player;
/*
RESPONSABILITÀ : Gestisce una partita tra due giocatori virtuali.
*/
public class COMVsCOM extends Match {
private boolean fastMode;
public COMVsCOM(COMPlayer p1, COMPlayer p2) {
super(p1, p2);
}
public COMVsCOM(COMPlayer p1, COMPlayer p2, boolean fastMode) {
super(p1, p2);
this.fastMode = true;
}
public COMVsCOM() {
COMFactory comFactory = new COMFactory();
players[0] = comFactory.createPlayer(Disc.RED);
Utils.blankLine();
players[1] = comFactory.createPlayer(Disc.YELLOW);
}
@Override
protected void notifyTurn(Player currentPlayer) {
if (fastMode) {// does not print
} else super.notifyTurn(currentPlayer);
}
@Override
protected void updateBoard() {
if (fastMode) {// does not print
} else super.updateBoard();
}
@Override
protected void notifyWin(Player winner) {
super.notifyWin(winner);
if (fastMode) Utils.printBoard(gameBoard);
}
}
<file_sep>/src/com/unicam/cs/pa/player/COMFactory.java
package com.unicam.cs.pa.player;
import com.unicam.cs.pa.core.Disc;
import java.util.InputMismatchException;
import java.util.Scanner;
/*
RESPONSABILITÀ : Gestisce l'input utente per creare istanza di COMPlayer desiderata.
*/
public class COMFactory implements PlayerFactory {
@Override
public COMPlayer createPlayer(Disc color) {
printCOMInstructions();
Scanner comInput = new Scanner(System.in);
int comType = 0;
try {
comType = comInput.nextInt();
} catch (InputMismatchException ex) {
System.out.println("Wrong Input! Please try again.");
return createPlayer(color);
}
COMPlayer com = null;
switch (comType) {
case 1:
com = new RandomPlayer("EasyCOM", color);
break;
case 2:
com = new GoofPlayer("GoofCOM", color);
break;
case 3:
com = new SmartPlayer("SmartCOM", color);
break;
default:
System.out.println("Invalid option");
createPlayer(color);
}
return com;
}
@Override
public Player getPlayer() {
return null;
}
private void printCOMInstructions() {
System.out.println("COM Player setup :");
System.out.println("Select type of COM player");
System.out.println("[1] (Easy) Random COM");
System.out.println("[2] (Medium) Goof COM");
System.out.println("[3] (Hard) Smart COM");
}
}
<file_sep>/src/com/unicam/cs/pa/player/SmartPlayer.java
package com.unicam.cs.pa.player;
import com.unicam.cs.pa.core.Disc;
public class SmartPlayer extends COMPlayer {
public SmartPlayer(String username, Disc color) {
super(username, color);
}
/*
SmartCOM move checks if there is a row of three discs with same color:
if he can close a four-in-a-row and win he wins
if the opponent can close a four-in-a-row he denies it.
*/
@Override
public int getMove() {
return fourthInARow();
}
private int fourthInARow() {
for (int i = 1; i <= 7; i++) {
if (gameBoardCopy.winCheck(Disc.RED, gameBoardCopy.getColumnCounter(i)+1, i)) {
return i;
}
}
for (int i = 1; i <= 7; i++) {
if (gameBoardCopy.winCheck(Disc.YELLOW, gameBoardCopy.getColumnCounter(i)+1, i)) {
return i;
}
}
// if there are no winning moves
return randomMove();
}
}
<file_sep>/src/com/unicam/cs/pa/core/FilledColumnException.java
package com.unicam.cs.pa.core;
public class FilledColumnException extends Exception {
@Override
public String getMessage() {
return "The column selected is full!";
}
}
<file_sep>/src/com/unicam/cs/pa/match/MatchBuilder.java
package com.unicam.cs.pa.match;
import com.unicam.cs.pa.player.Player;
import java.util.Scanner;
/*
RESPONSABILITÀ : Gestisce l'input utente per creare istanza di Match desiderata.
*/
public class MatchBuilder {
protected boolean rematch;
protected Match match;
public Match getMatch() {
createNewMatch();
return match;
}
public void playAndRematch() {
boolean rematch = true;
while (rematch) {
getMatch();
match.executeMatch();
rematch = askRematch();
}
}
public void createNewMatch() {
Player[] players = new Player[2];
printInstructions();
Scanner matchInput = new Scanner(System.in);
int matchType = matchInput.nextInt();
switch (matchType) {
case 1:
match = new HumanVsCOM();
break;
case 2:
match = new HumanVsHuman();
break;
case 3:
match = new COMVsCOM();
break;
default:
System.out.println("Invalid option");
createNewMatch();
}
}
private void printInstructions() {
System.out.print("Select type of match \n" +
"[1] 1P vs COM \n" +
"[2] 1P VS 2P \n" +
"[3] COM VS COM \n");
}
public boolean askRematch() {
boolean rematch = false;
System.out.println("Play Again ? (Y/n)");
Scanner rematchInputSC = new Scanner(System.in);
char rematchInput = rematchInputSC.next().charAt(0);
switch (rematchInput) {
case 'Y':
rematch = true;
break;
case 'N':
rematch = false;
System.exit(0);
break;
default:
System.out.println("Wrong Input");
return askRematch();
}
return rematch;
}
}
<file_sep>/src/com/unicam/cs/pa/core/Main.java
package com.unicam.cs.pa.core;
import com.unicam.cs.pa.match.MatchBuilder;
/*
RESPONSABILITÀ : esecuzione del programma
*/
public class Main {
public static void main(String[] args) {
MatchBuilder matchBuilder = new MatchBuilder();
matchBuilder.playAndRematch();
}
}
<file_sep>/test/com/unicam/cs/pa/core/GameBoardTest.java
package com.unicam.cs.pa.core;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class GameBoardTest {
@Test
void verticalStreak() {
GameBoard gb = new GameBoard();
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,1);
int streak = gb.directionCheck(Disc.RED,Direction.DOWN,4,1);
assertTrue(streak==4);
assertTrue(gb.winCheck(Disc.RED,4,1));
}
@Test
void verticalWin(){
}
@Test
void horizontalStreak() {
GameBoard gb = new GameBoard();
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,3);
gb.dropDisc(Disc.RED,2);
gb.dropDisc(Disc.RED,4);
int streak = gb.directionCheck(Disc.RED,Direction.RIGHT,1,1);
assertTrue(streak==4);
}
@Test
void shouldNotWin() {
GameBoard gb = new GameBoard();
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,3);
gb.dropDisc(Disc.RED,2);
assertFalse(gb.winCheck(Disc.RED,1,1));
}
@Test
void horizontalReverseStreak(){
GameBoard gb = new GameBoard();
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,3);
gb.dropDisc(Disc.RED,2);
gb.dropDisc(Disc.RED,4);
int streak = gb.directionCheck(Disc.RED,Direction.LEFT,1,4);
assertTrue(streak==4);
}
@Test
void diagonalStreak() {
GameBoard gb = new GameBoard();
gb.dropDisc(Disc.YELLOW,1);
gb.dropDisc(Disc.RED,2);
gb.dropDisc(Disc.RED,3);
gb.dropDisc(Disc.RED,4);
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.YELLOW,2);
gb.dropDisc(Disc.RED,3);
gb.dropDisc(Disc.RED,4);
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,2);
gb.dropDisc(Disc.YELLOW,3);
gb.dropDisc(Disc.RED,4);
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,2);
gb.dropDisc(Disc.RED,3);
gb.dropDisc(Disc.YELLOW,4);
int streak = gb.directionCheck(Disc.YELLOW,Direction.UPRIGHT,1,1);
assertTrue(streak==4);
assertTrue(gb.winCheck(Disc.YELLOW,2,2));
}
@Test
void latestDisc(){
GameBoard gb = new GameBoard();
gb.dropDisc(Disc.YELLOW,1);
assertTrue(gb.getLatestDisc()==Disc.YELLOW);
assertTrue(gb.getLatestDiscCol()==1);
assertTrue(gb.getLatestDiscRow()==1);
}
@Test
void isLegit(){
GameBoard gb = new GameBoard();
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,1);
gb.dropDisc(Disc.RED,1);
assertFalse(gb.isLegit(1));
assertFalse(gb.isLegit(0));
assertFalse(gb.isLegit(9));
}
@Test
void isDraw() {
GameBoard gb = new GameBoard();
for (int i = 1; i <= 6; i++) {
gb.dropDisc(Disc.RED, 1);
gb.dropDisc(Disc.RED, 2);
gb.dropDisc(Disc.RED, 3);
gb.dropDisc(Disc.RED, 4);
gb.dropDisc(Disc.RED, 5);
gb.dropDisc(Disc.RED, 6);
gb.dropDisc(Disc.RED, 7);
}
assertTrue(gb.isDraw());
}
}<file_sep>/src/com/unicam/cs/pa/player/COMPlayer.java
package com.unicam.cs.pa.player;
import com.unicam.cs.pa.core.Disc;
import java.util.Random;
/*
RESPONSABILITÀ : Rappresenta giocatore artificiale.
*/
public abstract class COMPlayer extends Player {
public COMPlayer(String username, Disc color) {
super(username, color);
}
/**
* @return integer between 1 and 7
* useful for returning a random column number
*/
protected int randomMove() {
int move = new Random().nextInt(7) + 1;
while (!gameBoardCopy.isLegit(move))
move = new Random().nextInt(7) + 1;
return move;
}
}
<file_sep>/src/com/unicam/cs/pa/match/HumanVsCOM.java
package com.unicam.cs.pa.match;
import com.unicam.cs.pa.core.Disc;
import com.unicam.cs.pa.core.Utils;
import com.unicam.cs.pa.player.COMFactory;
import com.unicam.cs.pa.player.COMPlayer;
import com.unicam.cs.pa.player.HumanPlayer;
import com.unicam.cs.pa.player.Player;
/*
RESPONSABILITÀ : Gestisce una partita tra utente e giocatore artificiale.
*/
public class HumanVsCOM extends Match {
public HumanVsCOM(HumanPlayer p1, COMPlayer p2) {
super(p1, p2);
}
public HumanVsCOM() {
players[0] = new HumanPlayer(Disc.RED);
Utils.blankLine();
COMFactory comFactory = new COMFactory();
players[1] = comFactory.createPlayer(Disc.YELLOW);
}
@Override
public void randomStart() {
super.randomStart();
System.out.println(currentPlayer.getUsername() + " starting!");
}
@Override
protected void notifyWin(Player winner) {
if (winner.equals(players[0]))
System.out.println("You WIN! ");
else System.out.println("You LOSE! ");
}
}
| 55b2c9e8f6bf778e518dc2172d0ea718e30ed837 | [
"Markdown",
"Java"
] | 13 | Markdown | napo5/connect4CLI | 2cdced1fad61674d637c2a2535456cd16d729fe2 | 333796be18af5a5a03b83f2ec87a1fd647dc4d5b | |
refs/heads/master | <repo_name>austenpiers/quash<file_sep>/HeapNode.h
#ifndef HEAPNODE_H
#define HEAPNODE_H
#include "HashNode.h"
class HeapNode{
public:
int value, count;
int HashIndex;
HashNode *PTE;
HeapNode(int Val, int i):value(Val),count(1),HashIndex(i),PTE(NULL){};
HeapNode(int Val, HashNode *k):value(Val),count(1),HashIndex(-1),PTE(k){};
~HeapNode(){};
};
#endif
<file_sep>/main.cpp
#include <iostream>
#include <string.h>
#include <stdio.h> /* printf, fgets */
#include <stdlib.h>
#include "Quash.h"
using namespace std;
int main(int argc, char *argv[])
{
Quash *myQuash = new Quash();
char buffer[256];
int o;
while(cin.getline(buffer, 256))
{
string command(buffer);
if(command.compare(0,6,"insert") == 0)
{
o = atoi(&(command[7]));
myQuash->InsertHashNode(o);
}
else if(command.compare("print") == 0)
myQuash->print();
else if(command.compare("deleteMin") == 0)
myQuash->deleteMin();
else if(command.compare(0,6,"lookup") == 0){
o = atoi(&(command[7]));
myQuash->lookup(o);
}
else if(command.compare(0,6,"delete") == 0){
o = atoi(&(command[7]));
myQuash->deleteNode(o);
}
else
cout << "Invalid Command" << endl;
}
}
<file_sep>/Quash.h
#ifndef QUASH_H
#define QUASH_H
#include <vector>
#include "HeapNode.h"
class Quash {
public:
HashNode *Table[43];
std::vector<HeapNode*> Heap;
Quash();
~Quash();
void insert(int i);
int hashFunction(int);
void InsertHashNode(int);
int HeapInsertNode(int,int);
int HeapInsertNode(int,HashNode*);
int percolateUp(int i);
void lookup(int key);
void deleteMin();
int percolateDown(int i);
void deleteNode(int key);
void deleteMin(int i);
void print();
};
#endif
<file_sep>/HashNode.h
#ifndef HASHNODE_H
#define HASHNODE_H
class HashNode
{
public:
int Value, Count;
int HeapVal;
HashNode *Next;
HashNode(int Val): Value(Val), Count(1), Next(NULL){};
~HashNode(){};
};
#endif
<file_sep>/Quash.cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include "Quash.h"
#include "HeapNode.h"
#include "HashNode.h"
using namespace std;
//QUASH CONSTRUCTOR
Quash::Quash(){
//initializing Hash Table
for(int i = 0; i<43; i++)
this->Table[i] = NULL;
}
//QUASH DESTRUCTOR
Quash::~Quash(){
//deleting Hash Table
for(int i = 0; i<43; i++){
while(this->Table[i] != NULL)
{
HashNode *current = this->Table[i];
do{
HashNode *tmp = current;
current = current->Next;
delete tmp;
}while(current != NULL);
}
}
}
//HASH FUNCTION
int Quash::hashFunction(int input){
int index = input%(43);
if (index < 0)
index += 43;
return index;
}
//INSERTION OF NODE
void Quash::InsertHashNode(int key){
//find initial index
int index = this->hashFunction(key);
HashNode *Location = (this->Table[index]);
//Base case, index is empty
if(Location == NULL){
this->Table[index] = new HashNode(key);
cout << "item successfully inserted, count = 1" << endl;
this->Table[index]->HeapVal = HeapInsertNode(key, index);
return;
}
//while there is no spot available, keep looking
while(Location != NULL ){
//the item already exists, increment count
if((Location->Value)==key){
(Location->Count)++;
(Heap[Location->HeapVal]->count)++;
cout << "item already present, new count = " << Location->Count << endl;
return;
}
//when we hit the end, create a new Node, insert to hash and heap
if((Location->Next) == NULL){
(Location->Next) = new HashNode(key);
cout << "item successfully inserted, count = 1" << endl;
(Location->Next->HeapVal) = (HeapInsertNode(key, Location));
return;
}
}
}
//INSERT NODE INTO HEAP /hash-node is root
int Quash::HeapInsertNode(int key, int index){
HeapNode *nwNode = new HeapNode(key, index);
this->Heap.push_back(nwNode);
return(percolateUp(Heap.size() - 1));
}
//INSERT NODE INTO HEAP /hash-node in separate chain
int Quash::HeapInsertNode(int key, HashNode *index){
HeapNode *nwNode = new HeapNode(key, index);
this->Heap.push_back(nwNode);
return(percolateUp(Heap.size() - 1));
}
//PERCULATE UP
int Quash::percolateUp(int i){
if(Heap.size() == 1)
return 0;
int swtch = i;
HeapNode* temp;
int parent = (i/2); //set the key of the parent node
//if there is a left child and its less than parent
if (Heap[parent]->value > Heap[i]->value)
swtch = parent;
//if parent is greater than
if (i != swtch){
//switch them
if(Heap[swtch]->HashIndex == -1)
(Heap[swtch]->PTE->Next->HeapVal) = i;
else
(Table[Heap[swtch]->HashIndex]->HeapVal) = i;
temp = (Heap[swtch]);
Heap[swtch] = Heap[i];
Heap[i] = temp;
//percolate up from the one we just switched to
return (percolateUp(swtch));
}
else
return i;
}
//HASHTABLE IMPLEMENTED LOOKUP
void Quash::lookup(int key){
int index = this->hashFunction(key);
HashNode *Location = (this->Table[index]);
//search through list for key or NULL
while(Location != NULL){
// Found
if((Location->Value) == key){
cout << "item found, count = " << Location->Count << endl;
return;
}
Location = Location->Next;
}
//not found
cout << "item not found" << endl;
return;
}
//DELETE MINIMUM ELEMENT
void Quash::deleteMin(){
if(this->Heap.size() == 0){
cout << "min item not present since table is empty" << endl; return;}
//store minimum
HeapNode* min = (this->Heap[0]);
//setting potential index of min in HashTable
int potInd = min->HashIndex;
// if there is more than one of the min elements, just minus the count
if((min->count) > 1){
(min->count)--;
cout << "min item = " << min->value << ", count decremented, new count = " << min->count << endl;
if(potInd == -1)
(min->PTE->Next->Count)--;
else
(this->Table[potInd]->Count)--;
return;
}
//take the last element and put it at the root
this->Heap[0] = this->Heap[Heap.size() - 1];
this->Heap.pop_back();
//Percolate Down and update HashTable's Node pointing to the perviously last element
if((this->Heap[0]->HashIndex) == -1)
(this->Heap[0]->PTE->Next->HeapVal) = percolateDown(0);
else
(this->Table[Heap[0]->HashIndex]->HeapVal) = percolateDown(0);
//Delete the min in HashTable
HashNode *tmp;
if(potInd == -1){
tmp = min->PTE->Next;
min->PTE->Next = tmp->Next;
}
else{
tmp = this->Table[potInd];
this->Table[potInd] = tmp->Next;
}
//print standard output
cout << "min item " << tmp->Value << " successfully deleted" << endl;
delete tmp;
delete min;
return;
}
//PERCULATE DOWN
int Quash::percolateDown(int i){
if(Heap.size() == 1)
return i;
int swtch = i;
HeapNode* temp;
int left = 2*i + 1; //set the key of the left node
int right = 2*i + 2; //set the key of the right node
//if there is a left child and its less than parent
if (left < (Heap.size()) && Heap[left]->value < Heap[i]->value)
swtch = left;
//if there is a right child and its less than either the parent or the left node
else if(right < (Heap.size()) && Heap[right]->value < Heap[swtch]->value)
swtch = right;
//if a switch must be made
if (i != swtch){
//switch them
if(Heap[swtch]->HashIndex == -1)
Heap[swtch]->PTE->Next->HeapVal = i;
else
Table[Heap[swtch]->HashIndex]->HeapVal = i;
temp = (Heap[swtch]);
Heap[swtch] = Heap[i];
Heap[i] = temp;
//percolate down from the one we just switched to
return percolateDown(swtch);
}
else
return i;
}
//DELETING A SPECIFIC INDEX IN THE HASH TABLE
void Quash::deleteNode(int key){
int index = this->hashFunction(key);
HashNode *tmp = this->Table[index];
while(tmp != NULL){
if(tmp->Value == key){
this->deleteMin(tmp->HeapVal);
cout << "item successfully deleted" << endl;
tmp = tmp->Next;
return;
}
}
cout << "item not present in the table" << endl;
}
//DELETE SPECIFIC ELEMENT
void Quash::deleteMin(int i){
//store minimum
HeapNode* min = (this->Heap[i]);
//setting potential index of min in HashTable
int potInd = min->HashIndex;
// if there is more than one of the min elements, just minus the count
if((min->count) > 1){
(min->count)--;
if(potInd == -1)
(min->PTE->Next->Count)--;
else
(this->Table[potInd]->Count)--;
return;
}
//take the last element and put it at the root
this->Heap[i] = this->Heap[Heap.size() - 1];
this->Heap.pop_back();
//Percolate Down and update HashTable's Node pointing to the perviously last element
if((this->Heap[i]->HashIndex) == -1)
(this->Heap[i]->PTE->Next->HeapVal) = percolateDown(i);
else
(this->Table[Heap[i]->HashIndex]->HeapVal) = percolateDown(i);
//Delete the min in HashTable
HashNode *tmp;
if(potInd == -1){
tmp = min->PTE->Next;
min->PTE->Next = tmp->Next;
}
else{
tmp = this->Table[potInd];
this->Table[potInd] = tmp->Next;
}
//print standard output
delete tmp;
delete min;
return;
}
void Quash::print(){
for(int iter = 0; iter < this->Heap.size(); iter++)
cout << Heap[iter]->value << " ";
cout << endl;
}
| 83a0d5c510a63a70635f548f896ee193cec53932 | [
"C++"
] | 5 | C++ | austenpiers/quash | d6810af4598d4d9dd5a0940f1d951511dec5f2a5 | 517af672d347f7228829032c4ddd7fd4bc35e9ad | |
refs/heads/master | <file_sep>const express = require('express');
const { search } = require('./search');
const router = express.Router();
require('dotenv').config();
const {
client,
server,
} = require('./errors');
router.get('/', (req, res) => {
res.render('home');
});
router.post('/search', search);
router.use(client);
router.use(server);
module.exports = router;
<file_sep>document.querySelector('form').addEventListener('submit', (e) => {
// e.preventDefault();
});
<file_sep># Stomach Care Center
## Team :
* The Fadi(s) Team
## Why we built this website?
* To let the user to search for a meal by its name or any part of its name
## What does the website do?
* It display the meals that the user search for
## How did we build it ?
* First, We read the project specification carefully and discuss the details, then we looked for an API.
* Second, discuss the flow of the project
* Third, sketch simple layout for the homepage
* Fourth, Create new repo on GitHub and install the required modules, also we create the file structure and set up Travis CI and Hide the API key
* Fifth, we create tests for the routes that we want to create
* Sixth, Create the server and handle the routes
* Seventh, Handle the response data in handlebars
* Eighth, set up the handlebars engine and build the default layout and the partials that we import them in the main layout
* Nineth, deploy the website on heroku
# User Jouerny
When the user browse the website the server handle that request and render the homepage from the server side to the user and show him the search input field and the submit button
then he can search for a specific meal and get the result from the server by rendering the result to another endpoint to display the meals.
<file_sep>const server = require('./app');
server.listen(server.get('port'), () => {
console.log(`the server running at port ${server.get('port')}`);
});
<file_sep>const fetch = require('node-fetch');
exports.search = (req, res, next) => {
const query = req.body.input;
const key = process.env.API_KEY;
const url = `https://www.themealdb.com/api/json/v1/${key}/search.php?s=${query}`;
fetch(url)
.then(data => data.json())
.then((data) => {
res.render('home', {
meals: data.meals,
});
})
.catch(error => next(error));
};
<file_sep>const test = require('tape');
const supertest = require('supertest');
// / test for statring work on travise :
test('this test just to pass travis', (t) => {
t.equal(1, 1, 'equal 1 ');
t.end();
});
// / test for the home page :
const app = require('../src/app');
test('Home root return status code 200', (t) => {
supertest(app)
.get('/')
.expect(200)
.expect('Content-Type', /html/)
.end((err, res) => {
if (err) {
t.error(err);
} else {
t.equal(res.statusCode, 200, 'Status Code should be 200');
t.end();
}
});
});
// // test for the search route :
test('Testing the search route', (t) => {
supertest(app)
.post('/search')
.send('pas')
.expect(200)
.expect('Content-Type', /html/)
.end((err, res) => {
if (err) {
t.error(err);
} else {
const actual = typeof res.text;
t.equal(actual, 'string', 'should return html string');
t.deepEqual(res.text.includes('<!DOCTYPE html>'), true, 'type of the response is html ');
t.end();
}
});
});
test('wrong path return status code 404', (t) => {
supertest(app)
.get('/asd')
.expect(404)
.expect('Content-Type', /html/)
.end((err, res) => {
if (err) {
t.error(err);
} else {
t.equal(res.statusCode, 404, 'Status Code should be 404');
t.end();
}
});
});
| 4703412630d66e7559e566cb46187feda30dcd42 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | GSG-G7/make-your-meal | b6c8f6f9714558907d40cec1bbd861e580b0b1f7 | 0cc6f954f88f28dd128ce01e7ebeabe1e61c271d | |
refs/heads/master | <repo_name>angeladowns/hellosasebo<file_sep>/README.md
# Hello, Sasebo!
January 2017
Ruby 2.6.3 // Rails 5.0.0.1
http://www.hellosasebo.com/
This adventure app was created using the Rails Girls LA Guide located at: https://gist.github.com/jendiamond/5a26b531e8e47b4aa638.
<file_sep>/lib/fog.rb
# lib/fog.rb
module Fog
# :)
end
<file_sep>/spec/factories/comments.rb
FactoryBot.define do
factory :comment do
user_name "MyString"
body "MyText"
adventure_id 1
end
end
<file_sep>/app/controllers/pages_controller.rb
class PagesController < ApplicationController
def info
end
def map
if params[:search].present?
@adventures = Adventure.near(params[:search], 1000, :order => :address)
else
@adventures = Adventure.all
end
@hash = Gmaps4rails.build_markers(@adventures) do |adventure, marker|
marker.lat adventure.latitude
marker.lng adventure.longitude
marker.infowindow adventure.name
marker.picture({
"width" => 32,
"height" => 32})
marker.json({ name: adventure.name})
end
end
end
<file_sep>/spec/requests/adventures_spec.rb
require 'rails_helper'
#------------------INDEX
describe "adventures", type: :request do
let!(:adventure) { FactoryGirl.create(:adventure) }
describe 'reading adventures' do
it "should render adventures index template" do
get '/adventures'
expect(response).to have_http_status(200)
expect(response).to render_template :index
end
end
#------------------NEW/CREATE
describe 'GET /adventures/new' do
it "should render adventures new template" do
get '/adventures/new'
expect(response).to have_http_status(200)
expect(response).to render_template :new
end
end
describe 'POST /adventures' do
it 'should create a new adventure' do
expect {
post '/adventures', adventure: { date_time: adventure.date_time,
activity: adventure.activity,
location: adventure.location,
description: adventure.description }
}.to change(adventure, :count).by(1)
expect(response).to have_http_status(302)
expect(response).to redirect_to(adventure_url(adventure.last.id))
end
end
#-----NEW/CREATE FAILURE
describe 'GET /adventures/:id save failure' do
before do
post '/adventures', adventure: { location: adventure.location,
description: adventure.description }
end
it 'should not render adventure show template' do
get "/adventures/#{adventure.last.id}"
expect(response).to have_http_status(200)
expect(response).to render_template :show
end
it 'does not save the new adventure' do
expect{
post '/adventures', adventure: { location: adventure.location,
description: adventure.description }
}.to_not change(adventure,:count)
end
it 're-renders the new page' do
post '/adventures', adventure: { location: adventure.location,
description: adventure.description }
expect(response).to render_template :new
end
end
#------------------SHOW
describe 'GET /adventures/:id' do
before do
post '/adventures', adventure: { date_time: adventure.date_time,
activity: adventure.activity,
location: adventure.location,
description: adventure.description }
end
it "should render adventure show template" do
get "/adventures/#{adventure.last.id}"
expect(response).to have_http_status(200)
expect(response).to render_template :show
end
end
#------------------EDIT/UPDATE
describe 'GET /adventures/:id/edit' do
it "should render adventures edit template" do
get "/adventures/#{adventure.id}/edit"
expect(response).to have_http_status(200)
expect(response).to render_template :edit
end
end
describe 'POST /adventures/:id' do
before do
post '/adventures', adventure: { date_time: adventure.date_time,
activity: adventure.activity,
location: adventure.location,
description: adventure.description }
end
it "should update a adventure" do
expect {
patch "/adventures/#{adventure.id}", adventure: { date_time: adventure.date_time,
activity: adventure.activity,
location: adventure.location,
description: adventure.description }
}.to change(adventure, :count).by(0)
expect(response).to have_http_status(302)
expect(response).to redirect_to(adventure_url(adventure))
end
end
#-----EDIT/UPDATE FAILURE
describe 'GET /adventures/:id/edit failure' do
before do
post '/adventures', adventure: { date_time: adventure.date_time,
activity: adventure.activity,
location: adventure.location,
description: adventure.description }
end
it 're-renders the edit page' do
get "/adventures/#{adventure.last.id}/edit", adventure: { date_time: adventure.date_time,
activity: adventure.activity,
location: adventure.location,
description: adventure.description }
expect(response).to render_template :edit
end
end
#------------------DELETE
describe 'DELETE' do
before do
post '/adventures', adventure: { date_time: adventure.date_time,
activity: adventure.activity,
location: adventure.location,
description: adventure.description }
end
it "should delete a adventure" do
expect {
delete "/adventures/#{adventure.last.id}"
}.to change(adventure, :count).by(-1)
expect(response).to have_http_status(302)
end
end
end
<file_sep>/app/controllers/adventures_controller.rb
class AdventuresController < ApplicationController
before_action :set_adventure, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
before_action :owns_adventure, only: [:edit, :update, :destroy]
before_action :prepare_categories
# GET /adventures
# GET /adventures.json
def index
@adventures = Adventure.all.order("updated_at DESC")
#if params[:search]
# @adventures = Adventure.search(params[:search]).order("created_at DESC")
#else
# @adventures = Adventure.all.order("created_at DESC")
#end
end
def search
if params[:search]
@adventures = Adventure.search(params[:search]).order("created_at DESC")
else
@adventures = Adventure.all.order("created_at DESC")
end
end
# GET /adventures/1
# GET /adventures/1.json
def show
@adventure = Adventure.find(params[:id])
end
# GET /adventures/new
def new
@adventure = Adventure.new
@adventure = current_user.adventures.build
end
# GET /adventures/1/edit
def edit
end
# POST /adventures
# POST /adventures.json
def create
@adventure = current_user.adventures.new(adventure_params)
@adventure = Adventure.new(adventure_params)
respond_to do |format|
if @adventure.save
format.html { redirect_to @adventure, notice: 'Adventure was successfully created.' }
format.json { render :show, status: :created, location: @adventure }
else
format.html { render :new }
format.json { render json: @adventure.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /adventures/1
# PATCH/PUT /adventures/1.json
def update
respond_to do |format|
if @adventure.update(adventure_params)
format.html { redirect_to @adventure, notice: 'Adventure was successfully updated.' }
format.json { render :show, status: :ok, location: @adventure }
else
format.html { render :edit }
format.json { render json: @adventure.errors, status: :unprocessable_entity }
end
end
end
# DELETE /adventures/1
# DELETE /adventures/1.json
def destroy
@adventure.destroy
respond_to do |format|
format.html { redirect_to adventures_url, notice: 'Adventure was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_adventure
@adventure = Adventure.find(params[:id])
end
# add the @categories = Category.All to the before action so avail for all actions
def prepare_categories
@categories = Category.all
end
# Never trust parameters from the scary internet, only allow the white list through.
def adventure_params
params.require(:adventure).permit(:name, :description, :picture, :location, :visit, :address, :user_id, :category_id)
end
def owns_adventure
if !user_signed_in? || current_user != Adventure.find(params[:id]).user
redirect_to adventures_path, error: "You cannot do that"
end
end
end
<file_sep>/app/admin/adventure.rb
ActiveAdmin.register Adventure do
# See permitted parameters documentation:
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
#
# permit_params :list, :of, :attributes, :on, :model
#
# or
#
# permit_params do
# permitted = [:permitted, :attributes]
# permitted << :other if params[:action] == 'create' && current_user.admin?
# permitted
# end
permit_params :name, :description, :picture, :location, :visit, :address, :user_id, :category_id, :User
index do
column :name
column :location
column :user
column :category
actions
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
get 'contacts/new'
resources :contacts, only: [:new, :create]
devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
resources :categories
devise_for :users
resources :comments
get 'pages/info'
get 'pages/terms'
get 'pages/privacy'
root 'adventures#index'
resources :adventures do
collection do
get :search
end
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
<file_sep>/app/models/adventure.rb
class Adventure < ApplicationRecord
geocoded_by :address
after_validation :geocode # this command auto fetches our coordinates
belongs_to :user
belongs_to :category
mount_uploader :picture, PictureUploader
def self.search(search)
where("name ILIKE ? OR location ILIKE ? OR description ILIKE ?", "%#{search}%", "%#{search}%", "%#{search}%")
end
end
<file_sep>/db/migrate/20170419022602_add_category_to_adventures.rb
class AddCategoryToAdventures < ActiveRecord::Migration[5.0]
def change
add_column :adventures, :category_id, :int
end
end
<file_sep>/spec/factories/adventures.rb
FactoryBot.define do
factory :adventure do
date_time { Date.today.strftime("%A, %B %d %I:%M %P") }
activity { FFaker::Sport.name }
location { FFaker::AddressUS.neighborhood }
description { FFaker::HipsterIpsum.words(4).join(',') }
end
end
| 2b9231edcaf59e39d709bac390893b403043722b | [
"Markdown",
"Ruby"
] | 11 | Markdown | angeladowns/hellosasebo | ec047d82ef27bcc5b1ca2c706b100d74819c3d48 | 73673076019be95977ddcf3929a6c5fab9a4f8ae | |
refs/heads/master | <repo_name>tobidsn/ci3-started<file_sep>/README.md
# ci3-started
Mulai Codeigniter 3 dengan illuminate/database
## Instalasi
* <code>$ git clone https://github.com/huiralb/ci3-started myProject</code>
* Jalankan command line berikut:
```
$ cd myProject
$ composer install
$ php -S localhost:8000
```
* Lihat pada browser dengan url <code>localhost:8000</code>
#### Setup environment
Untuk mengaktifkan debug error secara otomatis pada <code>setting.ini.php</code>
```php
env = development
```
Jika anda bekerja pada local komputer masukkan nilai <code>env</code> dengan <code>development</code>
Ganti <code>env</code> menjadi <code>production</code> untuk environment remote / produksi.
## Database Model
####Untuk menggunakan paket ini:
Sejak anda menjalankan <code>$ composer install</code>, aplikasi sudah terinstall paket database Eloquent dengan bantuan composer, secara spesifik ada di folder <code>app/vendor/illuminate/database</code>.
Pastikan setting koneksi database dengan baik pada file <code>setting.ini.php</code>
### Query Builder
Untuk mengakses model data dari table, code PHP anda kurang lebih terlihat seperti di bawah ini:
```php
use Illuminate\Database\Capsule\Manager as DB;
class Selamat_datang extends CI_Controller {
public function index()
{
$users = DB::table('users')->get();
var_dump($users);
$this->load->view('welcome_message');
}
}
```
### ORM Eloquent Database
* Create file <code>app/Model/User.php</code>
```php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
}
```
* akses dari controller
```php
$users = \App\Model\User::all();
print_r($users);
<file_sep>/app/modules/backend/controllers/Backend.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Backend extends MX_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
echo "Base page with hmvc";
}
}
/* End of file Base.php */
/* Location: ./application/controllers/Base.php */<file_sep>/app/libraries/MY_Database.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Illuminate\Database\Capsule\Manager as DB;
class MY_Database
{
protected $ci;
public function __construct()
{
$setting = parse_ini_file(FCPATH . "setting.ini.php");
$capsule = new DB;
$capsule->addConnection(array(
'host' => $setting['host'],
'database' => $setting['database'],
'username' => $setting['username'],
'password' => $setting['<PASSWORD>'],
'driver' => 'mysql',
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => ''
));
$capsule->setAsGlobal();
$capsule->bootEloquent();
}
}<file_sep>/setting.ini.php
;<?php return; ?>
[SQL]
host = localhost
username = root
password =
database = database
env = development
| 3694aae9835dbc50288126d6c13d78755259c32e | [
"Markdown",
"PHP"
] | 4 | Markdown | tobidsn/ci3-started | 5294a8d6cc362fe2bc1fdd163364960c9d8a5512 | 986da8010ba82efc7344e2f1a5de74208b289be8 | |
refs/heads/master | <repo_name>freak0/yacht<file_sep>/yacht-web/src/main/java/br/com/eltonsantos/yacht/YachtApplication.java
package br.com.eltonsantos.yacht;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class YachtApplication {
public static void main(String[] args) {
SpringApplication.run(YachtApplication.class, args);
}
}
<file_sep>/yacht-data/src/main/java/br/com/eltonsantos/yacht/data/services/CrudService.java
package br.com.eltonsantos.yacht.data.services;
import br.com.eltonsantos.yacht.data.model.BaseEntity;
import java.io.Serializable;
import java.util.Optional;
import java.util.Set;
public interface CrudService<T extends BaseEntity, ID extends Serializable> {
T save(T object);
Optional<T> findById(ID id);
Set<T> findAll();
void delete(T object);
void deleteById(ID id);
}
<file_sep>/yacht-web/src/main/java/br/com/eltonsantos/yacht/bootstrap/DataLoader.java
package br.com.eltonsantos.yacht.bootstrap;
import br.com.eltonsantos.yacht.data.model.Checklist;
import br.com.eltonsantos.yacht.data.model.ChecklistGroup;
import br.com.eltonsantos.yacht.data.services.ChecklistGroupService;
import br.com.eltonsantos.yacht.data.services.ChecklistService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.Month;
@Component
public class DataLoader implements CommandLineRunner {
private final ChecklistService checklistService;
private final ChecklistGroupService checklistGroupService;
private static final Logger LOG = LoggerFactory.getLogger(DataLoader.class);
public DataLoader(ChecklistService checklistService, ChecklistGroupService checklistGroupService) {
this.checklistService = checklistService;
this.checklistGroupService = checklistGroupService;
}
@Override
public void run(String... args) throws Exception {
LOG.info("Creating checklist groups...");
ChecklistGroup australiaChecklistGroup = new ChecklistGroup("Australia travel");
ChecklistGroup studyListChecklistGroup = new ChecklistGroup("Study list");
checklistGroupService.save(australiaChecklistGroup);
checklistGroupService.save(studyListChecklistGroup);
LOG.info("Checklist groups created.");
LOG.info("Creating checklists...");
Checklist luggageChecklist =
new Checklist("Getting the luggage figured out", LocalDate.of(2018, Month.DECEMBER, 30));
luggageChecklist.setGroup(australiaChecklistGroup);
Checklist documentationChecklist =
new Checklist("Preparing documentation", LocalDate.of(2018, Month.DECEMBER, 22));
documentationChecklist.setGroup(australiaChecklistGroup);
Checklist studySpringChecklist =
new Checklist("Spring studies", LocalDate.of(2019, Month.JANUARY, 7));
studySpringChecklist.setGroup(studyListChecklistGroup);
checklistService.save(luggageChecklist);
checklistService.save(documentationChecklist);
checklistService.save(studySpringChecklist);
LOG.info("Checklists created.");
}
}
<file_sep>/yacht-data/src/main/java/br/com/eltonsantos/yacht/data/model/Task.java
package br.com.eltonsantos.yacht.data.model;
public class Task extends BaseEntity {
private String name;
private String description;
private Boolean checked;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
}
<file_sep>/yacht-data/src/test/java/br/com/eltonsantos/yacht/data/services/map/ChecklistServiceMapTest.java
package br.com.eltonsantos.yacht.data.services.map;
import br.com.eltonsantos.yacht.data.model.Checklist;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.util.Optional;
import java.util.Set;
import static java.time.Month.DECEMBER;
import static org.junit.jupiter.api.Assertions.*;
class ChecklistServiceMapTest {
private static LocalDate XMAS_DATE = LocalDate.of(2018, DECEMBER, 25);
private ChecklistServiceMap cut;
@BeforeEach
void setUp() {
this.cut = new ChecklistServiceMap();
this.cut.save(new Checklist("Create tests", LocalDate.of(2018, DECEMBER, 17)));
this.cut.save(new Checklist("Create more tests", LocalDate.of(2018, DECEMBER, 18)));
this.cut.save(new Checklist("Create the actual code", LocalDate.of(2018, DECEMBER, 19)));
}
@Test
@DisplayName("When I save a new Checklist, check if its saved using its ID to find it.")
void save() {
//when:
Checklist checklist = new Checklist("<NAME>", XMAS_DATE);
Checklist returnedChecklist = this.cut.save(checklist);
//and:
Optional<Checklist> optChecklistFound = this.cut.findById(4L);
//then:
assertTrue(optChecklistFound.isPresent());
Checklist checklistFound = optChecklistFound.get();
assertEquals((Object) 4L, checklistFound.getId());
assertEquals("<NAME>", checklistFound.getName());
assertEquals(XMAS_DATE, checklistFound.getDueDate());
assertEquals(returnedChecklist, checklistFound);
}
@Test
@DisplayName("Tests the search for all checklists to see if returns only the 3 bootstraped checklists.")
void findAll() {
//when:
Set<Checklist> checklists = this.cut.findAll();
//then:
assertEquals(3, checklists.size());
}
@Test
@DisplayName("When I search for a checklist by its ID, check the checklist to see if its data is as expected.")
void findById() {
//when:
Optional<Checklist> optChecklist = this.cut.findById(1L);
//then:
assertTrue(optChecklist.isPresent());
Checklist checklist = optChecklist.get();
assertEquals((Object) 1L, checklist.getId());
assertEquals("Create tests", checklist.getName());
assertEquals(LocalDate.of(2018, DECEMBER, 17), checklist.getDueDate());
}
@Test
@DisplayName("Tests if a deleted checklist is not returned anymore after been excluded based on its id.")
void deleteById() {
//when:
this.cut.deleteById(2L);
Optional<Checklist> removedChecklist = this.cut.findById(2L);
//then:
assertFalse(removedChecklist.isPresent());
}
@Test
@DisplayName("Tests if a deleted checklist is not returned anymore after been excluded.")
void delete() {
//when:
Checklist checklistToBeRemoved = this.cut.findById(3L).get();
this.cut.delete(checklistToBeRemoved);
Optional<Checklist> removedChecklist = this.cut.findById(3L);
//then:
assertFalse(removedChecklist.isPresent());
}
}<file_sep>/yacht-data/src/main/java/br/com/eltonsantos/yacht/data/services/map/ChecklistServiceMap.java
package br.com.eltonsantos.yacht.data.services.map;
import br.com.eltonsantos.yacht.data.model.Checklist;
import br.com.eltonsantos.yacht.data.services.ChecklistService;
import org.springframework.stereotype.Service;
@Service
public class ChecklistServiceMap extends AbstractCrudServiceMap<Checklist, Long> implements ChecklistService {
}
<file_sep>/yacht-data/src/main/java/br/com/eltonsantos/yacht/data/services/ChecklistGroupService.java
package br.com.eltonsantos.yacht.data.services;
import br.com.eltonsantos.yacht.data.model.ChecklistGroup;
public interface ChecklistGroupService extends CrudService<ChecklistGroup, Long> {
}
<file_sep>/yacht-data/src/main/java/br/com/eltonsantos/yacht/data/services/ChecklistService.java
package br.com.eltonsantos.yacht.data.services;
import br.com.eltonsantos.yacht.data.model.Checklist;
public interface ChecklistService extends CrudService<Checklist, Long> {
}
<file_sep>/yacht-data/src/main/java/br/com/eltonsantos/yacht/data/services/map/ChecklistGroupServiceMap.java
package br.com.eltonsantos.yacht.data.services.map;
import br.com.eltonsantos.yacht.data.model.ChecklistGroup;
import br.com.eltonsantos.yacht.data.services.ChecklistGroupService;
import org.springframework.stereotype.Service;
@Service
public class ChecklistGroupServiceMap extends AbstractCrudServiceMap<ChecklistGroup, Long> implements ChecklistGroupService {
}
<file_sep>/README.md
Yet Another Checklist Tool - Using this app to study some more of:
- Spring Boot;
- Reactive Programming;
- Unit tests;
- React;
- Redux.
<file_sep>/yacht-data/src/main/java/br/com/eltonsantos/yacht/data/services/TaskService.java
package br.com.eltonsantos.yacht.data.services;
import br.com.eltonsantos.yacht.data.model.Task;
public interface TaskService extends CrudService<Task, Long> {
}
| 8ee4c9d7a8668c74d3d2654000f0ce6fc136c0e1 | [
"Markdown",
"Java"
] | 11 | Java | freak0/yacht | a606f6343ca8248f2321e3d65c7eb209d7601693 | 09c58e27beb355594c8ec320a1195909b6caffa7 | |
refs/heads/main | <repo_name>derdroste/tinder_bot<file_sep>/secrets/secret.js
const secret = {
tinder: {
mail: 'your email',
password: '<PASSWORD>',
message: {
firstPart: 'Hi ',
secondPart: ', my name is peter!'
}
}
};
module.exports = secret;<file_sep>/views/assets/index.js
document.addEventListener('DOMContentLoaded', () => {
const tinderLike = document.querySelector('#tinderlike');
let valueTinderLike = true;
const tinderMessage = document.querySelector('#tindermessage');
let valueTinderMessage = true;
tinderLike.addEventListener('click', () => {
sendRequest('http://www.localhost:3000/api/tinder/like',valueTinderLike);
if (valueTinderLike === true) {
tinderLike.classList.add('stop');
tinderLike.innerHTML = 'Stop';
valueTinderLike = false;
} else {
tinderLike.classList.remove('stop');
tinderLike.innerHTML = 'Like';
valueTinderLike = true;
}
});
tinderMessage.addEventListener('click', () => {
sendRequest('http://www.localhost:3000/api/tinder/like',valueTinderMessage);
if (valueTinderMessage === true) {
tinderMessage.classList.add('stop');
tinderMessage.innerHTML = 'Stop';
valueTinderMessage = false;
} else {
tinderMessage.classList.remove('stop');
tinderMessage.innerHTML = 'Like';
valueTinderMessage = true;
}
});
});
function sendRequest(url, val) {
const xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: val
}));
}<file_sep>/routes/views.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.render('index', {
title: 'Vidoodle',
tinder: 'Tinder',
like: 'Like',
message: 'Message'
});
});
module.exports = router;
<file_sep>/routes/tinder.js
const express = require('express');
const router = express.Router();
const loginTinder = require('../modules/tinder/loginTinder');
const likeTinder = require('../modules/tinder/likeTinder');
const messageTinder = require('../modules/tinder/messageTinder');
const chrome = require('selenium-webdriver/chrome');
const chromedriver = require('chromedriver');
const webdriver = require('selenium-webdriver');
let driver = null;
let driverMessage = null;
router.post('/like',async (req, res) => {
if(req.body.value === true) {
try {
driver = await new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.build();
await loginTinder(driver, webdriver, 'http://www.tinder.com/');
await messageTinder(driver, webdriver);
} catch (e) {
console.log('Liking all the girls failed...', e);
driver.quit();
}
} else {
try {
driver.quit();
driver = null;
} catch (e) {
console.log('Liking all the girls failed...', e);
driver.quit();
}
}
});
router.post('/message',async (req, res) => {
if(req.body.value === true) {
try {
driverMessage = await new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.build();
await loginTinder(driverMessage, webdriver, 'http://www.tinder.com/');
await likeTinder(driverMessage, webdriver);
} catch (e) {
console.log('Liking all the girls failed...', e);
driverMessage.quit();
}
} else {
try {
driverMessage.quit();
driverMessage = null;
} catch (e) {
console.log('Liking all the girls failed...', e);
driverMessage.quit();
}
}
});
module.exports = router;
<file_sep>/README.md
# Tinder Bot
I have automated Tinder through Node & Selenium!
# Install
Install Node if you didn't already.
```bash
$ npm i
```
Add your E-Mail and Password in /secrets/secret.js.
Add two parts of the message, you want to send to all the girls.
The message will be displayed as 'firstMessage + name-of-the-girl + secondMessage'.
Example: 'Hi -sandra-, my name is peter'.
# Run
```bash
$ node app.js
```
# Use
A new Browser window should open, with the options to either like all the girls or to message all the girls.
You also have always the option to stop the execution. | 539ee7a57801b35d02cfd50fcf0a54f5b05fa41e | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | derdroste/tinder_bot | e9d54b6bf131fce89ff5b2b2c45d929a83a1232d | 64994a8289edea7c2a31918f9e635436102fa84f | |
refs/heads/master | <file_sep>package com.dreampany.frame.data.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import com.dreampany.frame.data.model.Color;
import com.dreampany.frame.ui.activity.BaseActivity;
public class BarUtil {
public static void hide(Activity activity) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
View decorView = activity.getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
}
//hideToolbar(activity);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void setStatusColor(Activity activity, Color color) {
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(ColorUtil.getColor(activity, color.getColorPrimaryDarkId()));
}
// window.set(activity.getResources().getColor(R.color.example_color));
}
public static void setStatusColor(BaseActivity activity, Color color) {
setStatusColor((Activity) activity, color);
}
private static int backupStatusColor;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void backupStatusColor(Activity activity) {
Window window = activity.getWindow();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
backupStatusColor = window.getStatusBarColor();
}
}
public static void backupStatusColor(BaseActivity activity) {
backupStatusColor((Activity) activity);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void restoreStatusColor(Activity activity) {
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(backupStatusColor);
}
}
public static void setActionBarColor(Toolbar toolbar, Color color) {
if (toolbar != null) {
toolbar.setBackgroundColor(ColorUtil.getColor(toolbar.getContext(), color.getColorPrimaryId()));
}
}
public static void showToolbar(Activity activity) {
if (BaseActivity.class.isInstance(activity)) {
// showToolbar((BaseActivity) activity);
}
}
public static void showToolbar(Toolbar toolbar) {
if (toolbar != null) {
toolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
}
// mFabButton.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).startUi();
}
public static void hideToolbar(Activity activity) {
if (BaseActivity.class.isInstance(activity)) {
// hideToolbar((BaseActivity) activity);
}
}
public static void hideToolbar(Toolbar toolbar) {
if (toolbar != null) {
toolbar.animate().translationY(-toolbar.getHeight()).setInterpolator(new AccelerateInterpolator(2));
}
//mToolbar.animate().translationY(-mToolbar.getHeight()).setInterpolator(new AccelerateInterpolator(2));
// FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mFabButton.getLayoutParams();
// int fabBottomMargin = lp.bottomMargin;
// mFabButton.animate().translationY(mFabButton.getHeight()+fabBottomMargin).setInterpolator(new AccelerateInterpolator(2)).startUi();
}
}
<file_sep>package com.dreampany.frame.data.callback;
import com.dreampany.frame.data.event.NetworkEvent;
/**
* Created by nuc on 6/11/2017.
*/
public interface NetworkCallback {
void onInternet(boolean internet);
void onNetworkEvent(NetworkEvent event);
}
<file_sep>package com.dreampany.frame.data.event;
import com.dreampany.frame.data.enums.NetworkStatus;
/**
* Created by nuc on 6/11/2017.
*/
public class NetworkEvent {
protected final NetworkStatus networkStatus;
protected NetworkEvent(NetworkStatus networkStatus) {
this.networkStatus = networkStatus;
}
public NetworkStatus getNetworkStatus() {
return networkStatus;
}
}
<file_sep>package com.dreampany.frame.data.manager;
import com.dreampany.frame.data.thread.Runner;
/**
* Created by nuc on 5/20/2017.
*/
public abstract class Manager extends Runner {
protected volatile boolean started;
public void start() {
super.start();
}
public void stop() {
super.stop();
}
@Override
public void run() {
super.run();
}
}
<file_sep>package com.dreampany.frame.data.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.dreampany.frame.data.enums.Type;
import com.dreampany.frame.data.enums.SQLiteQueryType;
import com.dreampany.frame.data.enums.SQLiteSelectionType;
import java.lang.reflect.Field;
/**
* Created by nuc on 12/3/2016.
*/
public class SQLiteTask<T extends Base, X extends Type> extends Task<T, X> {
private long hash;
private int count;
private SQLiteQueryType queryType;
private SQLiteSelectionType selectionType;
public SQLiteTask() {
}
public SQLiteTask(T item) {
super(item);
}
protected SQLiteTask(Parcel in) {
super(in);
hash = in.readLong();
count = in.readInt();
queryType = in.readParcelable(SQLiteQueryType.class.getClassLoader());
selectionType = in.readParcelable(SQLiteSelectionType.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeLong(hash);
dest.writeInt(count);
dest.writeParcelable(queryType, flags);
dest.writeParcelable(selectionType, flags);
}
public static final Parcelable.Creator<SQLiteTask> CREATOR = new Parcelable.Creator<SQLiteTask>() {
@Override
public SQLiteTask createFromParcel(Parcel in) {
return new SQLiteTask(in);
}
@Override
public SQLiteTask[] newArray(int size) {
return new SQLiteTask[size];
}
};
public void setHash(long hash) {
this.hash = hash;
}
public void setCount(int count) {
this.count = count;
}
public void setQueryType(SQLiteQueryType queryType) {
this.queryType = queryType;
}
public void setSelectionType(SQLiteSelectionType selectionType) {
this.selectionType = selectionType;
}
public long getHash() {
return hash;
}
public long getCount() {
return count;
}
public SQLiteQueryType getQueryType() {
return queryType;
}
public SQLiteSelectionType getSelectionType() {
return selectionType;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");
result.append(this.getClass().getName());
result.append(" Object {");
result.append(newLine);
//determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//print field names paired with their values
for (Field field : fields) {
result.append(" ");
try {
result.append(field.getName());
result.append(": ");
//requires access to private field:
result.append(field.get(this));
} catch (IllegalAccessException ex) {
//System.out.println(ex);
ex.printStackTrace();
}
result.append(newLine);
}
result.append("}");
return result.toString();
}
}
<file_sep>package com.dreampany.frame.ui.activity;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.view.MenuItem;
/**
* Created by nuc on 2/13/2017.
*/
public abstract class BaseBottomNavigationActivity extends BaseMenuActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
protected int currentNavId;
@Override
protected void startUi(boolean fullScreen) {
super.startUi(fullScreen);
final BottomNavigationView bottomNavigationView = getBottomNavigationView();
if (bottomNavigationView != null) {
bottomNavigationView.setOnNavigationItemSelectedListener(this);
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int targetNavId = item.getItemId();
if (targetNavId != currentNavId) {
onNavigationItem(targetNavId);
currentNavId = targetNavId;
return true;
}
return false;
}
protected int getBottomNavigationViewId() {
return 0;
}
protected BottomNavigationView getBottomNavigationView() {
return (BottomNavigationView) findViewById(getBottomNavigationViewId());
}
protected void onNavigationItem(int navItemId) {
}
}
<file_sep>package com.dreampany.frame.data.provider.pref;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
* Created by nuc on 1/12/2017.
*/
public abstract class BasePref {
protected int getMode() {
return Context.MODE_PRIVATE;
}
protected String getPrefName() {
return context.getPackageName();
}
protected void release() {
context = null;
publicPref = null;
privatePref = null;
}
protected Context context;
private SharedPreferences publicPref;
private SharedPreferences privatePref;
protected BasePref(Context context) {
this.context = context.getApplicationContext();
publicPref = PreferenceManager.getDefaultSharedPreferences(context);
privatePref = this.context.getSharedPreferences(getPrefName(), getMode());
}
public void setPublicValue(String key, String value) {
SharedPreferences.Editor editor = publicPref.edit();
editor.putString(key, value);
editor.apply();
}
public void setPublicValue(String key, boolean value) {
SharedPreferences.Editor editor = publicPref.edit();
editor.putBoolean(key, value);
editor.apply();
}
public void setPrivateValue(String key, String value) {
SharedPreferences.Editor editor = privatePref.edit();
editor.putString(key, value);
editor.apply();
}
public void setPrivateValue(String key, int value) {
SharedPreferences.Editor editor = privatePref.edit();
editor.putInt(key, value);
editor.apply();
}
public void setPrivateValue(String key, long value) {
SharedPreferences.Editor editor = privatePref.edit();
editor.putLong(key, value);
editor.apply();
}
public void setPrivateValue(String key, boolean value) {
SharedPreferences.Editor editor = privatePref.edit();
editor.putBoolean(key, value);
editor.apply();
}
public String getPublicString(String key, String defaultValue) {
return publicPref.getString(key, defaultValue);
}
public String getPrivateString(String key, String defaultValue) {
return privatePref.getString(key, defaultValue);
}
public int getPrivateInt(String key, int defaultValue) {
return privatePref.getInt(key, defaultValue);
}
public long getPrivateLong(String key, long defaultValue) {
return privatePref.getLong(key, defaultValue);
}
public boolean getPrivateBoolean(String key, boolean defaultValue) {
return privatePref.getBoolean(key, defaultValue);
}
public boolean getPublicBoolean(String key, boolean defaultValue) {
return publicPref.getBoolean(key, defaultValue);
}
}
<file_sep>package com.dreampany.frame.data.manager;
import android.support.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseError;
import com.dreampany.frame.data.connection.FirebaseConnection;
import com.dreampany.frame.data.model.FirebaseLock;
import com.dreampany.frame.data.util.Constant;
import com.dreampany.frame.data.util.DataUtil;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by nuc on 4/7/2016.
*/
public final class FirebaseManager {
private final FirebaseLock<?, DatabaseError, FirebaseAuth> firebaseLock = new FirebaseLock<>();
private static FirebaseManager firebaseManager;
private FirebaseConnection firebaseConnection;
private FirebaseManager() {
firebaseConnection = new FirebaseConnection<>();
}
synchronized public static FirebaseManager onManager() {
if (firebaseManager == null) {
firebaseManager = new FirebaseManager();
}
return firebaseManager;
}
public FirebaseUser toUser() {
return FirebaseAuth.getInstance().getCurrentUser();
}
public String toUid() {
FirebaseUser user = toUser();
if (user != null) {
return user.getUid();
}
return null;
}
public boolean isAuthenticated() {
return toUser() != null;
}
public String getUid() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
user.getUid();
}
return null;
}
public boolean signInAnonymously() {
if (FirebaseManager.onManager().isAuthenticated()) return true;
FirebaseAuth.getInstance().signInAnonymously()
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
notifyWaiting();
}
});
waiting();
return FirebaseManager.onManager().isAuthenticated();
}
public void signOut() {
FirebaseAuth.getInstance().signOut();
}
private void waiting() {
synchronized (firebaseLock) {
try {
firebaseLock.wait(Constant.HALF_MINUTE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void notifyWaiting() {
synchronized (firebaseLock) {
firebaseLock.notify();
}
}
interface Key {
String data = "data";
String all = "all";
}
private <T> String toName(T t) {
return toName(t.getClass());
}
private <T> String toName(Class<T> tClass) {
return tClass.getSimpleName().toLowerCase(Locale.getDefault());
}
private <T> Long toHash(T t) {
try {
final Method getHashMethod = t.getClass().getMethod("getHash");
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
getHashMethod.setAccessible(true);
return null; // nothing to return
}
});
Long hash = (Long) getHashMethod.invoke(t);
return hash;
} catch (SecurityException | InvocationTargetException | NoSuchMethodException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public <T> T write(T t, String childPath) {
if (t == null) return null;
String parentPath = Key.data + "/" + toName(t) + "/" + Key.all;
if (!DataUtil.isEmpty(childPath)) {
parentPath += "/" + childPath;
}
String hash = String.valueOf(toHash(t));
T result = (T) firebaseConnection.addToFirebase(t, parentPath, hash);
return result;
}
public <T> T write(T t) {
if (t == null) return null;
String parentPath = Key.data + "/" + toName(t);
String hash = String.valueOf(toHash(t));
T result = (T) firebaseConnection.addToFirebase(t, parentPath, hash);
return result;
}
public <T> List<T> write(List<T> ts) {
if (ts == null || ts.isEmpty()) return null;
List<T> results = new ArrayList<>();
for (T t : ts) {
String parentPath = Key.data + "/" + toName(t) + "/" + Key.all;
String childPath = String.valueOf(toHash(t));
T result = (T) firebaseConnection.addToFirebase(t, parentPath, childPath);
results.add(result);
}
return results;
}
public <T> List<T> read(Class<T> tClass, String childPath, long atTimestamp, int howMuch) {
String parentPath = Key.data + "/" + toName(tClass) + "/" + Key.all + "/" + childPath;
return firebaseConnection.takeFromFirebase(tClass, parentPath, atTimestamp, howMuch);
}
public <T> List<T> read(Class<T> tClass, String childPath, String orderBy, long equalTo) {
String parentPath = Key.data + "/" + toName(tClass) + "/" + Key.all;
if (!DataUtil.isEmpty(childPath)) {
parentPath += "/" + childPath;
}
return firebaseConnection.takeFromFirebase(tClass, parentPath, orderBy, equalTo);
}
public <T> List<T> read(Class<T> tClass, String orderBy, long equalTo) {
String parentPath = Key.data + "/" + toName(tClass);
return firebaseConnection.takeFromFirebase(tClass, parentPath, orderBy, equalTo);
}
}
<file_sep>package com.dreampany.frame.data.enums;
/**
* Created by air on 6/27/17.
*/
public enum ApState {
WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_ENABLING, WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_FAILED
}
<file_sep>package com.dreampany.frame.data.model;
import android.os.Parcel;
import com.dreampany.frame.data.enums.Type;
/**
* Created by nuc on 12/21/2016.
*/
public class UiTask<T extends Base> extends Task<T, Type> {
public UiTask() {
}
public UiTask(T item) {
super(item);
}
public UiTask(T item, Type itemType) {
super(item);
setItemType(itemType);
}
private UiTask(Parcel in) {
super(in);
}
public static final Creator<UiTask> CREATOR = new Creator<UiTask>() {
@Override
public UiTask createFromParcel(Parcel in) {
return new UiTask(in);
}
@Override
public UiTask[] newArray(int size) {
return new UiTask[size];
}
};
}
<file_sep>package com.dreampany.frame.data.manager;
import android.content.Context;
import android.content.Intent;
import com.dreampany.frame.data.receiver.InternetReceiver;
import com.dreampany.frame.data.util.NetworkUtil;
import java.io.IOException;
public class InternetManager {
private static final String DEFAULT_PING_HOST = "www.google.com";
private static final int DEFAULT_PING_PORT = 80;
private static final int DEFAULT_PING_TIMEOUT_IN_MS = 2000;
private final Context context;
private String pingHost;
private int pingPort;
private int pingTimeout;
private boolean hasInternet;
public InternetManager(Context context) {
this.context = context;
this.pingHost = DEFAULT_PING_HOST;
this.pingPort = DEFAULT_PING_PORT;
this.pingTimeout = DEFAULT_PING_TIMEOUT_IN_MS;
}
public void check() {
new Thread(new Runnable() {
@Override
public void run() {
try {
hasInternet = NetworkUtil.hasInternet(pingHost, pingPort, pingTimeout);
} catch (IOException e) {
hasInternet = false;
} finally {
sendBroadcast(hasInternet);
}
}
}).start();
}
public void setPingParameters(String host, int port, int timeoutInMs) {
this.pingHost = host;
this.pingPort = port;
this.pingTimeout = timeoutInMs;
}
public boolean hasInternet() {
return hasInternet;
}
private void sendBroadcast(boolean hasInternet) {
Intent intent = new Intent(InternetReceiver.INTENT);
intent.putExtra(InternetReceiver.INTENT_EXTRA, hasInternet);
context.sendBroadcast(intent);
}
}<file_sep>package com.dreampany.frame.data.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.os.Looper;
import com.dreampany.frame.data.callback.NetworkCallback;
import com.dreampany.frame.data.manager.NetworkManager;
import com.dreampany.frame.data.util.AndroidUtil;
import com.dreampany.frame.data.enums.NetworkStatus;
import com.dreampany.frame.data.event.ConnectivityChanged;
import com.dreampany.frame.data.event.NetworkEvent;
public abstract class BaseReceiver extends BroadcastReceiver {
private final Context context;
private NetworkCallback callback;
public BaseReceiver(Context context, NetworkCallback callback) {
this.context = context;
this.callback = callback;
}
protected boolean hasChanged(NetworkStatus networkStatus) {
return NetworkManager.networkStatus != networkStatus;
}
protected void postStatus(NetworkStatus networkStatus) {
NetworkManager.networkStatus = networkStatus;
post(new ConnectivityChanged(context, networkStatus));
}
protected void post(final NetworkEvent event) {
if (Looper.myLooper() == Looper.getMainLooper()) {
callback.onNetworkEvent(event);
} else {
AndroidUtil.post(new Runnable() {
@Override
public void run() {
callback.onNetworkEvent(event);
}
});
}
}
}<file_sep>package com.dreampany.frame.data.enums;
import android.os.Parcelable;
public interface Type extends Parcelable {
boolean equals(Type type);
String value();
int ordinalValue();
}<file_sep>package com.dreampany.frame.data.util;
import android.content.Context;
import android.os.Looper;
import android.widget.Toast;
public final class NotifyUtil {
private NotifyUtil() {
}
public static void longToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
public static void shortToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
public static void toast(Context context, final String text) {
toast(context, text, Toast.LENGTH_SHORT);
}
public static void toast(final Context context, final String text, final int duration) {
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
Toast.makeText(context, text, duration).show();
} else {
AndroidUtil.getHandler().post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, text, duration).show();
}
});
}
}
}
<file_sep>package com.dreampany.frame.ui.activity;
import android.view.Menu;
import android.view.MenuItem;
/**
* Created by nuc on 8/9/2016.
*/
public abstract class BaseMenuActivity extends BaseActivity {
private final int defaultMenuResourceId = 0;
private int menuResourceId = defaultMenuResourceId;
public int getMenuResourceId() {
return menuResourceId;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (getMenuResourceId() <= defaultMenuResourceId) {
menu.clear();
} else {
getMenuInflater().inflate(getMenuResourceId(), menu);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
public void optionMenu(int menuResourceId) {
this.menuResourceId = menuResourceId;
supportInvalidateOptionsMenu();
}
}
<file_sep>package com.dreampany.frame.data.model;
import android.os.Parcel;
import com.google.common.primitives.Longs;
import com.google.firebase.database.Exclude;
import com.dreampany.frame.data.util.DataUtil;
import java.lang.reflect.Field;
/**
* Created by nuc on 12/6/2015.
*/
public abstract class Base extends BaseParcel {
private long id;
private long time;
private long hash;
protected Base() {
}
protected Base(Parcel in) {
id = in.readLong();
time = in.readLong();
hash = in.readLong();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeLong(time);
dest.writeLong(hash);
}
@Override
public boolean equals(Object inObject) {
if (this == inObject) {
return true;
}
if (!Base.class.isInstance(inObject)) {
return false;
}
Base base = (Base) inObject;
return hash == base.hash;
}
@Override
public int hashCode() {
int hashCode = Longs.hashCode(hash);
return hashCode;
}
@Exclude
public long getId() {
return this.id;
}
@Exclude
public long getTime() {
return this.time;
}
public long getHash() {
return hash;
}
public Base setId(long id) {
this.id = id;
return this;
}
public Base setTime(long time) {
this.time = time;
return this;
}
public Base setHash(long hash) {
this.hash = hash;
return this;
}
protected String toString(Object object) {
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");
result.append(object.getClass().getName());
result.append(" Object {");
result.append(newLine);
//determine fields declared in this class only (no fields of superclass)
Field[] fields = object.getClass().getDeclaredFields();
//print field names paired with their values
for (Field field : fields) {
result.append(" ");
try {
result.append(field.getName());
result.append(": ");
//requires access to private field:
result.append(field.get(object));
} catch (IllegalAccessException ex) {
System.out.println(ex);
}
result.append(newLine);
}
result.append("}");
return result.toString();
}
public void createHash() {
hash = DataUtil.getSha256();
}
}
<file_sep>package com.dreampany.frame.data.model;
import android.content.Context;
import android.os.Parcel;
import com.google.common.primitives.Longs;
import com.dreampany.frame.data.enums.Type;
import com.dreampany.frame.data.enums.Processor;
/**
* Created by nuc on 11/3/2016.
*/
public abstract class Task<T extends BaseParcel, X extends Type> extends BaseParcel {
protected long id;
protected T item;
protected X itemType;
protected X itemSource;
protected X taskType;
protected X density;
protected X priority;
protected X status;
protected Processor processor;
protected Context context;
protected Task() {
}
protected Task(T item) {
this.item = item;
}
protected Task(X taskType) {
this.taskType = taskType;
}
protected Task(Parcel in) {
super(in);
id = in.readLong();
if (in.readByte() == 0) {
item = null;
} else {
Class<?> itemClazz = (Class<?>) in.readSerializable();
item = in.readParcelable(itemClazz.getClassLoader());
}
itemType = in.readParcelable(Type.class.getClassLoader());
itemSource = in.readParcelable(Type.class.getClassLoader());
taskType = in.readParcelable(Type.class.getClassLoader());
density = in.readParcelable(Type.class.getClassLoader());
priority = in.readParcelable(Type.class.getClassLoader());
status = in.readParcelable(Type.class.getClassLoader());
processor = in.readParcelable(Processor.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeLong(id);
if (item == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
Class<?> itemClazz = item.getClass();
dest.writeSerializable(itemClazz);
dest.writeParcelable(item, flags);
}
dest.writeParcelable(itemType, flags);
dest.writeParcelable(itemSource, flags);
dest.writeParcelable(taskType, flags);
dest.writeParcelable(density, flags);
dest.writeParcelable(priority, flags);
dest.writeParcelable(status, flags);
dest.writeParcelable(processor, flags);
}
@Override
public boolean equals(Object inObject) {
if (this == inObject) {
return true;
}
if (!Task.class.isInstance(inObject)) {
return false;
}
Task item = (Task) inObject;
return id == item.id;
}
@Override
public int hashCode() {
return Longs.hashCode(id);
}
@Override
protected Task<T, X> clone() throws CloneNotSupportedException {
return (Task<T, X>) super.clone();
}
public Task<T, X> setId(long id) {
this.id = id;
return this;
}
public Task<T, X> setItem(T item) {
this.item = item;
return this;
}
public Task<T, X> setItemType(X itemType) {
this.itemType = itemType;
return this;
}
public Task<T, X> setItemSource(X itemSource) {
this.itemSource = itemSource;
return this;
}
public Task<T, X> setTaskType(X taskType) {
this.taskType = taskType;
return this;
}
public Task<T, X> setDensity(X density) {
this.density = density;
return this;
}
public Task<T, X> setPriority(X priority) {
this.priority = priority;
return this;
}
public Task<T, X> setStatus(X status) {
this.status = status;
return this;
}
public Task<T, X> setProcessor(Processor processor) {
this.processor = processor;
return this;
}
public Task<T, X> setContext(Context context) {
this.context = context.getApplicationContext();
return this;
}
public long getId() {
return id;
}
public T getItem() {
return item;
}
public X getItemType() {
return itemType;
}
public X getItemSource() {
return itemSource;
}
public X getTaskType() {
return taskType;
}
public X getDensity() {
return density;
}
public X getPriority() {
return priority;
}
public X getStatus() {
return status;
}
public Processor getProcessor() {
return processor;
}
public Context getContext() {
return context;
}
public void process() {
processor.process(this);
}
}
<file_sep>package com.dreampany.frame.data.enums;
import android.os.Parcel;
/**
* Created by nuc on 12/3/2016.
*/
public enum TaskStatus implements Type {
FAIL, SUCCESS;
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(ordinal());
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<TaskStatus> CREATOR = new Creator<TaskStatus>() {
public TaskStatus createFromParcel(Parcel in) {
return TaskStatus.values()[in.readInt()];
}
public TaskStatus[] newArray(int size) {
return new TaskStatus[size];
}
};
@Override
public boolean equals(Type status) {
return this == status && status instanceof TaskStatus && compareTo((TaskStatus) status) == 0;
}
@Override
public int ordinalValue() {
return ordinal();
}
@Override
public String value() {
return name();
}
}
<file_sep>package com.dreampany.frame.data.adapter;
import android.app.Fragment;
import android.app.FragmentManager;
public class FragmentAdapter<T extends Fragment> extends BaseFragmentAdapter<T> {
private FragmentAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
public static FragmentAdapter<?> newAdapter(FragmentManager fragmentManager) {
return new FragmentAdapter<>(fragmentManager);
}
@Override
public Fragment getItem(int position) {
return newFragment(position);
}
}
<file_sep>apply plugin: 'com.android.library'
apply plugin: 'idea'
android {
compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
useLibrary 'org.apache.http.legacy'
defaultConfig {
minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION)
targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
versionCode 1
versionName "0.0.1"
multiDexEnabled true
vectorDrawables.useSupportLibrary = true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled true
}
}
configurations.all {
exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
//android
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:design:26.0.0-alpha1'
compile 'com.android.support:support-v4:26.0.0-alpha1'
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
compile 'com.android.support:cardview-v7:26.0.0-alpha1'
compile 'com.android.support:preference-v7:26.0.0-alpha1'
compile 'com.android.support:support-v13:26.0.0-alpha1'
compile 'com.android.support:preference-v14:26.0.0-alpha1'
compile 'com.android.support:support-vector-drawable:26.0.0-alpha1'
compile 'com.android.support:animated-vector-drawable:26.0.0-alpha1'
//google
compile 'com.google.firebase:firebase-core:11.0.4'
compile 'com.google.firebase:firebase-auth:11.0.4'
compile 'com.google.firebase:firebase-ads:11.0.4'
compile 'com.google.firebase:firebase-database:11.0.4'
compile 'com.google.firebase:firebase-storage:11.0.4'
compile 'com.google.firebase:firebase-crash:11.0.4'
compile 'com.google.firebase:firebase-appindexing:11.0.4'
compile 'com.google.android.gms:play-services-location:11.0.4'
//compile 'com.google.android.gms:play-services-ads:11.0.4'
compile 'com.google.guava:guava:23.0-android'
compile 'com.google.code.gson:gson:2.8.1'
compile 'com.google.protobuf:protobuf-java:3.3.0'
//firebase
//compile 'com.firebaseui:firebase-ui:1.0.1'
//facebook
compile 'com.facebook.android:facebook-android-sdk:4.18.0'
compile 'com.facebook.fresco:fresco:1.3.0'
compile 'com.facebook.network.connectionclass:connectionclass:1.0.1'
compile 'com.facebook.shimmer:shimmer:0.1.0@aar'
//twitter
//compile 'com.twitter.sdk.android:twitter:2.2.0'
//squareup
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okio:okio:1.13.0'
// apache
//compile 'commons-codec:commons-codec:1.10'
//compile 'org.apache.httpcomponents:httpclient:4.5.2'
//compile 'org.apache.httpcomponents:httpmime:4.5.2'
compile 'org.apache.commons:commons-lang3:3.6'
//rx
compile 'io.reactivex.rxjava2:rxjava:2.1.3'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
//util
compile 'org.greenrobot:essentials:3.0.0-RC1'
compile 'org.greenrobot:eventbus:3.0.0'
compile 'joda-time:joda-time:2.9.9'
//compile 'com.wordnik:wordnik-android-client:4.0'
compile 'com.memetix:microsoft-translator-java-api:0.6.2'
compile 'com.kbeanie:multipicker:1.1.3@aar'
compile 'com.karumi:dexter:4.1.0'
compile 'com.jaredrummler:android-device-names:1.1.2'
compile 'net.yslibrary.keyboardvisibilityevent:keyboardvisibilityevent:2.0.0'
compile 'com.sromku:simple-storage:1.2.0'
compile 'org.kocakosm:pitaya:0.4'
compile 'org.nibor.autolink:autolink:0.6.0'
compile 'com.luffykou:android-common-utils:1.1.3'
compile 'cn.trinea.android.common:trinea-android-common:4.2.15'
compile 'com.sromku:simple-storage:1.2.0'
compile 'io.netty:netty-buffer:4.1.0.Beta5'
compile 'cc.mvdan.accesspoint:library:0.2.0'
compile 'com.kbeanie:multipicker:1.1.31@aar'
compile 'com.einmalfel:earl:1.1.0'
compile 'com.github.pwittchen:prefser-rx2:2.1.0'
//compile 'com.github.nisrulz:android-utils:1.0.3'
// compile 'net.the4thdimension:android-utils:2.0.4'
//ui library
compile 'eu.davidea:flipview:1.1.1'
compile 'eu.davidea:flexible-adapter:5.0.0-rc2'
compile 'eu.davidea:flexible-adapter-databinding:1.0.0-b1@aar'
compile 'com.daasuu:CountAnimationTextView:0.1.1'
compile 'com.gordonwong:material-sheet-fab:1.2.1'
compile 'com.ms-square:expandableTextView:0.1.4'
compile 'net.cachapa.expandablelayout:expandablelayout:2.8'
compile 'com.flyco.roundview:FlycoRoundView_Lib:1.1.4@aar'
compile 'com.wang.avi:library:2.1.3'
compile 'com.daimajia.swipelayout:library:1.2.0@aar'
compile 'com.vstechlab.easyfonts:easyfonts:1.0.0'
compile 'com.dev.sacot41:scviewpager:0.0.4'
compile 'com.roughike:swipe-selector:1.0.6'
compile 'com.roughike:bottom-bar:2.3.1'
compile 'com.github.medyo:fancybuttons:1.8.3'
compile 'id.arieridwan:pageloader:0.0.2'
compile 'com.github.iammert:StatusView:1.3'
compile 'com.github.gturedi:stateful-layout:1.2.1'
//compile 'com.github.traex.rippleeffect:library:1.3'
compile 'me.zhanghai.android.materialprogressbar:library:1.4.1'
compile 'com.github.bassaer:chatmessageview:1.3.3'
compile 'me.himanshusoni.chatmessageview:chat-message-view:1.0.7'
compile 'com.github.jinatonic.confetti:confetti:1.1.0'
compile 'com.github.apl-devs:appintro:v4.2.2'
compile 'com.github.jakob-grabner:Circle-Progress-View:v1.3'
// compile 'com.github.Hitta:RippleEffect:82cf00e551' //AndroidRuntime: java.lang.IllegalStateException: Underflow in restore - more restores than saves
//maven
//compile 'com.github.linger1216:labelview:v1.1.1'
//compile 'com.github.shts:TriangleLabelView:1.1.2'
// compile 'org.slf4j:slf4j-android:1.7.22'
// compile 'io.netty:netty-buffer:5.0.0.Alpha2'
// compile 'com.google.protobuf:protobuf-java:2.6.1'
// compile project(':swipe-selector')
}
//apply plugin: 'com.google.gms.google-services'
idea {
module {
downloadJavadoc = true
}
}
<file_sep>package com.dreampany.frame.data.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import com.dreampany.frame.data.enums.Type;
import com.dreampany.frame.data.model.Base;
import com.dreampany.frame.data.model.Task;
/**
* Created by nuc on 4/12/2016.
*/
public final class FragmentUtil {
private FragmentUtil() {
}
public static Fragment getFragmentById(Activity activity, int fragmentId) {
return activity.getFragmentManager().findFragmentById(fragmentId);
}
public static <T extends Fragment> T getFragmentByTag(Activity activity, String fragmentTag) {
return (T) activity.getFragmentManager().findFragmentByTag(fragmentTag);
}
public static <T extends android.support.v4.app.Fragment> T getSupportFragmentByTag(AppCompatActivity activity, String fragmentTag) {
return (T) activity.getSupportFragmentManager().findFragmentByTag(fragmentTag);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static android.support.v4.app.Fragment getFragmentById(android.support.v4.app.Fragment fragment, int fragmentId) {
return fragment.getChildFragmentManager().findFragmentById(fragmentId);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static <F extends android.support.v4.app.Fragment> F getFragmentByTag(android.support.v4.app.Fragment fragment, String fragmentTag) {
return (F) fragment.getChildFragmentManager().findFragmentByTag(fragmentTag);
}
public static <F extends Fragment> F newFragment(Class<F> fragmentClass) {
try {
return fragmentClass.newInstance();
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
}
return null;
}
public static <F extends android.support.v4.app.Fragment> F newSupportFragment(Class<F> fragmentClass) {
try {
return fragmentClass.newInstance();
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
}
return null;
}
public static <F extends Fragment, T extends Base, X extends Type> F getFragment(Activity activity, Class<F> fragmentClass, Task<T, X> task) {
F fragment = getFragmentByTag(activity, fragmentClass.getName());
if (fragment == null) {
fragment = newFragment(fragmentClass);
if (fragment != null && task != null) {
Bundle bundle = new Bundle();
bundle.putParcelable(Task.class.getName(), task);
fragment.setArguments(bundle);
}
} else if (task != null) {
fragment.getArguments().putParcelable(Task.class.getName(), task);
}
return fragment;
}
public static <F extends Fragment, T extends Parcelable> F getFragment(Activity activity, Class<F> fragmentClass) {
F fragment = getFragmentByTag(activity, fragmentClass.getName());
if (fragment == null) {
fragment = newFragment(fragmentClass);
LogKit.verbose("New Fragment " + fragment);
/* if (fragment != null && config != null) {
Bundle bundle = new Bundle();
bundle.putParcelable(config.getClass().getName(), config);
fragment.setArguments(bundle);
}*/
} /*else if (config != null) {
fragment.getArguments().putParcelable(config.getClass().getName(), config);
}*/
return fragment;
}
public static <F extends android.support.v4.app.Fragment, T extends Parcelable> F getSupportFragment(AppCompatActivity activity, Class<F> fragmentClass, Task<?, ?> task) {
F fragment = getSupportFragmentByTag(activity, fragmentClass.getName());
if (fragment == null) {
fragment = newSupportFragment(fragmentClass);
LogKit.verbose("New Fragment " + fragment);
if (fragment != null && task != null) {
Bundle bundle = new Bundle();
bundle.putParcelable(Task.class.getName(), task);
fragment.setArguments(bundle);
}
} else if (task != null) {
fragment.getArguments().putParcelable(Task.class.getName(), task);
}
return fragment;
}
public static <F extends android.support.v4.app.Fragment, T extends Parcelable> F getSupportFragment(android.support.v4.app.Fragment parent, Class<F> fragmentClass, Task<?, ?> task) {
F fragment = getFragmentByTag(parent, fragmentClass.getName());
if (fragment == null) {
fragment = newSupportFragment(fragmentClass);
LogKit.verbose("New Fragment " + fragment);
if (fragment != null && task != null) {
Bundle bundle = new Bundle();
bundle.putParcelable(Task.class.getName(), task);
fragment.setArguments(bundle);
}
} else if (task != null) {
fragment.getArguments().putParcelable(Task.class.getName(), task);
}
return fragment;
}
public static <F extends Fragment, T extends Base> Fragment commitFragment(final Activity activity, final Class<F> fragmentClass, final Task<T, ?> task, final int parentLayoutId) {
final Fragment fragment = getFragment(activity, fragmentClass, task);
Runnable commitRunnable = new Runnable() {
@Override
public void run() {
if (activity.isDestroyed() || activity.isFinishing()) {
return;
}
activity.getFragmentManager().
beginTransaction().
setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out).
replace(parentLayoutId, fragment, fragmentClass.getName()).
// addToBackStack(fragmentClass.getName()).
commitAllowingStateLoss();
}
};
AndroidUtil.postDelay(commitRunnable);
return fragment;
}
public static <F extends Fragment, T extends Parcelable> F commitFragment(final Activity activity, final Class<F> fragmentClass, final int parentId) {
final F fragment = getFragment(activity, fragmentClass);
Runnable commitRunnable = new Runnable() {
@Override
public void run() {
if (activity.isDestroyed() || activity.isFinishing()) {
return;
}
activity.getFragmentManager().
beginTransaction().
setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out).
replace(parentId, fragment, fragmentClass.getName()).
commitAllowingStateLoss();
}
};
AndroidUtil.postDelay(commitRunnable);
return fragment;
}
public static <F extends android.support.v4.app.Fragment, T extends Parcelable> F commitFragmentCompat(final AppCompatActivity activity, final Class<F> fragmentClass, final int parentId) {
final F fragment = getSupportFragment(activity, fragmentClass, null);
Runnable commitRunnable = new Runnable() {
@Override
public void run() {
if (activity.isDestroyed() || activity.isFinishing()) {
return;
}
activity.getSupportFragmentManager().
beginTransaction().
//setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out).
replace(parentId, fragment, fragmentClass.getName()).
commitAllowingStateLoss();
}
};
AndroidUtil.postDelay(commitRunnable);
return fragment;
}
public static <F extends android.support.v4.app.Fragment, T extends Parcelable> F commitFragmentCompat(final AppCompatActivity activity, final Class<F> fragmentClass, final int parentId, Task<?, ?> task) {
final F fragment = getSupportFragment(activity, fragmentClass, task);
Runnable commitRunnable = new Runnable() {
@Override
public void run() {
if (activity.isDestroyed() || activity.isFinishing()) {
return;
}
activity.getSupportFragmentManager().
beginTransaction().
//setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out).
replace(parentId, fragment, fragmentClass.getName()).
commitAllowingStateLoss();
}
};
AndroidUtil.postDelay(commitRunnable);
return fragment;
}
public static <F extends android.support.v4.app.Fragment, T extends Parcelable> F commitFragmentCompat(final android.support.v4.app.Fragment parent, final Class<F> fragmentClass, final int parentId) {
final F fragment = getSupportFragment(parent, fragmentClass, null);
Runnable commitRunnable = new Runnable() {
@Override
public void run() {
parent.getChildFragmentManager().
beginTransaction().
//setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out).
replace(parentId, fragment, fragmentClass.getName()).
commitAllowingStateLoss();
}
};
AndroidUtil.post(commitRunnable, 500L); // need a good time to load parent fragment
return fragment;
}
}
<file_sep>package com.dreampany.frame.data.util;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* Created by nuc on 1/18/2017.
*/
public final class JsonUtil {
private JsonUtil() {}
public static JsonObject getJsonObject(String json) {
JsonParser parser = new JsonParser();
return parser.parse(json).getAsJsonObject();
}
}
<file_sep>package com.dreampany.frame.data.enums;
import android.os.Parcelable;
import com.dreampany.frame.data.model.Task;
public interface Processor extends Parcelable {
void process(Task task);
}<file_sep>/*
package com.ringbyte.framekit.data.model;
import android.databinding.Bindable;
import android.os.Parcel;
import com.ringbyte.english.BR;
*/
/**
* Created by nuc on 8/22/2015.
*//*
public class Category extends Base {
private String title;
private long count;
private boolean checked;
public Category(String title) {
this.title = title;
}
public Category(String title, boolean checked) {
this.title = title;
this.checked = checked;
}
protected Category(Parcel in) {
super(in);
title = in.readString();
count = in.readLong();
checked = in.readByte() != 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(title);
dest.writeLong(count);
dest.writeByte((byte) (checked ? 1 : 0));
}
public static final Creator<Category> CREATOR = new Creator<Category>() {
@Override
public Category createFromParcel(Parcel in) {
return new Category(in);
}
@Override
public Category[] newArray(int size) {
return new Category[size];
}
};
@Override
public int describeContents() {
return 0;
}
public Category setCategory(Category category) {
setTitle(category.title);
setCount(category.count);
setChecked(category.checked);
return this;
}
@Bindable
public String getTitle() {
return this.title;
}
@Bindable
public long getCount() {
return count;
}
@Bindable
public boolean isChecked() {
return checked;
}
public Category setTitle(String title) {
this.title = title;
notifyPropertyChanged(BR.title);
return this;
}
public Category setCount(long count) {
this.count = count;
notifyPropertyChanged(BR.count);
return this;
}
public Category setChecked(boolean checked) {
this.checked = checked;
notifyPropertyChanged(BR.checked);
return this;
}
}
*/
<file_sep>package com.dreampany.frame.data.manager;
import android.content.Context;
import com.dreampany.frame.data.enums.Type;
import com.dreampany.frame.data.model.Point;
import com.dreampany.frame.data.model.Session;
import com.dreampany.frame.data.provider.pref.FramePref;
import com.dreampany.frame.data.provider.sqlite.FrameSQLite;
import com.dreampany.frame.data.util.AndroidUtil;
import com.dreampany.frame.data.util.DataUtil;
/**
* Created by air on 5/11/17.
*/
public final class PointManager {
public static final long defaultThreshold = 100;
public static final long defaultPoints = 1000L;
private static final String usedPoints = "used_points";
private static PointManager manager;
private long threshold = defaultThreshold;
private PointManager() {
}
public static synchronized PointManager onInstance() {
if (manager == null) {
manager = new PointManager();
}
return manager;
}
public long toPoints(long credits) {
long points = credits / threshold;
return points < 0L ? 0L : points;
}
public void trackPoints(Context context, Session session, Type pointType) {
long credits = session.getSessionTime() / 1000; // seconds
long points = toPoints(credits);
Point point = new Point();
point.setHash(session.getHash());
point.setPoints(points);
point.setType(pointType);
FrameSQLite.onInstance(context).write(point);
}
public void trackPoints(Context context, long hash, long points, Type pointType) {
Point point = new Point();
point.setHash(hash);
point.setPoints(points);
point.setType(pointType);
FrameSQLite.onInstance(context).write(point);
}
public long getAvailablePoints(Context context) {
long totalPoints = FrameSQLite.onInstance(context).getPoints();
long usedPoints = FramePref.onInstance(context).getLong(PointManager.usedPoints);
return totalPoints - usedPoints;
}
public long getPoints(Context context, Type... types) {
long points = 0L;
for (Type type : types) {
points += FrameSQLite.onInstance(context).getPoints(type);
}
return points;
}
public void dragDefaultPoints(Context context, Type pointType) {
if (FrameSQLite.onInstance(context).isEmpty(pointType)) {
String appId = AndroidUtil.getApplicationId(context);
long hash = DataUtil.getSha256(appId);
Point point = new Point();
point.setHash(hash);
point.setPoints(defaultPoints);
point.setType(pointType);
FrameSQLite.onInstance(context).write(point);
}
}
}
<file_sep>package com.dreampany.frame.data.thread;
public abstract class Runner implements Runnable {
protected long defaultWait = 1000L;
protected long superWait = 3 * defaultWait;
protected long periodWait = 1000L / 100;
protected long wait = defaultWait;
private Thread thread;
private boolean running;
private final Object guard = new Object();
private volatile boolean guarded;
public void start() {
if (running) {
return;
}
running = true;
thread = new Thread(this);
thread.setDaemon(true);
thread.start();
}
public void stop() {
if (!running) {
return;
}
running = false;
thread.interrupt();
notifyRunner();
}
public void waitRunner(long timeoutMs) {
if (guarded) {
//return;
}
guarded = true;
synchronized (guard) {
try {
if (timeoutMs > 0L) {
guard.wait(timeoutMs);
} else {
guard.wait();
}
} catch (InterruptedException e) {
}
}
}
public void notifyRunner() {
if (!guarded) {
//return;
}
guarded = false;
synchronized (guard) {
guard.notify();
}
}
protected void silentStop() {
if (running) {
running = false;
}
}
public boolean isRunning() {
return running;
}
private void waitFor(long timeout) throws InterruptedException {
Thread.sleep(timeout);
}
protected abstract boolean looping() throws InterruptedException;
@Override
public void run() {
try {
while (running) {
boolean looped = looping();
if (!looped) {
break;
}
}
} catch (InterruptedException interrupt) {
}
running = false;
}
}<file_sep>package com.dreampany.frame.data.util;
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.hardware.display.DisplayManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Parcelable;
import android.os.PowerManager;
import android.provider.Settings;
import android.speech.tts.TextToSpeech;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import com.google.common.hash.Hashing;
import com.jaredrummler.android.device.DeviceName;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.listener.single.PermissionListener;
import com.dreampany.frame.data.manager.PermissionManager;
import com.dreampany.frame.data.model.Task;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public final class AndroidUtil {
private static final String TAG = AndroidUtil.class.getSimpleName();
private static boolean debug = true;
private AndroidUtil() {
}
public static void setDebug(Context context) {
AndroidUtil.debug = isDebug(context);
}
public static final String WRITE_EXTERNAL_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
public static boolean isMarshmallow() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
public static boolean isPermissionGranted(Context context, String permission) {
return PermissionManager.isPermissionGranted(context, permission);
}
public static void requestPermission(Activity activity, String permission, PermissionListener permissionListener) {
Dexter.withActivity(activity)
.withPermission(permission)
.withListener(permissionListener)
.check();
}
public static boolean isDebug() {
return debug;
//return false;
}
public static boolean isDebug(Context context) {
boolean debuggable = false;
Context appContext = context.getApplicationContext();
PackageManager pm = appContext.getPackageManager();
try {
ApplicationInfo appInfo = pm.getApplicationInfo(appContext.getPackageName(), 0);
debuggable = (0 != (appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE));
} catch (PackageManager.NameNotFoundException e) {
/*debuggable variable will remain false*/
}
return debuggable;
}
public static boolean needThread(Thread thread) {
return (thread == null || !thread.isAlive());
}
public static Thread createThread(Runnable runnable) {
return new Thread(runnable);
}
public static Thread createThread(Runnable runnable, String name) {
Thread thread = new Thread(runnable);
thread.setName(name);
thread.setDaemon(true);
return thread;
}
public static void sleep(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
}
}
/* public static String getApplicationId() {
return BuildConfig.APPLICATION_ID;
}
public static int getVersionCode() {
return BuildConfig.VERSION_CODE;
}*/
public static long getDeviceId(Context context) {
String androidId = Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);//InstanceID.getInstance(context).getId();
long deviceId = Hashing.sha256().newHasher().putUnencodedChars(androidId).hash().asLong();
return Math.abs(deviceId);
}
public static long getPackageId(Context context) {
String packageName = context.getApplicationContext().getPackageName();
return DataUtil.getSha256(packageName);
}
public static String getDeviceName() {
return DeviceName.getDeviceName();
}
public static boolean isAndroid() {
return System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik");
}
public static void log(String unit, String message) {
if (isDebug()) {
if (isAndroid()) {
Log.d(unit, message);
} else {
System.out.println(unit + ": " + message);
}
}
}
public static void logE(String unit, String message) {
if (isAndroid()) {
Log.d(unit, "FATAL ERROR: " + message);
} else {
System.out.println(unit + ": FATAL ERROR: " + message);
}
throw new RuntimeException(unit + ": FATAL ERROR: " + message);
}
public static byte byteOfInt(int value, int which) {
int shift = which * 8;
return (byte) (value >> shift);
}
public static InetAddress intToInet(int value) {
byte[] bytes = new byte[4];
for (int e = 0; e < 4; ++e) {
bytes[e] = byteOfInt(value, e);
}
try {
return InetAddress.getByAddress(bytes);
} catch (UnknownHostException var3) {
return null;
}
}
public static Object invokeQuietly(Method method, Object receiver, Object... args) {
try {
return method.invoke(receiver, args);
} catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException var4) {
Log.e("WM", "", var4);
return null;
}
}
public static <T extends Activity> void openActivity(Activity activity, Class<T> clazz) {
activity.startActivity(new Intent(activity, clazz));
}
public static <T extends Activity> void openDestroyActivity(Activity activity, Class<T> clazz) {
activity.startActivity(new Intent(activity, clazz));
activity.finish();
}
public static <T extends Activity> void openActivity(Fragment fragment, Class<T> clazz) {
fragment.getActivity().startActivity(new Intent(fragment.getActivity(), clazz));
}
public static <T extends Activity> void openDestroyActivity(Fragment fragment, Class<T> clazz) {
fragment.getActivity().startActivity(new Intent(fragment.getActivity(), clazz));
fragment.getActivity().finish();
}
public static <T extends Activity> void openActivity(Activity activity, Class<T> clazz, Task<?, ?> task) {
Intent intent = new Intent(activity, clazz);
if (task != null) {
intent.putExtra(Task.class.getName(), (Parcelable) task);
}
activity.startActivity(intent);
}
public static <T extends Activity> void openActivityForResult(Activity activity, Class<T> clazz, int resultCode) {
activity.startActivityForResult(new Intent(activity, clazz), resultCode);
}
public static String printKeyHash(Activity context) {
PackageInfo packageInfo;
String key = null;
try {
//getting application package name, as defined in manifest
String packageName = context.getApplicationContext().getPackageName();
//Retriving package verbose
packageInfo = context.getPackageManager().getPackageInfo(packageName,
PackageManager.GET_SIGNATURES);
Log.e("Package Name=", context.getApplicationContext().getPackageName());
for (android.content.pm.Signature signature : packageInfo.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
key = new String(Base64.encode(md.digest(), 0));
// String key = new String(Base64.encodeBytes(md.digest()));
Log.e("Key Hash=", key);
}
} catch (PackageManager.NameNotFoundException e1) {
Log.e("Name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("No such an algorithm", e.toString());
} catch (Exception e) {
Log.e("Exception", e.toString());
}
return key;
}
public static Locale getCurrentLocale(Context context) {
return context.getResources().getConfiguration().locale;
}
//Build information
/* public static boolean isDebug(BuildConfig buildConfig) {
return BuildConfig.DEBUG;
}*/
public static float dp2px(final Context context, final float dpValue) {
return dpValue * context.getResources().getDisplayMetrics().density;
}
public static void hideKeyboard(Activity activity) {
/* ((InputMethodManager) view.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(view.getWindowToken(), 0);*/
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
public static void showKeyboard(Activity activity) {
// Check if no view has focus:
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
}
/**
* Is the screen of the device on.
*
* @param context the getContext
* @return true when (at least one) screen is on
*/
public static boolean isScreenOn(Context context) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
boolean screenOn = false;
for (Display display : dm.getDisplays()) {
if (display.getState() != Display.STATE_OFF) {
screenOn = true;
}
}
return screenOn;
} else {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//noinspection deprecation
return pm.isScreenOn();
}
}
public static String getApplicationId(Context context) {
PackageInfo packageInfo = getPackageInfo(context);
if (packageInfo != null) {
return packageInfo.packageName;
}
return null;
}
public static int getVersionCode(Context context) {
PackageInfo packageInfo = getPackageInfo(context);
if (packageInfo != null) {
return packageInfo.versionCode;
}
return 0;
}
private static PackageInfo getPackageInfo(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo;
} catch (PackageManager.NameNotFoundException nameException) {
return null;
}
}
// Android System Queue
private static Handler handler;
private static Handler nonUiHandler = new Handler(Looper.myLooper());
public static Handler getHandler() {
if (handler == null) {
handler = new Handler(Looper.getMainLooper());
}
return handler;
}
private static final long defaultDelay = 250L;
public static void removeRunnable(Runnable runnable) {
getHandler().removeCallbacks(runnable);
}
public static void post(Runnable runnable, long timeDelay) {
getHandler().postDelayed(runnable, timeDelay);
}
public static void postDelay(Runnable runnable) {
post(runnable, defaultDelay);
}
public static void post(Runnable runnable) {
getHandler().post(runnable);
}
public static void postNonUi(Runnable runnable, long timeout) {
nonUiHandler.postDelayed(runnable, timeout);
}
/* // Creating
public static <T extends Fragment> T newFragment(Class<T> fragmentClass) {
try {
return fragmentClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}*/
// Checking and Getting
public static boolean isNull(Object object) {
return object == null;
}
public static boolean isNull(View view) {
return view == null;
}
public static boolean isNull(Context context) {
return context == null;
}
public static View getViewById(View parentView, int viewId) {
if (!isNull(parentView)) {
return parentView.findViewById(viewId);
}
return null;
}
public static ViewPager getViewPager(View parentView, int viewPagerId) {
View viewPager = getViewById(parentView, viewPagerId);
if (ViewPager.class.isInstance(viewPager)) {
return (ViewPager) viewPager;
}
return null;
}
public static TabLayout getTabLayout(View parentView, int tabLayoutId) {
View tabLayout = getViewById(parentView, tabLayoutId);
if (TabLayout.class.isInstance(tabLayout)) {
return (TabLayout) tabLayout;
}
return null;
}
private static TextToSpeech textToSpeech;
public static void initTextToSpeech(Context context) {
if (textToSpeech == null) {
try {
textToSpeech = new TextToSpeech(context.getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.getDefault());
}
}
});
} catch (IllegalArgumentException e) {
}
}
}
public static void speak(String text) {
if (textToSpeech != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
} else {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
public static void stopTextToSpeech() {
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
textToSpeech = null;
}
}
public static void openVideo(Context context, String uri) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setDataAndType(Uri.parse(uri), "video/mp4");
context.startActivity(intent);
}
public static boolean isServiceRunning(Context context, Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public static boolean startService(Context context, Class<?> serviceClass) {
if (AndroidUtil.isServiceRunning(context, serviceClass)) {
return false;
}
Intent intent = new Intent(context, serviceClass);
context.startService(intent);
return true;
}
public static boolean stopService(Context context, Class<?> serviceClass) {
return context.stopService(new Intent(context, serviceClass));
}
public static boolean bindService(Context context, Class<?> serviceClass, ServiceConnection serviceConnection) {
return context.bindService(new Intent(context, serviceClass), serviceConnection, Context.BIND_AUTO_CREATE);
}
public static boolean unbindService(Context context, ServiceConnection serviceConnection) {
context.unbindService(serviceConnection);
return true;
}
public static boolean hasLollipop() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
public static boolean isJellyBeanMR2() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
}
public static boolean hasFeature(Context context, String feature) {
return context.getApplicationContext().getPackageManager().hasSystemFeature(feature);
}
public static BluetoothManager getBluetoothManager(Context context) {
return (BluetoothManager) context.getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);
}
private static HandlerThread handlerThread;
private static Handler backgroundHandler;
public static Handler getBackgroundHandler() {
if (handlerThread == null) {
handlerThread = new HandlerThread("background-thread");
handlerThread.start();
backgroundHandler = new Handler(handlerThread.getLooper());
}
return backgroundHandler;
}
public static boolean isAppInstalled(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
public static int getTargetSDKVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.applicationInfo.targetSdkVersion;
} catch (PackageManager.NameNotFoundException nnf) {
return -1;
}
}
/* public static boolean isShareServiceRunning(Context ctx) {
ActivityManager manager = (ActivityManager) ctx
.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (SHAREthemService.class.getCanonicalName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}*/
@RequiresApi(api = Build.VERSION_CODES.M)
public static boolean hasOverlayPermission(Context context) {
return Settings.canDrawOverlays(context.getApplicationContext());
}
@RequiresApi(api = Build.VERSION_CODES.M)
public static boolean hasWriteSettingsPermission(Context context) {
return Settings.System.canWrite(context.getApplicationContext());
}
public static boolean checkOverlayPermission(Activity activity, int requestCode) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (!hasOverlayPermission(activity)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + activity.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivityForResult(intent, requestCode);
return false;
} else {
return true;
}
}
public static boolean checkWriteSettingsPermission(Activity activity, int requestCode) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (!hasWriteSettingsPermission(activity.getApplicationContext())) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + activity.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivityForResult(intent, requestCode);
return false;
} else {
return true;
}
}
public static boolean hasPermission(Context context, String permission) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
return ContextCompat.checkSelfPermission(context.getApplicationContext(), permission) == PackageManager.PERMISSION_GRANTED;
}
public static List<String> getStrings(Context context, int resourceId) {
Resources resources = context.getResources();
String[] items = resources.getStringArray(resourceId);
return Arrays.asList(items);
}
}
<file_sep>package com.dreampany.frame.data.model;
/**
* Created by air on 7/20/17.
*/
public class Entry {
}
<file_sep># frame
A android framwork to work happily.
<file_sep>package com.dreampany.frame.data.connection;
/**
* Created by nuc on 6/10/2016.
*/
public interface Connection {
void start();
void stop();
}
| 1729aacbae773659f73b6cc08efd1f51c1bb7060 | [
"Markdown",
"Java",
"Gradle"
] | 30 | Java | NerdFaisal404/framework | e3bd049a89e9451a041e0208841e8736eb06cecf | e6b33a18bd2b4507a4ab508f08aef012523eac44 | |
refs/heads/master | <repo_name>frc3324/Metrobots2014<file_sep>/SimpleTemplate/util/gamepad.cpp
#include "GamePad.h"
#include <math.h>
#include <WPILib.h>
GamePad::GamePad(int port){
joystick_ = new Joystick( port );
dPadLeftDownEvent = false;
dPadRightDownEvent = false;
dPadLeftOld = false;
dPadRightOld = false;
for( int i = 0; i < MAX_NUM_BUTTONS; i++ ){
oldBtnStates[i] = false;
newBtnStates[i] = false;
upEventStates[i] = false;
downEventStates[i] = false;
}
}
double GamePad::GetAxis( int axis ){
double output;
if( axis == GamePad::LEFT_X || axis == GamePad::RIGHT_X ){
output = joystick_->GetRawAxis( axis );
}
else{
output = -joystick_->GetRawAxis( axis );
}
if( fabs(output) < GamePad::AXIS_DEADBAND ){
output = 0.0;
}
return output;
}
void GamePad::Update(){
for( int i = 1; i < MAX_NUM_BUTTONS + 1; i++ ){
newBtnStates[i] = joystick_->GetRawButton(i);
upEventStates[i] = !newBtnStates[i] && oldBtnStates[i];
downEventStates[i] = newBtnStates[i] && !oldBtnStates[i];
oldBtnStates[i] = newBtnStates[i];
}
dPadRightDownEvent = (joystick_->GetRawAxis(GamePad::DPAD_X) > 0.0) && !dPadRightOld;
dPadLeftDownEvent = (joystick_->GetRawAxis(GamePad::DPAD_X) < 0.0) && !dPadLeftOld;
dPadRightOld = joystick_->GetRawAxis(GamePad::DPAD_X) > 0.0;
dPadLeftOld = joystick_->GetRawAxis(GamePad::DPAD_X) < 0.0;
}
bool GamePad::GetButton( int button ){
return newBtnStates[ button ];
}
bool GamePad::GetButtonDown( int button ){
return downEventStates[ button ];
}
bool GamePad::GetButtonUp( int button ){
return upEventStates[ button ];
}
bool GamePad::GetDPadLeftDown(){
return dPadLeftDownEvent;
}
bool GamePad::GetDPadRightDown(){
return dPadRightDownEvent;
}
<file_sep>/SimpleTemplate/util/gamepad.h
#ifndef GAME_PAD_H
#define GAME_PAD_H
#include "WPILib.h"
#define MAX_NUM_BUTTONS 12
class GamePad {
public:
GamePad( int port );
double GetAxis( int axis );
void Update();
bool GetButton( int button );
bool GetButtonDown( int button );
bool GetButtonUp( int button );
bool GetDPadLeftDown();
bool GetDPadRightDown();
static const double AXIS_DEADBAND = 0.1;
static const int A = 1;
static const int B = 2;
static const int X = 3;
static const int Y = 4;
static const int LB = 5;
static const int RB = 6;
static const int BACK = 7;
static const int START = 8;
static const int LEFT_JS = 9;
static const int RIGHT_JS = 10;
static const int LEFT_X = 1;
static const int LEFT_Y = 2;
static const int TRIGGER = 3;
static const int RIGHT_X = 4;
static const int RIGHT_Y = 5;
static const int DPAD_X = 6;
static const int DPAD_Y = 7;
Joystick *joystick_;
private:
bool oldBtnStates[ MAX_NUM_BUTTONS ];
bool newBtnStates[ MAX_NUM_BUTTONS ];
bool upEventStates[ MAX_NUM_BUTTONS ];
bool downEventStates[ MAX_NUM_BUTTONS ];
bool dPadLeftDownEvent;
bool dPadRightDownEvent;
bool dPadLeftOld;
bool dPadRightOld;
};
#endif
<file_sep>/SimpleTemplate/kicker.h
#ifndef KICKER_H
#define KICKER_H
#include "WPILib.h"
#include <Math.h>
#include "util/metropidcontroller.h"
class Kicker {
public:
Kicker( SpeedController *kicker1, SpeedController *kicker2, AnalogChannel *kickerPot);
~Kicker(){};
void KickBall();
void Actuate();
void Disable();
void KickBallN();
void PullUp();
void RaiseLeg();
void StopRaise();
bool State();
void KickerPotVal(int x);
int GetAdjustedPotValue();
Timer* t;
enum {Nothing, PullingBack, Kicking, Sitting, Retracting, Pull, Raising} state;
//int state; // 0 = Nothing, 1 = Pulling Back, 2 = Kicking
SpeedController *kicker1;
SpeedController *kicker2;
AnalogChannel *kickerPot;
static const int kickRotationMin = 0; //dummy value
static const int kickRotationMax = 10; //dummy value3
bool isKicking, isPullingBack, isSitting, isRetracting;
int kickerPotVal;
};
#endif
<file_sep>/SimpleTemplate/pickup.h
#ifndef PICKUP_H
#define PICKUP_H
#include "WPILib.h"
#include <Math.h>
#include "util/metropidcontroller.h"
#include "util/dualrelay.h"
class Pickup {
public:
Pickup( SpeedController *motor, DualRelay *angleMotor, DigitalInput *bottomSwitch, DigitalInput *topSwitch );
~Pickup(){};
void Actuate();
void RunIntake(double wheelSpeed);
void Raise();
void Lower();
void ToTop();
void ToBottom();
void StopAngle();
void Intake();
void Expel();
void StopIntake();
void Disable();
void Kick();
bool AllWay();
bool isKicking();
enum {Pushing, Pulling, Kicking, Nothing} pickupState;
enum {Up, Down, Stopped} angleState;
SpeedController *motor;
DualRelay *angleMotor;
DigitalInput *bottomSwitch, *topSwitch;
double motorSpeed;
Relay::Value angleMotorBool;
bool moveAllWay;
};
#endif
<file_sep>/SimpleTemplate/drive.cpp
#include "drive.h"
#include <Math.h>
Drive::Drive( SpeedController *flMotor_, SpeedController *blMotor_, SpeedController *frMotor_, SpeedController *brMotor_,
Encoder *flEncoder_, Encoder *blEncoder_, Encoder *frEncoder_, Encoder *brEncoder_,
Gyro *gyro_ ){
flMotor = flMotor_;
blMotor = blMotor_;
frMotor = frMotor_;
brMotor = brMotor_;
flEncoder = flEncoder_;
blEncoder = blEncoder_;
frEncoder = frEncoder_;
brEncoder = brEncoder_;
flEncoder->Start();
blEncoder->Start();
frEncoder->Start();
brEncoder->Start();
gyro = gyro_;
flPID = new MetroPIDController( Drive::PID_P, Drive::PID_I, Drive::PID_D, MetroPIDController::PID, true );
blPID = new MetroPIDController( Drive::PID_P, Drive::PID_I, Drive::PID_D, MetroPIDController::PID, true );
frPID = new MetroPIDController( Drive::PID_P, Drive::PID_I, Drive::PID_D, MetroPIDController::PID, true );
brPID = new MetroPIDController( Drive::PID_P, Drive::PID_I, Drive::PID_D, MetroPIDController::PID, true );
xPID = new MetroPIDController( Drive::XYTURN_PID_P, Drive::XYTURN_PID_I, Drive::XYTURN_PID_D, MetroPIDController::PID, true );
yPID = new MetroPIDController( Drive::XYTURN_PID_P, Drive::XYTURN_PID_I, Drive::XYTURN_PID_D, MetroPIDController::PID, true );
turnPID = new MetroPIDController( Drive::XYTURN_PID_P, Drive::XYTURN_PID_I, Drive::XYTURN_PID_D, MetroPIDController::PID, true );
flPID->Disable();
blPID->Disable();
frPID->Disable();
brPID->Disable();
motorInverters[0] = 1;
motorInverters[1] = 1;
motorInverters[2] = 1;
motorInverters[3] = 1;
gyroBias = 0.0;
isPIDControl = false;
isSlowDrive = false;
isFieldOriented = true;
isHoldAngle = false;
driverX = 0.0;
driverY = 0.0;
driverTurn = 0.0;
}
double clamp(double range, double num) {
return (range > fabs(num)) ? 0.0 : num;
}
void Drive::Actuate(){
flPID->SetSource( ( 1 / flEncoder->GetPeriod() ) / Drive::VEL_PID_MULTIPLIER );
blPID->SetSource( -( 1 / blEncoder->GetPeriod() ) / Drive::VEL_PID_MULTIPLIER );
frPID->SetSource( -( 1 / frEncoder->GetPeriod() ) / Drive::VEL_PID_MULTIPLIER );
brPID->SetSource( ( 1 / brEncoder->GetPeriod() ) / Drive::VEL_PID_MULTIPLIER );
double flVel = 1 / flEncoder->GetPeriod() / Drive::VEL_PID_MULTIPLIER;
double blVel = 1 / flEncoder->GetPeriod() / Drive::VEL_PID_MULTIPLIER;
double frVel = -1 / flEncoder->GetPeriod() / Drive::VEL_PID_MULTIPLIER;
double brVel = -1 / flEncoder->GetPeriod() / Drive::VEL_PID_MULTIPLIER;
/*xPID->SetSource( flVel + brVel - blVel - frVel );
yPID->SetSource( flVel + brVel + blVel + frVel );
turnPID->SetSource( flVel - brVel + blVel - frVel );*/
double x = driverX;
double y = driverY;
double turn = driverTurn;
if( isFieldOriented ){
double gAngle = GetGyroAngle();
double cosA = cos( gAngle * 3.14159 / 180 );
double sinA = sin( gAngle * 3.14159 / 180 );
x = driverX*cosA - driverY*sinA;
y = driverX*sinA + driverY*cosA;
}
if( isHoldAngle ){
double gyroAngle = fmod( GetGyroAngle(), 360.0 );
double relativeAngle = gyroAngle - targetAngle;
if( relativeAngle > 180 ){
relativeAngle = ( 180 - ( relativeAngle - 180 ) );
}
turn = Drive::ANGLE_P * relativeAngle;
}
double fl = ( y + x + turn ) * ( isSlowDrive ? Drive::SLOW_DRIVE_MULTIPLIER : 1.0 );
double bl = ( y - x + turn ) * ( isSlowDrive ? Drive::SLOW_DRIVE_MULTIPLIER : 1.0 );
double fr = ( y - x - turn ) * ( isSlowDrive ? Drive::SLOW_DRIVE_MULTIPLIER : 1.0 );
double br = ( y + x - turn ) * ( isSlowDrive ? Drive::SLOW_DRIVE_MULTIPLIER : 1.0 );
if( isPIDControl ){
flPID->SetSetpoint( fl, fl );
blPID->SetSetpoint( bl, bl );
frPID->SetSetpoint( fr, fr );
brPID->SetSetpoint( br, br );
fl = flPID->GetOutput();
bl = blPID->GetOutput();
fr = frPID->GetOutput();
br = brPID->GetOutput();
//fl = xPID->GetOutput() + yPID->GetOutput() + turnPID->GetOutput() ;
//bl = -xPID->GetOutput() + yPID->GetOutput() + turnPID->GetOutput() ;
//fr = -xPID->GetOutput() + yPID->GetOutput() - turnPID->GetOutput() ;
//br = xPID->GetOutput() + yPID->GetOutput() - turnPID->GetOutput() ;
}
flMotor->Set( fl * motorInverters[0] );
blMotor->Set( bl * motorInverters[1] );
frMotor->Set( fr * motorInverters[2] );
brMotor->Set( br * motorInverters[3] );
}
void Drive::Disable(){
SetPIDControl( false );
flMotor->Set( 0.0 );
blMotor->Set( 0.0 );
frMotor->Set( 0.0 );
brMotor->Set( 0.0 );
}
void Drive::SetMecanumRLStrafe( double r, double l, double strafe ){
driverX = strafe;
driverY = (( r + l ) / 2) * (( r + l ) / 2);
driverTurn = (( l - r ) / 2) * (( l - r ) / 2);
}
void Drive::SetMecanumXYTurn( double x, double y, double turn ){
driverX = x;
driverY = y;
driverTurn = turn;
}
void Drive::SetFieldOriented( bool value ){
isFieldOriented = value;
}
bool Drive::IsFieldOriented(){
return isFieldOriented;
}
void Drive::SetHoldAngle( bool isOn ){
isHoldAngle = isOn;
}
void Drive::SetTargetAngle( double degrees ){
targetAngle = fmod( degrees, 360.0 );
}
void Drive::ResetEncoders(){
flEncoder->Reset();
blEncoder->Reset();
frEncoder->Reset();
brEncoder->Reset();
}
double Drive::GetDistMoved(){
return ( flEncoder->Get() + blEncoder->Get() - frEncoder->Get() - brEncoder->Get() ) / 4;
}
void Drive::ResetGyro( double bias ){
gyroBias = bias;
gyro->Reset();
}
double Drive::GetGyroAngle(){
return gyro->GetAngle() + gyroBias;
}
bool Drive::IsPIDControl(){
return isPIDControl;
}
void Drive::SetPIDControl( bool value ){
isPIDControl = value;
if( isPIDControl ){
flPID->Enable();
blPID->Enable();
frPID->Enable();
brPID->Enable();
xPID->Enable();
yPID->Enable();
turnPID->Enable();
}
else{
flPID->Disable();
blPID->Disable();
frPID->Disable();
brPID->Disable();
xPID->Disable();
yPID->Disable();
turnPID->Disable();
}
}
bool Drive::IsSlowDrive(){
return isSlowDrive;
}
void Drive::SetSlowDrive( bool value ){
isSlowDrive = value;
}
void Drive::SetInvertedMotors( bool fl, bool bl, bool fr, bool br ){
motorInverters[0] = fl ? -1 : 1;
motorInverters[1] = bl ? -1 : 1;
motorInverters[2] = fr ? -1 : 1;
motorInverters[3] = br ? -1 : 1;
}
void Drive::NormalizeMotorSpeeds(){
/*double maxValue = 1.0;
if(fabs( flSpeed ) > maxValue ){
maxValue = fabs( flSpeed );
}
if( fabs( blSpeed ) > maxValue ){
maxValue = fabs( blSpeed );
}
if( fabs( frSpeed ) > maxValue ){
maxValue = fabs( frSpeed );
}
if( fabs( brSpeed ) > maxValue ){
maxValue = fabs( brSpeed );
}
flSpeed = flSpeed / maxValue;
blSpeed = blSpeed / maxValue;
frSpeed = frSpeed / maxValue;
brSpeed = brSpeed / maxValue;
*/
}
<file_sep>/SimpleTemplate/kicker.cpp
#include "kicker.h"
#include <Math.h>
Kicker::Kicker( SpeedController *kicker1_, SpeedController *kicker2_, AnalogChannel *kickerPot_) {
kicker1 = kicker1_;
kicker2 = kicker2_;
//TODO: add GetAdjustedPotValue() method
kickerPot = kickerPot_;
state = Nothing;
kicker1->Set(0.0);
kicker2->Set(0.0);
isKicking = false;
isPullingBack = false;
isSitting = false;
t = new Timer();
t->Start();
}
void Kicker::Actuate() {
if (state == PullingBack) {
kicker1->Set(1.0);
kicker2->Set(1.0);
if (t->Get() >= 0.4) {
t->Reset();
state = Kicking;
}
}else if (state == Kicking) {
kicker1->Set(-1.0);
kicker2->Set(-1.0);
if (kickerPot->GetValue() > (kickerPotVal + 670)) {
state = Retracting;
kicker1->Set(0);
kicker2->Set(0);
t->Reset();
}
}else if (state == Retracting){
kicker1->Set(0.4);
kicker2->Set(0.4);
if (kickerPot->GetValue() < (kickerPotVal + 90)) {
state = Nothing;
kicker1->Set(0);
kicker2->Set(0);
t->Reset();
}
}else if (state == Pull){
kicker1->Set(1);
kicker2->Set(1);
if (kickerPot->GetValue() >= 1) {
kicker1->Set(-0.5);
kicker2->Set(-0.5);
if (kickerPot->GetValue() >= 1) {
kicker1->Set(0);
kicker2->Set(0);
}
}
}else if (state == Raising){
kicker1->Set(1);
kicker2->Set(1);
}else if (state == Nothing && kickerPot->GetValue() > (kickerPotVal + 15)){
kicker1->Set(0.8);
kicker2->Set(0.8);
}
else {
kicker1->Set(0.0);
kicker2->Set(0.0);
}
}
void Kicker::KickBall(){
if (state == Nothing) {
t->Reset();
state = PullingBack;
}
}
void Kicker::KickBallN() {
if (state == Nothing) {
//encoder->Reset();
t->Reset();
state = Kicking;
}
}
void Kicker::PullUp() {
if (state == Nothing) {
state = Pull;
}
}
void Kicker::RaiseLeg() {
if (state == Nothing) {
state = Raising;
}
}
void Kicker::StopRaise() {
if (state == Raising) state = Nothing;
}
void Kicker::Disable() {
kicker1->Set(0);
kicker2->Set(0);
state = Nothing;
}
bool Kicker::State() {
if (state == Nothing) return false;
else return true;
}
void Kicker::KickerPotVal(int x) {
kickerPotVal = x;
}
int Kicker::GetAdjustedPotValue() {
return kickerPot->GetValue() - kickerPotVal;
}
<file_sep>/SimpleTemplate/drive.h
#ifndef DRIVE_H
#define DRIVE_H
#include "WPILib.h"
#include <Math.h>
#include "util/metropidcontroller.h"
class Drive {
public:
Drive( SpeedController *flMotor_, SpeedController *blMotor_, SpeedController *frMotor_, SpeedController *brMotor_,
Encoder *flEncoder_, Encoder *blEncoder_, Encoder *frEncoder_, Encoder *brEncoder_,
Gyro *gyro_ );
~Drive(){};
void Actuate();
void Disable();
void SetMecanumXYTurn( double x, double y, double turn );
void SetMecanumRLStrafe( double leftSide, double rightSide, double strafe );
void SetHoldAngle( bool isOn );
void SetTargetAngle( double degrees );
double GetDistMoved();
void ResetEncoders();
void ResetGyro( double bias = 0.0 );
double GetGyroAngle();
bool IsFieldOriented();
void SetFieldOriented( bool value );
void SetPIDControl( bool value );
bool IsPIDControl();
bool IsSlowDrive();
void SetSlowDrive( bool value );
void SetInvertedMotors( bool fl, bool bl, bool fr, bool br );
static const double PID_P = 0.75;
static const double PID_I = 0.0;
static const double PID_D = 0.1;
static const double XYTURN_PID_P = 0.75;
static const double XYTURN_PID_I = 0.0;
static const double XYTURN_PID_D = 0.1;
static const double VEL_PID_MULTIPLIER = 1600;
static const double ANGLE_P = -1.0/45.0;
static const double AIM_BIAS_INCREMENT = 20.0;
static const double SLOW_DRIVE_MULTIPLIER = 0.4;
Encoder *flEncoder, *blEncoder, *frEncoder, *brEncoder;
//private:
void NormalizeMotorSpeeds();
SpeedController *flMotor, *blMotor, *frMotor, *brMotor;
Gyro *gyro;
MetroPIDController *flPID, *blPID, *frPID, *brPID, *xPID, *yPID, *turnPID;
double driverX, driverY, driverTurn, targetAngle;
int motorInverters[4];
double gyroBias;
bool isPIDControl;
bool isSlowDrive;
bool isHoldAngle;
bool isFieldOriented;
};
#endif
<file_sep>/SimpleTemplate/util/dualrelay.h
#ifndef DUAL_RELAY_H
#define DUAL_RELAY_H
#include "WPILib.h"
class DualRelay {
public:
DualRelay( int forwardPort, int reversePort );
~DualRelay(){};
void Set( Relay::Value value );
private:
Relay *forward;
Relay *reverse;
};
#endif
<file_sep>/SimpleTemplate/pickup.cpp
#include "pickup.h"
#include <Math.h>
Pickup::Pickup( SpeedController *motor_, DualRelay *angleMotor_, DigitalInput *bottomSwitch_, DigitalInput *topSwitch_ ) {
motor = motor_;
angleMotor = angleMotor_;
bottomSwitch = bottomSwitch_;
topSwitch = topSwitch_;
angleMotorBool = Relay::kOff;
motorSpeed = 0.0;
pickupState = Nothing;
angleState = Stopped;
}
void Pickup::Actuate() {
//motor->Set(motorSpeed);
/*if ( !topSwitch->Get() || !bottomSwitch->Get() ){
angleMotor->Set(Relay::kOff);
}else{
angleMotor->Set(angleMotorBool);
}*/
if( pickupState == Pushing ){
motor->Set(1);
}else if( pickupState == Pulling ){
motor->Set(-1);
}else{
motor->Set(0);
}
if(( angleState == Up || pickupState == Kicking ) && topSwitch->Get() ) {
angleMotor->Set(Relay::kReverse);
}else if ( angleState == Down && bottomSwitch->Get() ) {
angleMotor->Set(Relay::kForward);
}else{
angleMotor->Set(Relay::kOff);
angleState = Stopped;
moveAllWay = false;
}
}
void Pickup::Disable() {
motorSpeed = 0.0;
angleMotor->Set(Relay::kOff);
motor->Set(0.0);
angleState = Stopped;
}
void Pickup::RunIntake(double wheelSpeed) {
motorSpeed = wheelSpeed * 0.85;
}
void Pickup::Raise() {
angleMotorBool = Relay::kReverse;
angleState = Up;
moveAllWay = false;
}
void Pickup::Lower() {
angleMotorBool = Relay::kForward;
angleState = Down;
moveAllWay = false;
}
void Pickup::ToTop() {
angleMotorBool = Relay::kReverse;
angleState = Up;
moveAllWay = true;
}
void Pickup::ToBottom() {
angleMotorBool = Relay::kForward;
angleState = Down;
moveAllWay = true;
}
void Pickup::StopAngle() {
angleMotorBool = Relay::kOff;
angleState = Stopped;
}
void Pickup::Intake() {
pickupState = Pulling;
}
void Pickup::Expel() {
pickupState = Pushing;
}
void Pickup::Kick() {
pickupState = Kicking;
moveAllWay = true;
}
void Pickup::StopIntake() {
pickupState = Nothing;
}
bool Pickup::AllWay() {
if ( moveAllWay ) return 1;
else return 0;
}
bool Pickup::isKicking() {
if ( pickupState == Kicking ) return 1;
else return 0;
}
<file_sep>/SimpleTemplate/util/dualrelay.cpp
#include "dualrelay.h"
#include "WPILib.h"
DualRelay::DualRelay( int forwardPort, int reversePort ){
forward = new Relay( forwardPort, Relay::kForwardOnly );
reverse = new Relay( reversePort, Relay::kReverseOnly );
}
void DualRelay::Set( Relay::Value value )
{
if( value == Relay::kForward )
{
forward->Set( Relay::kOn );
reverse->Set( Relay::kOff );
}
else if( value == Relay::kReverse )
{
forward->Set( Relay::kOff );
reverse->Set( Relay::kOn );
}
else if( value == Relay::kOff )
{
forward->Set( Relay::kOff );
reverse->Set( Relay::kOff );
}
}
<file_sep>/SimpleTemplate/util/metropidcontroller.h
#ifndef METRO_PID_CONTROLLER_H
#define METRO_PID_CONTROLLER_H
#include "WPILib.h"
class MetroPIDController {
public:
enum Modes {
PID,
FEED_FORWARD_PID,
TAKE_BACK_HALF_PID,
BANG_BANG
};
MetroPIDController( double p_, double i_, double d_, Modes mode_, bool isIntegratedOutput_ = false, double period_ = 0.05 );
~MetroPIDController(){};
void SetSource( double value );
double GetOutput();
void SetSetpoint( double value );
void SetSetpoint( double value, double ffValue );
void Enable();
void Disable();
bool IsEnabled();
void Reset();
private:
void Init( double p_, double i_, double d_, Modes mode_, bool isIntegratedOutput_, double period_ );
void Run();
static void CallRun( void *controller );
double Limit( double input );
MetroPIDController::Modes mode;
bool isIntegratedOutput;
double p;
double i;
double d;
double period;
bool isEnabled;
double source;
double result;
double output;
double setPoint;
double error;
double prevError;
double totalError;
double feedForwardValue;
Notifier *notifier;
};
#endif
<file_sep>/SimpleTemplate/MyRobot.cpp
#include "WPILib.h"
#include "util/gamepad.h"
#include "util/metropidcontroller.h"
#include "util/dualrelay.h"
#include "drive.h"
#include "kicker.h"
#include "pickup.h"
#include <stdio.h>
#include <Math.h>
class CommandBasedRobot : public IterativeRobot {
private:
typedef enum {Kick, DoubleKick, Forward, NoScript} AutonScript;
AutonScript script;
int step;
Timer *timer, *freshness, *lightTimer;
Talon *flMotor, *blMotor, *frMotor, *brMotor, *kicker1, *kicker2, *pickupMotor;
Servo *kickerHolder;
DualRelay *angleMotor, *LED;
DigitalInput *limitSwitchb, *limitSwitcht, *PiInput;
DigitalOutput *PiAutonSignal;
Encoder *flEncoder, *blEncoder, *frEncoder, *brEncoder, *kickerEncoder;
AnalogChannel *kickerPot;
Gyro *gyro;
GamePad *driverGamePad, *kickerGamePad;
Drive *drive;
Kicker *kicker;
Pickup *pickup;
Kinect *kinect;
Skeleton *skeleton;
DriverStationLCD *ds;
//NetworkTable *table;
int state;
virtual void RobotInit() {
flMotor = new Talon( 1 );
blMotor = new Talon( 2 );
frMotor = new Talon( 3 );
brMotor = new Talon( 4 );
kicker1 = new Talon( 5 );
kicker2 = new Talon( 6 );
pickupMotor = new Talon( 7 );
angleMotor = new DualRelay( 1, 1 );
timer = new Timer();
freshness = new Timer();
limitSwitcht = new DigitalInput( 1 );
limitSwitchb = new DigitalInput( 2 );
PiInput = new DigitalInput( 12 );
flEncoder = new Encoder( 13, 14 );
blEncoder = new Encoder( 5, 6 );
frEncoder = new Encoder( 7, 8 );
brEncoder = new Encoder( 9, 10 );
//kickerEncoder = new Encoder( 11, 12 );
kickerPot = new AnalogChannel(2);
gyro = new Gyro( 1 );
gyro->Reset();
LED = new DualRelay( 2, 2 );
PiAutonSignal = new DigitalOutput( 11 );
skeleton = new Skeleton();
driverGamePad = new GamePad( 1 );
kickerGamePad = new GamePad( 2 );
drive = new Drive( flMotor, blMotor, frMotor, brMotor, flEncoder, blEncoder, frEncoder, brEncoder, gyro );
drive->SetInvertedMotors( false, false, true, true );
kicker = new Kicker( kicker1, kicker2, kickerPot );
pickup = new Pickup( pickupMotor, angleMotor, limitSwitchb, limitSwitcht );
ds = DriverStationLCD::GetInstance();
//table = NetworkTable::GetTable("net");
////net->PutNumber("angle", 0.0);
////net->PutBoolean("hasAngle", 0.0);
script = Kick;
step = 0;
timer->Reset();
timer->Start();
freshness->Reset();
freshness->Start();
}
virtual void AutonomousInit() {
Disable();
step = 0;
timer->Reset();
drive->ResetGyro();
drive->SetTargetAngle( drive->GetGyroAngle() );
drive->SetPIDControl(false);
drive->SetFieldOriented(false);
flEncoder->Reset();
blEncoder->Reset();
frEncoder->Reset();
brEncoder->Reset();
kicker->KickerPotVal(kickerPot->GetValue());
PiAutonSignal->Set(1);
}
void AdvanceStep() {
step++;
timer->Reset();
}
virtual void AutonomousPeriodic() {
if (script == Kick) {
switch (step) {
case 0:
if (kinect->GetSkeleton().GetWristLeft().y > kinect->GetSkeleton().GetShoulderLeft().y || kinect->GetSkeleton().GetWristRight().y > kinect->GetSkeleton().GetShoulderRight().y || timer->Get() >= 6.0) AdvanceStep();
break;
case 1:
drive->SetMecanumXYTurn(0.0, 2.0/3.0, 0.0);
if (timer->Get() >= 0.7) AdvanceStep();
break;
/*case 0:
drive->SetMecanumXYTurn(0.0, 2.0/3.0, 0.0);
PiAutonSignal->Set(1);
break;*/
/*case 1:
drive->SetMecanumXYTurn(0.0, 0.0, 0.0);
break;*/
case 2:
drive->SetPIDControl(false);
drive->SetMecanumXYTurn(0.0, 0.0, 0.0);
kicker->KickBallN();
if (kicker->State()) AdvanceStep();
break;
case 3:
//PiAutonSignal->Set(0);
break;
}
//drive->SetPIDControl( true );
}else if (script == DoubleKick) {
switch (step) {
case 0:
kicker->KickBallN();
if (timer->Get() >= 1) AdvanceStep();
break;
case 1:
drive->SetMecanumXYTurn(0.0, 2.0/3.0, 0.0);
pickup->RunIntake(-1);
if (timer->Get() >= 0.5) AdvanceStep();
break;
case 2:
drive->SetMecanumXYTurn(0.0, 0.0, 0.0);
pickup->Lower();
if (timer->Get() >= 0.5) AdvanceStep();
break;
case 3:
pickup->Disable();
kicker->KickBallN();
if (timer->Get() >= 2.4) AdvanceStep();
break;
case 4:
break;
}
//drive->SetPIDControl( true );
}else if (script == Forward) {
switch (step) {
case 0:
drive->SetMecanumXYTurn(0.0, 2.0/3.0, 0.0);
if (timer->Get() >= 1.5) AdvanceStep();
break;
case 1:
drive->SetMecanumXYTurn(0.0, 0.0, 0.0);
break;
}
//drive->SetPIDControl( true );
}
Actuate();
PrintToDS();
}
virtual void TeleopInit() {
/*drive->SetPIDControl(false);
drive->SetFieldOriented(true);
flEncoder->Reset();
blEncoder->Reset();
frEncoder->Reset();
brEncoder->Reset();
lightTimer->Start();*/
//kicker->KickerPotVal(kickerPot->GetValue());
}
virtual void TeleopPeriodic() {
UpdateOI();
/*
* Reset Gyro
* A: Press to reset gyro
*/
if( driverGamePad->GetButton( GamePad::A ) ){
drive->ResetGyro();
}
/*
* Slow Drive
* LB: Hold to toggle ON, Release to toggle OFF
*/
drive->SetSlowDrive( driverGamePad->GetButton( GamePad::LB ) );
/*
* Field Oriented
* START: Press to toggle ON
* BACK: Press to toggle OFF
*/
drive->SetFieldOriented( driverGamePad->GetButtonDown( GamePad::START ) ? true : ( driverGamePad->GetButtonDown( GamePad::BACK ) ? false : drive->IsFieldOriented() ) );
/*
* PID Control
* X: Press to toggle ON
* Y: Press to toggle OFF
*/
drive->SetPIDControl( driverGamePad->GetButtonDown( GamePad::X ) ? true : ( driverGamePad->GetButtonDown( GamePad::Y ) ? false : drive->IsPIDControl() ) );
/*
* Mecanum Drive
* LEFT_X_AXIS: Strafe Left/Right
* LEFT_Y_AXIS: Forward/Reverse
* RIGHT_X_AXIS: Turn
*/
drive->SetMecanumXYTurn( driverGamePad->GetAxis( GamePad::LEFT_X ), driverGamePad->GetAxis( GamePad::LEFT_Y ), driverGamePad->GetAxis( GamePad::RIGHT_X ) );
//drive->SetMecanumRLStrafe( driverGamePad->GetAxis( GamePad::LEFT_Y ), driverGamePad->GetAxis( GamePad::RIGHT_Y ), 0);
/*
* Hold Angle
* RIGHT_JS_BUTTON: Hold to hold current angle
* B: Hold to hold vision target angle
*/
if( driverGamePad->GetButtonDown( GamePad::RIGHT_JS ) ){
drive->SetTargetAngle( drive->GetGyroAngle() );
}
if( driverGamePad->GetButton/*Down*/( GamePad::B ) ){
drive->SetTargetAngle( HasTarget() ? GetAbsoluteAngle() : drive->GetGyroAngle() );
}
drive->SetHoldAngle( driverGamePad->GetButton( GamePad::RIGHT_JS ) || driverGamePad->GetButton( GamePad::B ) || driverGamePad->GetAxis(GamePad::DPAD_X) != 0.0 );
if(driverGamePad->GetDPadLeftDown()){
drive->SetTargetAngle( drive->GetGyroAngle() - Drive::AIM_BIAS_INCREMENT);
}
if(driverGamePad->GetDPadRightDown()){
drive->SetTargetAngle( drive->GetGyroAngle() + Drive::AIM_BIAS_INCREMENT);
}
/*
* Kick Ball
* A: Pull back kicker and kick ball
* X: Raise leg
*/
if( kickerGamePad->GetButton( GamePad::A )) {
kicker->KickBallN();
}
/*if( kickerGamePad->GetButton( GamePad::X )) {
kicker->RaiseLeg();
}else if ( !kickerGamePad->GetButton( GamePad::X )){
kicker->StopRaise();
}*/
//pickup->ArmAngle( kickerGamePad->GetAxis( GamePad::LEFT_Y ));
//pickup->RunIntake( -kickerGamePad->GetAxis( GamePad::LEFT_Y ));
/*
* Run intake
* LB: Take in ball
* RB: Spit out ball
*/
if ( kickerGamePad->GetButton( GamePad::LB )) {
pickup->Intake();
}else if ( kickerGamePad->GetButton( GamePad::RB )){
pickup->Expel();
}else /*if ( kickerGamePad->GetButton( GamePad::START ))*/ {
pickup->StopIntake();
}
/*
* Raise Pickup Mechanism
* LEFT_Y UP: Raise arm
* LEFT_Y DOWN: Lower arm
* Y: Raise arm to top
* B: Lower arm to bottom
*/
if( kickerGamePad->GetAxis( GamePad::LEFT_Y ) > 0.0 ) {
pickup->Raise();
}else if( kickerGamePad->GetAxis( GamePad::LEFT_Y ) < 0.0 ) {
pickup->Lower();
}else if( kickerGamePad->GetAxis( GamePad::LEFT_Y ) == 0.0 && !pickup->AllWay()){
pickup->StopAngle();
}
if( kickerGamePad->GetButton( GamePad::Y )) {
pickup->ToTop();
}
if( kickerGamePad->GetButton( GamePad::B )) {
pickup->ToBottom();
}
if( kickerGamePad->GetButton( GamePad::RIGHT_JS )) {
pickup->Kick();
}
if( pickup->isKicking() && !limitSwitcht->Get()) {
kicker->KickBallN();
}
if( kickerGamePad->GetButton( GamePad::RIGHT_JS ) || driverGamePad->GetButton( GamePad::RB )) {
if (lightTimer->Get() >= 0.25) {
LED->Set(Relay::kOff);
lightTimer->Reset();
}else{
LED->Set(Relay::kForward);
}
}else if(kicker->State()){
LED->Set(Relay::kOff);
}else{
LED->Set(Relay::kForward);
}
if( kickerGamePad->GetButton( GamePad::X )) kicker->KickerPotVal(kickerPot->GetValue());
if( kickerGamePad->GetAxis( GamePad::DPAD_X ) != 0) PiAutonSignal->Set(1);
else PiAutonSignal->Set(0);
Actuate();
PrintToDS();
}
virtual void DisabledInit() {
Disable();
}
virtual void DisabledPeriodic() {
UpdateOI();
if (driverGamePad->GetButton( GamePad::A )) {
script = Kick;
}else if (driverGamePad->GetButton( GamePad::B )) {
script = DoubleKick;
}else if (driverGamePad->GetButton( GamePad::X )) {
script = Forward;
}
drive->SetPIDControl( driverGamePad->GetButtonDown( GamePad::X ) ? true : ( driverGamePad->GetButtonDown( GamePad::Y ) ? false : drive->IsPIDControl() ) );
drive->SetFieldOriented( driverGamePad->GetButtonDown( GamePad::START ) ? true : ( driverGamePad->GetButtonDown( GamePad::BACK ) ? false : drive->IsFieldOriented() ) );
if( kickerGamePad->GetButton( GamePad::X )) kicker->KickerPotVal(kickerPot->GetValue());
PrintToDS();
}
void Actuate(){
drive->Actuate();
kicker->Actuate();
pickup->Actuate();
}
void Disable(){
drive->Disable();
kicker->Disable();
pickup->Disable();
}
void UpdateOI(){
driverGamePad->Update();
kickerGamePad->Update();
//IsFreshTarget();
}
void PrintToDS(){
ds->Clear();
ds->Printf(DriverStationLCD::kUser_Line1, 1, "Auto: %s", script == Kick ? "Single Kick" : ( script == DoubleKick ? "DoubleKick" : ( script == Forward ? "Forward" :( script == NoScript ? "None" : "YOU BROKE IT" ) ) ) );
ds->Printf(DriverStationLCD::kUser_Line2, 1, "Dr: %s%s %f", drive->IsPIDControl() ? "PID, " : "", drive->IsFieldOriented() ? "FO, " : "", drive->gyro->GetAngle() );
ds->Printf(DriverStationLCD::kUser_Line3, 1, "Vi: %s, Fresh: %f", HasTarget() ? "Y" : "N", freshness->Get() );
ds->Printf(DriverStationLCD::kUser_Line4, 1, "%d", kickerPot->GetValue() );
ds->Printf(DriverStationLCD::kUser_Line5, 1, "%d : %d : %d : %d", flEncoder->Get(), blEncoder->Get(), frEncoder->Get(), brEncoder->Get() );
//ds->Printf(DriverStationLCD::kUser_Line6, 1, "%d, %d, %f", PiInput->Get(), step, timer->Get() );
ds->Printf(DriverStationLCD::kUser_Line6, 1, "%f", ((kinect->GetSkeleton().GetWristLeft().y - kinect->GetSkeleton().GetShoulderLeft().y)) );
ds->UpdateLCD();
}
double GetAbsoluteAngle() {
return /*table->GetNumber("angle", 0.0) +*/ drive->GetGyroAngle();
}
double GetRelativeAngle() {
return 0.0;//table->GetNumber("angle", 0.0);
}
bool HasTarget(){
return false;//table->GetBoolean("hasTarget", false);
}
bool IsFreshTarget() {
bool isFresh = false;//table->GetBoolean("isFresh", false);
if(isFresh) {
freshness->Reset();
}
//table->PutBoolean("isFresh", false);
return isFresh;
}
double AngleDiff( double angle1, double angle2 ){
return fmod(angle1 - angle2 + 180.0, 360.0) - 180.0;
}
};
START_ROBOT_CLASS(CommandBasedRobot);
<file_sep>/SimpleTemplate/util/metropidcontroller.cpp
#include "metropidcontroller.h"
MetroPIDController::MetroPIDController( double p_, double i_, double d_, Modes mode_, bool isIntegratedOutput_, double period_ ){
p = p_;
i = i_;
d = d_;
mode = mode_;
isIntegratedOutput = isIntegratedOutput_;
period = period_;
notifier = new Notifier( MetroPIDController::CallRun , this );
source = 0.0;
result = 0.0;
output = 0.0;
setPoint = 0.0;
error = 0.0;
prevError = 0.0;
totalError = 0.0;
feedForwardValue = 0.0;
isEnabled = false;
notifier->StartPeriodic( period );
}
void MetroPIDController::CallRun( void *controller ){
MetroPIDController *control = (MetroPIDController*) controller;
control->Run();
}
void MetroPIDController::Run(){
Synchronized s(semaphore);
if( isEnabled ){
error = setPoint - source;
totalError += error;
if ( mode == TAKE_BACK_HALF_PID && ( error * prevError < 0 || error == 0 ) ) {
feedForwardValue = ( feedForwardValue + output ) / 2;
}
result = ( error * p ) + ( totalError * i ) + ( (error-prevError) * d ) + ( isIntegratedOutput ? result : 0.0 );
result = Limit( result );
output = result;
if ( mode == FEED_FORWARD_PID || mode == TAKE_BACK_HALF_PID ) {
output += feedForwardValue;
}
if( mode == BANG_BANG ){
output = ( source < setPoint ? 1.0 : 0.0 );
}
prevError = error;
}
}
void MetroPIDController::SetSource( double value ){
Synchronized s(semaphore);
source = value;
}
double MetroPIDController::GetOutput(){
Synchronized s(semaphore);
return output;
}
void MetroPIDController::SetSetpoint( double value ){
Synchronized s(semaphore);
setPoint = value;
}
void MetroPIDController::SetSetpoint( double value, double ffValue ){
Synchronized s(semaphore);
setPoint = value;
feedForwardValue = ffValue;
}
bool MetroPIDController::IsEnabled(){
Synchronized s(semaphore);
return isEnabled;
}
void MetroPIDController::Enable(){
Synchronized s(semaphore);
isEnabled = true;
}
void MetroPIDController::Disable(){
Synchronized s(semaphore);
output = 0.0;
isEnabled = false;
Reset();
}
double MetroPIDController::Limit( double input ){
if( input > 1.0 ){
return 1.0;
}
if( input < -1.0 ){
return -1.0;
}
return input;
}
void MetroPIDController::Reset(){
Synchronized s(semaphore);
output = 0.0;
prevError = 0.0;
totalError = 0.0;
setPoint = 0.0;
isEnabled = false;
}
| d576af5b765024d6184291107ef75dc863604789 | [
"C++"
] | 13 | C++ | frc3324/Metrobots2014 | 8c7a54779f7a8aa0211ffd938d38f581454a8e22 | b4b1aaa71da9be50236db5fcd417581c1e1cd3e3 | |
refs/heads/master | <repo_name>ppp225/go-common<file_sep>/encoding.go
package common
import (
"bytes"
"encoding/gob"
"fmt"
)
// ToGob - go binary encoder
func ToGob(m interface{}) []byte {
b := bytes.Buffer{}
e := gob.NewEncoder(&b)
err := e.Encode(m)
if err != nil {
fmt.Println(`failed gob Encode`, err)
}
return b.Bytes()
}
// FromGob - go binary decoder
func FromGob(by []byte, m interface{}) {
b := bytes.Buffer{}
b.Write(by)
d := gob.NewDecoder(&b)
err := d.Decode(m)
if err != nil {
fmt.Println(`failed gob Decode`, err)
}
}
<file_sep>/common.go
package common
import (
"encoding/json"
"fmt"
"log"
"regexp"
"runtime"
"time"
)
// Check check for error and panics, if not nil
func Check(e error) {
if e != nil {
panic(e)
}
}
// Log writes to stdout if shoudLog flag is true
func Log(shoudLog bool, format string, a ...interface{}) {
if shoudLog {
fmt.Printf(format, a...)
}
}
// ErrorTraced mimics panic() output.
//
// Usage: return ErrorTraced(err, inputAgrs...)
func ErrorTraced(prev error, args ...string) error {
pc := make([]uintptr, 15)
n := runtime.Callers(2, pc)
frames := runtime.CallersFrames(pc[:n])
frame, _ := frames.Next()
return fmt.Errorf("%s(%v)\n\t%s:%d\n%s", frame.Function, args, frame.File, frame.Line, prev)
//log.Printf("%s:%d %s\n", frame.File, frame.Line, frame.Function)
}
// Trace logs current code line trace
func Trace() {
pc := make([]uintptr, 15)
n := runtime.Callers(2, pc)
frames := runtime.CallersFrames(pc[:n])
frame, _ := frames.Next()
log.Printf("%s,:%d %s\n", frame.File, frame.Line, frame.Function)
}
// CheckEmail checks e-mail format correctness
func CheckEmail(email string) (ok bool) {
reEmail := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
return reEmail.MatchString(email)
}
// ElapsedMs returns elapsed time between now and arg as ms
func ElapsedMs(start time.Time) float64 {
return (float64)(time.Now().Sub(start).Nanoseconds()) / 1e6
}
// PrettyPrint prints objects prettier
func PrettyPrint(v interface{}) (err error) {
b, err := json.MarshalIndent(v, "", " ")
if err == nil {
fmt.Println(string(b))
}
return
}
// TODO: add retry function https://stackoverflow.com/questions/47606761/repeat-code-if-an-error-occured
<file_sep>/timeRemainingTimer.go
package common
import (
"fmt"
"log"
"time"
)
// TimeRemainingTimer used to track progress
type TimeRemainingTimer struct {
start int64
end int64
startTime int64
}
// CreateTimeRemainingTimer creates timer, that will interpolate remaining time based on some start & end indexes
func CreateTimeRemainingTimer(start, end int64) *TimeRemainingTimer {
return &TimeRemainingTimer{
start,
end,
time.Now().UnixNano(),
}
}
// Start starts the timer
func (v *TimeRemainingTimer) Start() {
v.startTime = time.Now().UnixNano()
}
// Restart restarts the timer with new start & end values
func (v *TimeRemainingTimer) Restart(start, end int64) {
v.start = start
v.end = end
v.startTime = time.Now().UnixNano()
}
// Get returns %done & remainingTime for current index
func (v *TimeRemainingTimer) Get(current int64) (percentageDone float64, timeRemaining time.Duration) {
now := time.Now().UnixNano()
elapsed := now - v.startTime
done := current - v.start
total := v.end - v.start
resultPerc := float64(done) / float64(total)
remainingTime := int64(0)
if resultPerc != 0 {
remainingTime = int64(float64(elapsed)/resultPerc - float64(elapsed))
}
resultRemainingTime := time.Duration(remainingTime)
return resultPerc, resultRemainingTime
}
// Getf returns formatted string of %done & remaining time
func (v *TimeRemainingTimer) Getf(current int64) string {
p, r := v.Get(current)
return fmt.Sprintf("Perc: %5.2f | Rem: %s", p*100, r.Round(time.Millisecond*10))
}
// Printr fmt.Printf's formatted %done & remaining time
func (v *TimeRemainingTimer) Printr(current int64) {
p, r := v.Get(current)
fmt.Printf("\rPerc: %5.2f | Rem: %s | ", p*100, r.Round(time.Millisecond*10))
}
/////////////////////////////////////////////////////////////////////////
// TimeTrack logs elapsed time for task
func TimeTrack(start time.Time, name string) {
elapsed := time.Since(start)
log.Printf("%s took %s", name, elapsed.Round(time.Millisecond*10))
}
| 8cedcf717498823c00f480685563acf411b6fd67 | [
"Go"
] | 3 | Go | ppp225/go-common | d58892d2149799c3fb5c7e4ba6eb28ecba9d57c4 | e031664ce2adbfa268d95912b9e0268b7f8515c4 | |
refs/heads/main | <repo_name>Canthesecond/Data_Cleaning<file_sep>/Data Cleaning.sql
-- Standardize the Date Format
Select SaleDate,CONVERT(Date,SaleDate) from CovidAnalysis.dbo.NashvilleHousing
Update NashvilleHousing
SET SaleDate = CONVERT(Date,SaleDate)
from CovidAnalysis.dbo.NashvilleHousing
use CovidAnalysis
Alter table NashvilleHousing
Add SaleDateConverted Date
Update NashvilleHousing
SET SaleDateConverted = CONVERT(Date,SaleDate)
from CovidAnalysis.dbo.NashvilleHousing
--Populate Property Adress data
Select a.ParcelID,b.ParcelID,a.PropertyAddress,b.PropertyAddress , ISNULL(a.PropertyAddress,b.PropertyAddress)
from CovidAnalysis.dbo.NashvilleHousing a
JOIN CovidAnalysis.dbo.NashvilleHousing b
ON a.ParcelID = b.ParcelID
and a.[UniqueID ] <> b.[UniqueID ]
Where a.PropertyAddress is null
Update a
SET PropertyAddress = ISNULL(a.PropertyAddress,b.PropertyAddress)
from CovidAnalysis.dbo.NashvilleHousing a
JOIN CovidAnalysis.dbo.NashvilleHousing b
ON a.ParcelID = b.ParcelID
and a.[UniqueID ] <> b.[UniqueID ]
Where a.PropertyAddress is null
--Breaking Address into individual columns
SELECT
SUBSTRING(propertyaddress,CHARINDEX(',',PROPERTYADDRESS)+1, LEN(propertyaddress)) AS ADDRESS,
SUBSTRING(propertyaddress,1,CHARINDEX(',',PROPERTYADDRESS)-1) as address
from CovidAnalysis.dbo.NashvilleHousing
use covidanalysis
Alter table NashvilleHousing
Add PropertSplitAddress Nvarchar(255);
Update NashvilleHousing
SET PropertSplitAddress = SUBSTRING(propertyaddress,CHARINDEX(',',PROPERTYADDRESS)+1, LEN(propertyaddress))
from CovidAnalysis.dbo.NashvilleHousing
USE covidanalysis
Alter table NashvilleHousing
Add PropertSplitCity Nvarchar(255);
Update NashvilleHousing
SET PropertSplitCity = SUBSTRING(propertyaddress,1,CHARINDEX(',',PROPERTYADDRESS)-1)
from CovidAnalysis.dbo.NashvilleHousing
SELECT
PARSENAME(REPLACE(OwnerAddress,',','.'),1),
PARSENAME(REPLACE(OwnerAddress,',','.'),2),
PARSENAME(REPLACE(OwnerAddress,',','.'),3)
from CovidAnalysis.dbo.NashvilleHousing
SELECT
*
From CovidAnalysis.dbo.NashvilleHousing
SELECT
SUBSTRING(OwnerAddress,CHARINDEX(',',OwnerAddress)+1, LEN(OwnerAddress)) AS ADDRESS,
SUBSTRING(OwnerAddress,1,CHARINDEX(',',OwnerAddress)-1) as address
From CovidAnalysis.dbo.NashvilleHousing
Use covidanalysis
Alter table NashvilleHousing
Add OwnerSplitAddress Nvarchar(255);
Update NashvilleHousing
SET OwnerSplitAddress = PARSENAME(REPLACE(OwnerAddress,',','.'),3)
from CovidAnalysis.dbo.NashvilleHousing
USE covidanalysis
Alter table NashvilleHousing
Add OwnerSplitCity Nvarchar(255);
Update NashvilleHousing
SET OwnerSplitCity = PARSENAME(REPLACE(OwnerAddress,',','.'),2)
From CovidAnalysis.dbo.NashvilleHousing
USE covidanalysis
Alter table NashvilleHousing
Add OwnerSplitZip Nvarchar(255);
Update NashvilleHousing
SET OwnerSplitZip = PARSENAME(REPLACE(OwnerAddress,',','.'),1)
From CovidAnalysis.dbo.NashvilleHousing
--
--Change Y and N to Yes and No in "Sold as Vacant" field
Select distinct(SoldAsVacant),count(SoldAsVacant)
From CovidAnalysis.dbo.NashvilleHousing
Group by SoldAsVacant
Order by 2
Select soldasvacant,
Case
When soldasvacant = 'y' then 'Yes'
When soldasvacant = 'n' then 'No'
Else SoldAsVacant
End
From CovidAnalysis.dbo.NashvilleHousing
Use CovidAnalysis
Update NashvilleHousing
Set SoldAsVacant = case
When soldasvacant = 'y' then 'Yes'
When soldasvacant = 'n' then 'No'
Else SoldAsVacant
End
--Remove duplicates
WITH RowNumCTE AS(
select *,
ROW_NUMBER() Over(
Partition by parcelid,
propertyaddress,
saledate,
saleprice,
legalreference
order by
uniqueid
)row_num
From CovidAnalysis.dbo.NashvilleHousing
)
select * From RowNumCTE
where row_num > 1
order by PropertyAddress
select *
From CovidAnalysis.dbo.NashvilleHousing
--Delete Unused Columns
select *
From CovidAnalysis.dbo.NashvilleHousing
alter table CovidAnalysis.dbo.NashvilleHousing
drop column owneraddress, taxdistrict,propertyaddress
alter table CovidAnalysis.dbo.NashvilleHousing
drop column saledate | 9d472a7238e98dfa2b879bacd19c0a708b9a777f | [
"SQL"
] | 1 | SQL | Canthesecond/Data_Cleaning | 1f917ef7229218d5e8f78e01e301439459fb44ca | 8c92c1dadd2b47eeb9ef12303a376983d8ba1d62 | |
refs/heads/master | <repo_name>jvalvert/poc<file_sep>/zmq-nodejs/zeromqclient.js
// Zeromq client that generates all the transactions
// use zmq to connect to server
var zmq = require('zmq')
, requester = zmq.socket('req');
requester.connect('tcp://localhost:38000');
var replyNbr = 0;
requester.on('message', function(msg) {
console.log('got reply', replyNbr, msg.toString());
replyNbr += 1;
});
for (var i = 0; i < 100; ++i) {
var mockTransaction= {title: 'Low Priority - Transaction # '+i
, from: 'btc china'
, to: 'oki coin)'
, amount: '100'
};
var msgTransaction = JSON.stringify(mockTransaction);
requester.send(msgTransaction);
}
<file_sep>/gonatpmp/client.go
import natpmp "github.com/jackpal/go-nat-pmp"
client := natpmp.NewClient(gatewayIP)
response, err := client.GetExternalAddress()
if err != nil {
return
}
print("External IP address:", response.ExternalIPAddress)
<file_sep>/zmq-nodejs/zeromq_broker_rr.js
// Request and Reply broker for the job injector
var zmq = require('zmq')
, router = zmq.socket('router')
, dealer = zmq.socket('dealer');
router.bindSync('tcp://*:38000');
dealer.bindSync('tcp://*:38001');
router.on('message', function() {
// Note that separate message parts come as function arguments.
var args = Array.apply(null, arguments);
// Pass array of strings/buffers to send multipart messages.
dealer.send(args);
});
dealer.on('message', function() {
var args = Array.apply(null, arguments);
router.send(args);
});
<file_sep>/zmq-c/zmq/main.cpp
//simple req rep server / client
//first p2p propossal
#include <zmq/zmq.h>
#include <zmq/zmq.hpp>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <iostream>
#include <msgpack/msgpack.hpp>
#include <vector>
using namespace std;
int zmq_server()
{
std::cout << "Zmq server listening at 5555..\n";
// Socket to talk to clients
void *context = zmq_ctx_new ();
void *responder = zmq_socket (context, ZMQ_REP);
int rc = zmq_bind (responder, "tcp://*:380001");
assert (rc == 0);
while (1) {
char buffer[500];
zmq_recv (responder, buffer, 500, 0);
msgpack::unpacked msg; // includes memory pool and deserialized object
msgpack::unpack(msg, buffer, 500);
msgpack::object obj = msg.get();
std::cout <<"Received: "<< obj << std::endl;
sleep (1); // Do some 'work'
zmq_send (responder, "Message received..", 20, 0);
}
return 0;
}
int zmq_client ()
{
std::cout << "Zmq Client...\n";
// Prepare our context and socket
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_REQ);
std::cout << "Connecting to server tcp://localhost:38001…" << std::endl;
socket.connect ("tcp://localhost:38001");
// Do 10 requests, waiting each time for a response
for (int request_nbr = 0; request_nbr != 10; request_nbr++) {
zmq::message_t request (500);
std::string other="y";
std::vector<std::string> target;
std::string message;
while (other.compare("y")==0)
{
cout << "Input a message to be serialized :" ;
getline(cin,message);
target.push_back(message);
cout << "Add other attribute ? [s/n] selected: "<< other;
getline(cin,other);
}
// serialize the message using MSGPACK
msgpack::sbuffer sbuf; // simple buffer
msgpack::pack(&sbuf, target);
msgpack::unpacked msg; // includes memory pool and deserialized object
msgpack::unpack(msg, sbuf.data(), sbuf.size());
msgpack::object obj = msg.get();
memcpy ((void *) request.data (), sbuf.data(), sbuf.size());
std::cout << "Sending message " << request_nbr << " of 10…" << std::endl;
socket.send (request);
// Get the reply.
zmq::message_t reply;
socket.recv (&reply);
std::cout << "Response from server # " << request_nbr << " ";
printf("%s\n",&reply);
}
return 0;
}
int zmq_demo_simple_rep_req(int argc, char *argv[])
{
if (argc > 0)
{
std::string arg(argv[1]);
if (arg.compare("CLIENT")==0)
return zmq_client();
else
return zmq_server();
}
std::cout << "Error: You need to add a parameter (CLIENT or SERVER)";
}
int main(int argc, char* argv[])
{
// demo simple rep req
return zmq_demo_simple_rep_req(argc,argv);
return 0;
}
<file_sep>/kue/consumer_error.js
var kue = require('kue')
, jobs = kue.createQueue();
jobs.process('transaction',10,function(job,done)
{
console.log('Transaction with errors');
console.log(job.data);
setTimeout(function()
{
try
{
throw new Error('Error with the transaction, not processed');
done();
}
catch(err)
{
done(err);
}
}, 3000);
});<file_sep>/zmq-nodejs/kueJobInjector.js
// Zero MQ Backend && Kue Injector
var zmq = require('zmq')
, responder = zmq.socket('rep');
// Create the queue
var kue = require('kue')
, jobs = kue.createQueue();
kue.app.listen(3000);
responder.connect('tcp://localhost:38001'); // connect to the dealer
responder.on('message', function(msg) {
console.log('received transaction:', msg.toString());
//var msg_json = JSON.stringify(msg);
// get the transaction from zmq and queue it into kue
var job = jobs
.create('transaction',JSON.parse(msg))
.save();
job.on('complete',function()
{
console.log('transaction completed!!')
});
job.on('failed',function()
{
console.log('transaction failed!!')
});
setTimeout(function() {
responder.send("Transaction Processed.");
}, 1000);
});
<file_sep>/nodejsRunner/nodejsrunner/nodejsrunner/mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
sleep(3);
ui->webView->load(QUrl("http://localhost:1337"));
}
void MainWindow::SL_Quitting()
{
std::cout << "closing process... " << sails.processId();
// the child process is always the process id plus one
// TODO: test on linux
// TODO: implement on windows
QString pid = QString::number(sails.processId()+1,10);
QProcess finish;
QString kill ="Kill "+ pid;
qDebug() << kill;
finish.start(kill);
finish.waitForFinished(3000);
finish.close();
sails.close();
}
MainWindow::~MainWindow()
{
delete ui;
}
<file_sep>/gloox-lib/gloox/gloox.cpp
#include "gloox.h"
Gloox::Gloox()
{
}
<file_sep>/zmq-multithread/zmq-multithread/main.cpp
#include <iostream>
#include <zmq.h>
#include <zmq.hpp>
#include <QApplication>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}
<file_sep>/kue/producer_delayed.js
var kue = require('kue')
, jobs = kue.createQueue();
var sequence = 0;
setInterval(
function()
{
sequence += 1;
(function(sequence)
{
var job = jobs.create('transaction',
{
title: 'Low Priority - Transaction number #' + sequence
, from: 'btc china'
, to: 'oki coin)'
, amount: '100'
}).attempts(2).priority('low').delay(5).save();
job.on('complete',function()
{
console.log('transaction low priority '+ sequence +' completed!!')
});
job.on('failed',function()
{
console.log('transaction low priority' + sequence + ' failed!!')
});
}(sequence));
}
, 1000);<file_sep>/webenginepatch/out/Makefile
#############################################################################
# Makefile for building: qtwebengine
# Generated by qmake (3.0) (Qt 5.4.0)
# Project: /Users/Rafa/pocs/webenginepatch/qtwebengine/qtwebengine.pro
# Template: subdirs
# Command: /Users/Rafa/Qt/5.4/clang_64/bin/qmake -spec macx-clang CONFIG+=debug CONFIG+=x86_64 CONFIG+=declarative_debug CONFIG+=qml_debug -o Makefile /Users/Rafa/pocs/webenginepatch/qtwebengine/qtwebengine.pro
#############################################################################
MAKEFILE = Makefile
first: make_first
QMAKE = /Users/Rafa/Qt/5.4/clang_64/bin/qmake
DEL_FILE = rm -f
CHK_DIR_EXISTS= test -d
MKDIR = mkdir -p
COPY = cp -f
COPY_FILE = cp -f
COPY_DIR = cp -f -R
INSTALL_FILE = $(COPY_FILE)
INSTALL_PROGRAM = $(COPY_FILE)
INSTALL_DIR = $(COPY_DIR)
DEL_FILE = rm -f
SYMLINK = ln -f -s
DEL_DIR = rmdir
MOVE = mv -f
TAR = tar -cf
COMPRESS = gzip -9f
DISTNAME = qtwebengine1.0.0
DISTDIR = /Users/Rafa/pocs/webenginepatch/qtwebengine/.obj/qtwebengine1.0.0
SUBTARGETS =
Makefile: /Users/Rafa/pocs/webenginepatch/qtwebengine/qtwebengine.pro /Users/Rafa/pocs/webenginepatch/qtwebengine/.qmake.conf .qmake.cache /Users/Rafa/Qt/5.4/clang_64/mkspecs/macx-clang/qmake.conf /Users/Rafa/Qt/5.4/clang_64/mkspecs/features/spec_pre.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/qdevice.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/device_config.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/shell-unix.conf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/unix.conf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/mac.conf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/macx.conf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/gcc-base.conf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/gcc-base-mac.conf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/clang.conf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/clang-mac.conf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/qconfig.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_bluetooth.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_bluetooth_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_bootstrap_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_clucene_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_concurrent.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_concurrent_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_core.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_core_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_dbus.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_dbus_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_declarative.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_declarative_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_designer.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_designer_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_designercomponents_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_enginio.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_enginio_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_gui.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_gui_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_help.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_help_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_location.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_location_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_macextras.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_macextras_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimedia.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimedia_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimediawidgets.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimediawidgets_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_network.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_network_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_nfc.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_nfc_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_opengl.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_opengl_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_openglextensions.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_openglextensions_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_platformsupport_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_positioning.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_positioning_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_printsupport.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_printsupport_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_qml.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_qml_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmldevtools_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmltest.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmltest_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_qtmultimediaquicktools_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_quick.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_quick_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickparticles_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickwidgets.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickwidgets_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_script.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_script_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_scripttools.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_scripttools_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_sensors.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_sensors_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_serialport.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_serialport_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_sql.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_sql_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_svg.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_svg_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_testlib.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_testlib_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_uitools.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_uitools_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webchannel.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webchannel_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webengine.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webengine_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginecore.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginecore_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginewidgets.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginewidgets_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkit.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkit_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkitwidgets.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkitwidgets_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_websockets.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_websockets_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webview.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webview_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_widgets.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_widgets_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_xml.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_xml_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_xmlpatterns.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_xmlpatterns_private.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qt_functions.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qt_config.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/macx-clang/qmake.conf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/spec_post.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/qmodule.pri \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qt_build_config.prf \
/Users/Rafa/pocs/webenginepatch/qtwebengine/.qmake.conf \
/Users/Rafa/pocs/webenginepatch/qtwebengine/tools/qmake/mkspecs/features/functions.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/exclusive_builds.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/default_pre.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/mac/default_pre.prf \
/Users/Rafa/pocs/webenginepatch/qtwebengine/tools/qmake/mkspecs/features/default_pre.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qt_parts.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/resolve_config.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/default_post.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/mac/sdk.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/mac/default_post.prf \
/Users/Rafa/pocs/webenginepatch/qtwebengine/tools/qmake/mkspecs/features/default_post.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/mac/objective_c.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qml_debug.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/declarative_debug.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qt_example_installs.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/exceptions_off.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qt_docs_targets.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/precompile_header.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/unix/largefile.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/warn_on.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/mac/rez.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/testcase_targets.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/yacc.prf \
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/lex.prf \
/Users/Rafa/pocs/webenginepatch/qtwebengine/qtwebengine.pro
$(QMAKE) -spec macx-clang CONFIG+=debug CONFIG+=x86_64 CONFIG+=declarative_debug CONFIG+=qml_debug -o Makefile /Users/Rafa/pocs/webenginepatch/qtwebengine/qtwebengine.pro
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/spec_pre.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/qdevice.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/device_config.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/shell-unix.conf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/unix.conf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/mac.conf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/macx.conf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/gcc-base.conf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/gcc-base-mac.conf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/clang.conf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/common/clang-mac.conf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/qconfig.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_bluetooth.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_bluetooth_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_bootstrap_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_clucene_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_concurrent.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_concurrent_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_core.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_core_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_dbus.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_dbus_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_declarative.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_declarative_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_designer.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_designer_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_designercomponents_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_enginio.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_enginio_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_gui.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_gui_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_help.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_help_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_location.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_location_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_macextras.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_macextras_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimedia.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimedia_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimediawidgets.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimediawidgets_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_network.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_network_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_nfc.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_nfc_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_opengl.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_opengl_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_openglextensions.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_openglextensions_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_platformsupport_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_positioning.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_positioning_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_printsupport.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_printsupport_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_qml.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_qml_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmldevtools_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmltest.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmltest_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_qtmultimediaquicktools_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_quick.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_quick_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickparticles_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickwidgets.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickwidgets_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_script.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_script_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_scripttools.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_scripttools_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_sensors.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_sensors_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_serialport.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_serialport_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_sql.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_sql_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_svg.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_svg_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_testlib.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_testlib_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_uitools.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_uitools_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webchannel.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webchannel_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webengine.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webengine_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginecore.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginecore_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginewidgets.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginewidgets_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkit.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkit_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkitwidgets.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkitwidgets_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_websockets.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_websockets_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webview.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_webview_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_widgets.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_widgets_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_xml.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_xml_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_xmlpatterns.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/modules/qt_lib_xmlpatterns_private.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qt_functions.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qt_config.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/macx-clang/qmake.conf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/spec_post.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/qmodule.pri:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qt_build_config.prf:
/Users/Rafa/pocs/webenginepatch/qtwebengine/.qmake.conf:
/Users/Rafa/pocs/webenginepatch/qtwebengine/tools/qmake/mkspecs/features/functions.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/exclusive_builds.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/default_pre.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/mac/default_pre.prf:
/Users/Rafa/pocs/webenginepatch/qtwebengine/tools/qmake/mkspecs/features/default_pre.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qt_parts.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/resolve_config.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/default_post.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/mac/sdk.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/mac/default_post.prf:
/Users/Rafa/pocs/webenginepatch/qtwebengine/tools/qmake/mkspecs/features/default_post.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/mac/objective_c.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qml_debug.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/declarative_debug.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qt_example_installs.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/exceptions_off.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/qt_docs_targets.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/precompile_header.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/unix/largefile.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/warn_on.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/mac/rez.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/testcase_targets.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/yacc.prf:
/Users/Rafa/Qt/5.4/clang_64/mkspecs/features/lex.prf:
/Users/Rafa/pocs/webenginepatch/qtwebengine/qtwebengine.pro:
qmake: FORCE
@$(QMAKE) -spec macx-clang CONFIG+=debug CONFIG+=x86_64 CONFIG+=declarative_debug CONFIG+=qml_debug -o Makefile /Users/Rafa/pocs/webenginepatch/qtwebengine/qtwebengine.pro
qmake_all: FORCE
make_first: FORCE
all: FORCE
clean: FORCE
distclean: FORCE
-$(DEL_FILE) Makefile
install_subtargets: FORCE
uninstall_subtargets: FORCE
html_docs:
$(MAKE) -f $(MAKEFILE) prepare_docs && $(MAKE) -f $(MAKEFILE) generate_docs
docs:
$(MAKE) -f $(MAKEFILE) html_docs && $(MAKE) -f $(MAKEFILE) qch_docs
install_html_docs:
uninstall_html_docs:
install_qch_docs:
uninstall_qch_docs:
install_docs:
uninstall_docs:
qch_docs:
prepare_docs:
generate_docs:
check:
install: install_subtargets FORCE
uninstall: uninstall_subtargets FORCE
FORCE:
dist: distdir FORCE
(cd `dirname $(DISTDIR)` && $(TAR) $(DISTNAME).tar $(DISTNAME) && $(COMPRESS) $(DISTNAME).tar) && $(MOVE) `dirname $(DISTDIR)`/$(DISTNAME).tar.gz . && $(DEL_FILE) -r $(DISTDIR)
distdir: FORCE
@test -d $(DISTDIR) || mkdir -p $(DISTDIR)
$(COPY_FILE) --parents /Users/Rafa/pocs/webenginepatch/qtwebengine/.qmake.conf /Users/Rafa/pocs/webenginepatch/qtwebengine/tools/qmake/mkspecs/features/functions.prf /Users/Rafa/pocs/webenginepatch/qtwebengine/tools/qmake/mkspecs/features/default_pre.prf /Users/Rafa/pocs/webenginepatch/qtwebengine/tools/qmake/mkspecs/features/default_post.prf /Users/Rafa/pocs/webenginepatch/qtwebengine/qtwebengine.pro $(DISTDIR)/
<file_sep>/zmq-nodejs/restClient.sh
var http = require('http');
var options = {
host: 'localhost:3000',
path: '/stats'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();<file_sep>/msgpack/msgpack/main.cpp
#include "msgpack.hpp"
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main() {
// object to send....
std::string other="y";
std::vector<std::string> target;
std::string message;
while (other.compare("y")==0)
{
cout << "Input a message :" ;
getline(cin,message);
target.push_back(message);
cout << "Add other attribute ? [s/n] selected: "<< other;
getline(cin,other);
}
// Serialize it.
msgpack::sbuffer sbuf; // simple buffer
msgpack::pack(&sbuf, target);
// send the buffer over socket
// Deserialize the serialized data.
msgpack::unpacked msg; // includes memory pool and deserialized object
msgpack::unpack(msg, sbuf.data(), sbuf.size());
msgpack::object obj = msg.get();
// Print the deserialized object to stdout.
std::cout << obj << std::endl; // ["Hello," "World!"]
// Convert the deserialized object to staticaly typed object.
std::vector<std::string> result;
obj.convert(&result);
// If the type is mismatched, it throws msgpack::type_error.
// obj.as<int>(); // type is mismatched, msgpack::type_error is thrown
}
<file_sep>/websockets/websocketClient/main.cpp
#include <QtCore/QCoreApplication>
#include "echoclient.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
EchoClient client(QUrl(QStringLiteral("ws://localhost:38000")),"Test");
return a.exec();
}
<file_sep>/portScanner/main.cpp
#include "ClientSocket.h"
#include "SocketException.h"
#include <iostream>
#include <string>
int main ( int argc, char *argv[] )
{
char * hostname="jabb3r.net";
int port=5222;
char* testString="GET / \n \n";
hostent * record = gethostbyname(hostname);
if(record == NULL)
{
printf("%s is unavailable\n", argv[1]);
exit(1);
}
in_addr * address = (in_addr * )record->h_addr;
std::string ip_address = inet_ntoa(* address);
try
{
ClientSocket client_socket ( ip_address, port );
std::string reply;
try
{
client_socket << testString;
client_socket >> reply;
}
catch ( SocketException& ) {}
std::cout << "Server is Available: Header: \n\"" << reply << "\"\n";;
}
catch ( SocketException& e )
{
std::cout << "Error:" << e.description() << "\n";
}
return 0;
}
<file_sep>/websockets/websocketClient/echoclient.cpp
#include "echoclient.h"
#include <QtCore/QDebug>
QT_USE_NAMESPACE
EchoClient::EchoClient(const QUrl &url,const QString &message, QObject *parent) :
QObject(parent),
m_url(url),
m_message(message)
{
connect(&m_webSocket, &QWebSocket::connected, this, &EchoClient::onConnected);
connect(&m_webSocket, &QWebSocket::disconnected, this, &EchoClient::closed);
m_message=message;
m_webSocket.open(QUrl(url));
if (!m_webSocket.isValid())
{
qDebug() << "Failed to open the websocket";
}
}
void EchoClient::onConnected()
{
qDebug() << "WebSocket connected";
connect(&m_webSocket, &QWebSocket::textMessageReceived,
this, &EchoClient::onTextMessageReceived);
m_webSocket.sendTextMessage(m_message);
}
void EchoClient::onTextMessageReceived(QString message)
{
qDebug() << "Message received:" << message;
m_webSocket.close();
}
<file_sep>/nodejsRunner/huevonTest/README.md
# huevonTest
a [Sails](http://sailsjs.org) application
<file_sep>/nodejsRunner/nodejsrunner/nodejsrunner/main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QProcess>
#include <QDebug>
#include <QStringList>
// Node Js Runner from C++
// Running on Mac OS and Linux
#include <QRegularExpression>
#include <QDebug>
QProcess sails;
int main(int argc, char *argv[])
{
//Node JS Runner test
// For this example we assume the following:
//
// 1. Node Js installed
// 2. Sails js installed
// 3. The Sails js app installed
// A installer can install npm and sails
// Setting up the path to locate the nodejs executable
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
QStringList envlist = env.toStringList();
envlist.replaceInStrings(QRegularExpression("^(?i)PATH=(.*)"), "PATH=/usr/local/bin:$HOME/bin:\\1");
QApplication a(argc, argv);
// set the environment to the process
sails.setEnvironment(envlist);
// set the working directory, for sails, the sails app folder
sails.setWorkingDirectory("/Users/Rafa/pocs/nodejsRunner/huevonTest/");
// run the nodejs app. for this example lift sails app
sails.start("/usr/local/bin/sails lift");
//TODO: Check if is possible to sync a forever process here...
//sleep(4); // since sails is a process that start a server that runs forever wait for the start to be ready to serve the app
sails.waitForStarted();
if (sails.errorString().compare("Unknown error")!=0)
qDebug() << "Error String content:" << sails.errorString();
MainWindow w;
QObject::connect(&a, SIGNAL(aboutToQuit()), &w, SLOT(SL_Quitting()));
w.show();
return a.exec();
}
<file_sep>/protobuf/protobuff/addbookWrite.sh
clang++ main.cpp addressbook.pb.cc -o protobuf.out `pkg-config --cflags --libs protobuf`
./protobuf.out addressbook 1<file_sep>/stun/out/Makefile
#############################################################################
# Makefile for building: stunclient
# Generated by qmake (3.0) (Qt 5.4.0)
# Project: ../stunclient/stunclient.pro
# Template: app
# Command: /Users/Rafa/Qt/5.4/clang_64/bin/qmake -spec macx-clang CONFIG+=debug CONFIG+=x86_64 -o Makefile ../stunclient/stunclient.pro
#############################################################################
MAKEFILE = Makefile
####### Compiler, tools and options
CC = /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
CXX = /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++
DEFINES = -DNDEBUG
CFLAGS = -pipe -g -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk -mmacosx-version-min=10.7 -Wall -W -fPIE $(DEFINES)
CXXFLAGS = -pipe -g -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk -mmacosx-version-min=10.7 -Wall -W -fPIE $(DEFINES)
INCPATH = -I../../../Qt/5.4/clang_64/mkspecs/macx-clang -I../stunclient -I../stunclient/common -I../stunclient/stuncore -I../stunclient/resources -I../stunclient/networkutils -I../stunclient/boost -I../stunclient/openssl -I.
QMAKE = /Users/Rafa/Qt/5.4/clang_64/bin/qmake
DEL_FILE = rm -f
CHK_DIR_EXISTS= test -d
MKDIR = mkdir -p
COPY = cp -f
COPY_FILE = cp -f
COPY_DIR = cp -f -R
INSTALL_FILE = $(COPY_FILE)
INSTALL_PROGRAM = $(COPY_FILE)
INSTALL_DIR = $(COPY_DIR)
DEL_FILE = rm -f
SYMLINK = ln -f -s
DEL_DIR = rmdir
MOVE = mv -f
TAR = tar -cf
COMPRESS = gzip -9f
DISTNAME = stunclient1.0.0
DISTDIR = /Users/Rafa/poc/stun/stunclient/.tmp/stunclient1.0.0
LINK = /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++
LFLAGS = -headerpad_max_install_names -Wl,-syslibroot,/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk -mmacosx-version-min=10.7
LIBS = $(SUBLIBS) -lcrypto -lssl
AR = /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ar cq
RANLIB = /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ranlib -s
SED = sed
STRIP =
####### Output directory
OBJECTS_DIR = ./
####### Files
SOURCES = ../stunclient/clientmain.cpp \
../stunclient/common/atomichelpers.cpp \
../stunclient/common/cmdlineparser.cpp \
../stunclient/common/common.cpp \
../stunclient/common/fasthash.cpp \
../stunclient/common/getconsolewidth.cpp \
../stunclient/common/getmillisecondcounter.cpp \
../stunclient/common/logger.cpp \
../stunclient/common/prettyprint.cpp \
../stunclient/common/refcountobject.cpp \
../stunclient/common/stringhelper.cpp \
../stunclient/networkutils/adapters.cpp \
../stunclient/networkutils/polling.cpp \
../stunclient/networkutils/recvfromex.cpp \
../stunclient/networkutils/resolvehostname.cpp \
../stunclient/networkutils/stunsocket.cpp \
../stunclient/stuncore/buffer.cpp \
../stunclient/stuncore/datastream.cpp \
../stunclient/stuncore/messagehandler.cpp \
../stunclient/stuncore/socketaddress.cpp \
../stunclient/stuncore/stunbuilder.cpp \
../stunclient/stuncore/stunclientlogic.cpp \
../stunclient/stuncore/stunclienttests.cpp \
../stunclient/stuncore/stunreader.cpp \
../stunclient/stuncore/stunutils.cpp
OBJECTS = clientmain.o \
atomichelpers.o \
cmdlineparser.o \
common.o \
fasthash.o \
getconsolewidth.o \
getmillisecondcounter.o \
logger.o \
prettyprint.o \
refcountobject.o \
stringhelper.o \
adapters.o \
polling.o \
recvfromex.o \
resolvehostname.o \
stunsocket.o \
buffer.o \
datastream.o \
messagehandler.o \
socketaddress.o \
stunbuilder.o \
stunclientlogic.o \
stunclienttests.o \
stunreader.o \
stunutils.o
DIST = ../../../Qt/5.4/clang_64/mkspecs/features/spec_pre.prf \
../../../Qt/5.4/clang_64/mkspecs/qdevice.pri \
../../../Qt/5.4/clang_64/mkspecs/features/device_config.prf \
../../../Qt/5.4/clang_64/mkspecs/common/shell-unix.conf \
../../../Qt/5.4/clang_64/mkspecs/common/unix.conf \
../../../Qt/5.4/clang_64/mkspecs/common/mac.conf \
../../../Qt/5.4/clang_64/mkspecs/common/macx.conf \
../../../Qt/5.4/clang_64/mkspecs/common/gcc-base.conf \
../../../Qt/5.4/clang_64/mkspecs/common/gcc-base-mac.conf \
../../../Qt/5.4/clang_64/mkspecs/common/clang.conf \
../../../Qt/5.4/clang_64/mkspecs/common/clang-mac.conf \
../../../Qt/5.4/clang_64/mkspecs/qconfig.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_bluetooth.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_bluetooth_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_bootstrap_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_clucene_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_concurrent.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_concurrent_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_core.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_core_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_dbus.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_dbus_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_declarative.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_declarative_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_designer.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_designer_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_designercomponents_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_enginio.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_enginio_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_gui.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_gui_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_help.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_help_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_location.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_location_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_macextras.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_macextras_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimedia.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimedia_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimediawidgets.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimediawidgets_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_network.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_network_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_nfc.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_nfc_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_opengl.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_opengl_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_openglextensions.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_openglextensions_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_platformsupport_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_positioning.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_positioning_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_printsupport.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_printsupport_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qml.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qml_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmldevtools_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmltest.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmltest_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qtmultimediaquicktools_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quick.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quick_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickparticles_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickwidgets.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickwidgets_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_script.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_script_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_scripttools.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_scripttools_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_sensors.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_sensors_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_serialport.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_serialport_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_sql.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_sql_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_svg.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_svg_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_testlib.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_testlib_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_uitools.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_uitools_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webchannel.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webchannel_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webengine.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webengine_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginecore.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginecore_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginewidgets.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginewidgets_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkit.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkit_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkitwidgets.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkitwidgets_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_websockets.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_websockets_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webview.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webview_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_widgets.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_widgets_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_xml.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_xml_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_xmlpatterns.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_xmlpatterns_private.pri \
../../../Qt/5.4/clang_64/mkspecs/features/qt_functions.prf \
../../../Qt/5.4/clang_64/mkspecs/features/qt_config.prf \
../../../Qt/5.4/clang_64/mkspecs/macx-clang/qmake.conf \
../../../Qt/5.4/clang_64/mkspecs/features/spec_post.prf \
../../../Qt/5.4/clang_64/mkspecs/features/exclusive_builds.prf \
../../../Qt/5.4/clang_64/mkspecs/features/default_pre.prf \
../../../Qt/5.4/clang_64/mkspecs/features/mac/default_pre.prf \
../../../Qt/5.4/clang_64/mkspecs/features/resolve_config.prf \
../../../Qt/5.4/clang_64/mkspecs/features/default_post.prf \
../../../Qt/5.4/clang_64/mkspecs/features/mac/sdk.prf \
../../../Qt/5.4/clang_64/mkspecs/features/mac/default_post.prf \
../../../Qt/5.4/clang_64/mkspecs/features/mac/objective_c.prf \
../../../Qt/5.4/clang_64/mkspecs/features/warn_on.prf \
../../../Qt/5.4/clang_64/mkspecs/features/mac/rez.prf \
../../../Qt/5.4/clang_64/mkspecs/features/testcase_targets.prf \
../../../Qt/5.4/clang_64/mkspecs/features/exceptions.prf \
../../../Qt/5.4/clang_64/mkspecs/features/yacc.prf \
../../../Qt/5.4/clang_64/mkspecs/features/lex.prf \
../stunclient/stunclient.pro common/atomichelpers.h \
common/chkmacros.h \
common/cmdlineparser.h \
common/commonincludes.hpp \
common/fasthash.h \
common/hresult.h \
common/logger.h \
common/objectfactory.h \
common/oshelper.h \
common/prettyprint.h \
common/refcountobject.h \
common/stringhelper.h \
networkutils/adapters.h \
networkutils/polling.h \
networkutils/recvfromex.h \
networkutils/resolvehostname.h \
networkutils/stunsocket.h \
stuncore/buffer.h \
stuncore/datastream.h \
stuncore/messagehandler.h \
stuncore/socketaddress.h \
stuncore/socketrole.h \
stuncore/stunauth.h \
stuncore/stunbuilder.h \
stuncore/stunclientlogic.h \
stuncore/stunclienttests.h \
stuncore/stuncore.h \
stuncore/stunreader.h \
stuncore/stuntypes.h \
stuncore/stunutils.h ../stunclient/clientmain.cpp \
../stunclient/common/atomichelpers.cpp \
../stunclient/common/cmdlineparser.cpp \
../stunclient/common/common.cpp \
../stunclient/common/fasthash.cpp \
../stunclient/common/getconsolewidth.cpp \
../stunclient/common/getmillisecondcounter.cpp \
../stunclient/common/logger.cpp \
../stunclient/common/prettyprint.cpp \
../stunclient/common/refcountobject.cpp \
../stunclient/common/stringhelper.cpp \
../stunclient/networkutils/adapters.cpp \
../stunclient/networkutils/polling.cpp \
../stunclient/networkutils/recvfromex.cpp \
../stunclient/networkutils/resolvehostname.cpp \
../stunclient/networkutils/stunsocket.cpp \
../stunclient/stuncore/buffer.cpp \
../stunclient/stuncore/datastream.cpp \
../stunclient/stuncore/messagehandler.cpp \
../stunclient/stuncore/socketaddress.cpp \
../stunclient/stuncore/stunbuilder.cpp \
../stunclient/stuncore/stunclientlogic.cpp \
../stunclient/stuncore/stunclienttests.cpp \
../stunclient/stuncore/stunreader.cpp \
../stunclient/stuncore/stunutils.cpp
QMAKE_TARGET = stunclient
DESTDIR = #avoid trailing-slash linebreak
TARGET = stunclient
####### Custom Compiler Variables
QMAKE_COMP_QMAKE_OBJECTIVE_CFLAGS = -pipe \
-g \
-isysroot \
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk \
-mmacosx-version-min=10.7 \
-Wall \
-W
first: all
####### Implicit rules
.SUFFIXES: .o .c .cpp .cc .cxx .C
.cpp.o:
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<"
.cc.o:
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<"
.cxx.o:
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<"
.C.o:
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<"
.c.o:
$(CC) -c $(CFLAGS) $(INCPATH) -o "$@" "$<"
####### Build rules
$(TARGET): $(OBJECTS)
$(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS)
Makefile: ../stunclient/stunclient.pro ../../../Qt/5.4/clang_64/mkspecs/macx-clang/qmake.conf ../../../Qt/5.4/clang_64/mkspecs/features/spec_pre.prf \
../../../Qt/5.4/clang_64/mkspecs/qdevice.pri \
../../../Qt/5.4/clang_64/mkspecs/features/device_config.prf \
../../../Qt/5.4/clang_64/mkspecs/common/shell-unix.conf \
../../../Qt/5.4/clang_64/mkspecs/common/unix.conf \
../../../Qt/5.4/clang_64/mkspecs/common/mac.conf \
../../../Qt/5.4/clang_64/mkspecs/common/macx.conf \
../../../Qt/5.4/clang_64/mkspecs/common/gcc-base.conf \
../../../Qt/5.4/clang_64/mkspecs/common/gcc-base-mac.conf \
../../../Qt/5.4/clang_64/mkspecs/common/clang.conf \
../../../Qt/5.4/clang_64/mkspecs/common/clang-mac.conf \
../../../Qt/5.4/clang_64/mkspecs/qconfig.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_bluetooth.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_bluetooth_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_bootstrap_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_clucene_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_concurrent.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_concurrent_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_core.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_core_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_dbus.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_dbus_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_declarative.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_declarative_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_designer.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_designer_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_designercomponents_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_enginio.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_enginio_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_gui.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_gui_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_help.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_help_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_location.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_location_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_macextras.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_macextras_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimedia.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimedia_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimediawidgets.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimediawidgets_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_network.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_network_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_nfc.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_nfc_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_opengl.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_opengl_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_openglextensions.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_openglextensions_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_platformsupport_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_positioning.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_positioning_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_printsupport.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_printsupport_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qml.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qml_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmldevtools_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmltest.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmltest_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qtmultimediaquicktools_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quick.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quick_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickparticles_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickwidgets.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickwidgets_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_script.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_script_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_scripttools.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_scripttools_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_sensors.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_sensors_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_serialport.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_serialport_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_sql.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_sql_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_svg.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_svg_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_testlib.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_testlib_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_uitools.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_uitools_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webchannel.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webchannel_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webengine.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webengine_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginecore.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginecore_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginewidgets.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginewidgets_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkit.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkit_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkitwidgets.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkitwidgets_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_websockets.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_websockets_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webview.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webview_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_widgets.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_widgets_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_xml.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_xml_private.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_xmlpatterns.pri \
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_xmlpatterns_private.pri \
../../../Qt/5.4/clang_64/mkspecs/features/qt_functions.prf \
../../../Qt/5.4/clang_64/mkspecs/features/qt_config.prf \
../../../Qt/5.4/clang_64/mkspecs/macx-clang/qmake.conf \
../../../Qt/5.4/clang_64/mkspecs/features/spec_post.prf \
../../../Qt/5.4/clang_64/mkspecs/features/exclusive_builds.prf \
../../../Qt/5.4/clang_64/mkspecs/features/default_pre.prf \
../../../Qt/5.4/clang_64/mkspecs/features/mac/default_pre.prf \
../../../Qt/5.4/clang_64/mkspecs/features/resolve_config.prf \
../../../Qt/5.4/clang_64/mkspecs/features/default_post.prf \
../../../Qt/5.4/clang_64/mkspecs/features/mac/sdk.prf \
../../../Qt/5.4/clang_64/mkspecs/features/mac/default_post.prf \
../../../Qt/5.4/clang_64/mkspecs/features/mac/objective_c.prf \
../../../Qt/5.4/clang_64/mkspecs/features/warn_on.prf \
../../../Qt/5.4/clang_64/mkspecs/features/mac/rez.prf \
../../../Qt/5.4/clang_64/mkspecs/features/testcase_targets.prf \
../../../Qt/5.4/clang_64/mkspecs/features/exceptions.prf \
../../../Qt/5.4/clang_64/mkspecs/features/yacc.prf \
../../../Qt/5.4/clang_64/mkspecs/features/lex.prf \
../stunclient/stunclient.pro
$(QMAKE) -spec macx-clang CONFIG+=debug CONFIG+=x86_64 -o Makefile ../stunclient/stunclient.pro
../../../Qt/5.4/clang_64/mkspecs/features/spec_pre.prf:
../../../Qt/5.4/clang_64/mkspecs/qdevice.pri:
../../../Qt/5.4/clang_64/mkspecs/features/device_config.prf:
../../../Qt/5.4/clang_64/mkspecs/common/shell-unix.conf:
../../../Qt/5.4/clang_64/mkspecs/common/unix.conf:
../../../Qt/5.4/clang_64/mkspecs/common/mac.conf:
../../../Qt/5.4/clang_64/mkspecs/common/macx.conf:
../../../Qt/5.4/clang_64/mkspecs/common/gcc-base.conf:
../../../Qt/5.4/clang_64/mkspecs/common/gcc-base-mac.conf:
../../../Qt/5.4/clang_64/mkspecs/common/clang.conf:
../../../Qt/5.4/clang_64/mkspecs/common/clang-mac.conf:
../../../Qt/5.4/clang_64/mkspecs/qconfig.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_bluetooth.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_bluetooth_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_bootstrap_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_clucene_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_concurrent.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_concurrent_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_core.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_core_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_dbus.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_dbus_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_declarative.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_declarative_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_designer.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_designer_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_designercomponents_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_enginio.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_enginio_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_gui.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_gui_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_help.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_help_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_location.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_location_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_macextras.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_macextras_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimedia.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimedia_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimediawidgets.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_multimediawidgets_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_network.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_network_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_nfc.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_nfc_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_opengl.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_opengl_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_openglextensions.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_openglextensions_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_platformsupport_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_positioning.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_positioning_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_printsupport.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_printsupport_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qml.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qml_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmldevtools_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmltest.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qmltest_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_qtmultimediaquicktools_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quick.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quick_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickparticles_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickwidgets.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_quickwidgets_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_script.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_script_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_scripttools.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_scripttools_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_sensors.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_sensors_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_serialport.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_serialport_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_sql.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_sql_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_svg.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_svg_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_testlib.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_testlib_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_uitools.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_uitools_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webchannel.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webchannel_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webengine.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webengine_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginecore.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginecore_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginewidgets.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webenginewidgets_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkit.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkit_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkitwidgets.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webkitwidgets_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_websockets.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_websockets_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webview.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_webview_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_widgets.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_widgets_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_xml.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_xml_private.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_xmlpatterns.pri:
../../../Qt/5.4/clang_64/mkspecs/modules/qt_lib_xmlpatterns_private.pri:
../../../Qt/5.4/clang_64/mkspecs/features/qt_functions.prf:
../../../Qt/5.4/clang_64/mkspecs/features/qt_config.prf:
../../../Qt/5.4/clang_64/mkspecs/macx-clang/qmake.conf:
../../../Qt/5.4/clang_64/mkspecs/features/spec_post.prf:
../../../Qt/5.4/clang_64/mkspecs/features/exclusive_builds.prf:
../../../Qt/5.4/clang_64/mkspecs/features/default_pre.prf:
../../../Qt/5.4/clang_64/mkspecs/features/mac/default_pre.prf:
../../../Qt/5.4/clang_64/mkspecs/features/resolve_config.prf:
../../../Qt/5.4/clang_64/mkspecs/features/default_post.prf:
../../../Qt/5.4/clang_64/mkspecs/features/mac/sdk.prf:
../../../Qt/5.4/clang_64/mkspecs/features/mac/default_post.prf:
../../../Qt/5.4/clang_64/mkspecs/features/mac/objective_c.prf:
../../../Qt/5.4/clang_64/mkspecs/features/warn_on.prf:
../../../Qt/5.4/clang_64/mkspecs/features/mac/rez.prf:
../../../Qt/5.4/clang_64/mkspecs/features/testcase_targets.prf:
../../../Qt/5.4/clang_64/mkspecs/features/exceptions.prf:
../../../Qt/5.4/clang_64/mkspecs/features/yacc.prf:
../../../Qt/5.4/clang_64/mkspecs/features/lex.prf:
../stunclient/stunclient.pro:
qmake: FORCE
@$(QMAKE) -spec macx-clang CONFIG+=debug CONFIG+=x86_64 -o Makefile ../stunclient/stunclient.pro
qmake_all: FORCE
all: Makefile $(TARGET)
dist: distdir FORCE
(cd `dirname $(DISTDIR)` && $(TAR) $(DISTNAME).tar $(DISTNAME) && $(COMPRESS) $(DISTNAME).tar) && $(MOVE) `dirname $(DISTDIR)`/$(DISTNAME).tar.gz . && $(DEL_FILE) -r $(DISTDIR)
distdir: FORCE
@test -d $(DISTDIR) || mkdir -p $(DISTDIR)
$(COPY_FILE) --parents $(DIST) $(DISTDIR)/
clean:compiler_clean
-$(DEL_FILE) $(OBJECTS)
-$(DEL_FILE) *~ core *.core
distclean: clean
-$(DEL_FILE) $(TARGET)
-$(DEL_FILE) Makefile
####### Sub-libraries
check: first
compiler_objective_c_make_all:
compiler_objective_c_clean:
compiler_rez_source_make_all:
compiler_rez_source_clean:
compiler_yacc_decl_make_all:
compiler_yacc_decl_clean:
compiler_yacc_impl_make_all:
compiler_yacc_impl_clean:
compiler_lex_make_all:
compiler_lex_clean:
compiler_clean:
####### Compile
clientmain.o: ../stunclient/clientmain.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/stuncore.h \
../stunclient/stuncore/buffer.h \
../stunclient/stuncore/datastream.h \
../stunclient/stuncore/socketaddress.h \
../stunclient/stuncore/stuntypes.h \
../stunclient/stuncore/stunbuilder.h \
../stunclient/stuncore/stunreader.h \
../stunclient/common/fasthash.h \
../stunclient/stuncore/stunutils.h \
../stunclient/stuncore/messagehandler.h \
../stunclient/stuncore/stunauth.h \
../stunclient/stuncore/socketrole.h \
../stunclient/stuncore/stunclienttests.h \
../stunclient/stuncore/stunclientlogic.h \
../stunclient/networkutils/stunsocket.h \
../stunclient/common/cmdlineparser.h \
../stunclient/networkutils/recvfromex.h \
../stunclient/networkutils/resolvehostname.h \
../stunclient/common/stringhelper.h \
../stunclient/networkutils/adapters.h \
../stunclient/common/oshelper.h \
../stunclient/common/prettyprint.h \
../stunclient/resources/stunclient.txtcode \
../stunclient/resources/stunclient_lite.txtcode
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o clientmain.o ../stunclient/clientmain.cpp
atomichelpers.o: ../stunclient/common/atomichelpers.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/common/atomichelpers.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o atomichelpers.o ../stunclient/common/atomichelpers.cpp
cmdlineparser.o: ../stunclient/common/cmdlineparser.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/common/cmdlineparser.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o cmdlineparser.o ../stunclient/common/cmdlineparser.cpp
common.o: ../stunclient/common/common.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o common.o ../stunclient/common/common.cpp
fasthash.o: ../stunclient/common/fasthash.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o fasthash.o ../stunclient/common/fasthash.cpp
getconsolewidth.o: ../stunclient/common/getconsolewidth.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/common/oshelper.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o getconsolewidth.o ../stunclient/common/getconsolewidth.cpp
getmillisecondcounter.o: ../stunclient/common/getmillisecondcounter.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/common/oshelper.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o getmillisecondcounter.o ../stunclient/common/getmillisecondcounter.cpp
logger.o: ../stunclient/common/logger.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o logger.o ../stunclient/common/logger.cpp
prettyprint.o: ../stunclient/common/prettyprint.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o prettyprint.o ../stunclient/common/prettyprint.cpp
refcountobject.o: ../stunclient/common/refcountobject.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/common/atomichelpers.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o refcountobject.o ../stunclient/common/refcountobject.cpp
stringhelper.o: ../stunclient/common/stringhelper.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/common/stringhelper.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o stringhelper.o ../stunclient/common/stringhelper.cpp
adapters.o: ../stunclient/networkutils/adapters.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/socketaddress.h \
../stunclient/stuncore/stuntypes.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o adapters.o ../stunclient/networkutils/adapters.cpp
polling.o: ../stunclient/networkutils/polling.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/networkutils/polling.h \
../stunclient/common/fasthash.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o polling.o ../stunclient/networkutils/polling.cpp
recvfromex.o: ../stunclient/networkutils/recvfromex.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/socketaddress.h \
../stunclient/stuncore/stuntypes.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o recvfromex.o ../stunclient/networkutils/recvfromex.cpp
resolvehostname.o: ../stunclient/networkutils/resolvehostname.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/socketaddress.h \
../stunclient/stuncore/stuntypes.h \
../stunclient/common/stringhelper.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o resolvehostname.o ../stunclient/networkutils/resolvehostname.cpp
stunsocket.o: ../stunclient/networkutils/stunsocket.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/stuncore.h \
../stunclient/stuncore/buffer.h \
../stunclient/stuncore/datastream.h \
../stunclient/stuncore/socketaddress.h \
../stunclient/stuncore/stuntypes.h \
../stunclient/stuncore/stunbuilder.h \
../stunclient/stuncore/stunreader.h \
../stunclient/common/fasthash.h \
../stunclient/stuncore/stunutils.h \
../stunclient/stuncore/messagehandler.h \
../stunclient/stuncore/stunauth.h \
../stunclient/stuncore/socketrole.h \
../stunclient/stuncore/stunclienttests.h \
../stunclient/stuncore/stunclientlogic.h \
../stunclient/networkutils/stunsocket.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o stunsocket.o ../stunclient/networkutils/stunsocket.cpp
buffer.o: ../stunclient/stuncore/buffer.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/buffer.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o buffer.o ../stunclient/stuncore/buffer.cpp
datastream.o: ../stunclient/stuncore/datastream.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/datastream.h \
../stunclient/stuncore/buffer.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o datastream.o ../stunclient/stuncore/datastream.cpp
messagehandler.o: ../stunclient/stuncore/messagehandler.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/stuncore.h \
../stunclient/stuncore/buffer.h \
../stunclient/stuncore/datastream.h \
../stunclient/stuncore/socketaddress.h \
../stunclient/stuncore/stuntypes.h \
../stunclient/stuncore/stunbuilder.h \
../stunclient/stuncore/stunreader.h \
../stunclient/common/fasthash.h \
../stunclient/stuncore/stunutils.h \
../stunclient/stuncore/messagehandler.h \
../stunclient/stuncore/stunauth.h \
../stunclient/stuncore/socketrole.h \
../stunclient/stuncore/stunclienttests.h \
../stunclient/stuncore/stunclientlogic.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o messagehandler.o ../stunclient/stuncore/messagehandler.cpp
socketaddress.o: ../stunclient/stuncore/socketaddress.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/socketaddress.h \
../stunclient/stuncore/stuntypes.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o socketaddress.o ../stunclient/stuncore/socketaddress.cpp
stunbuilder.o: ../stunclient/stuncore/stunbuilder.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/common/stringhelper.h \
../stunclient/common/atomichelpers.h \
../stunclient/stuncore/stunbuilder.h \
../stunclient/stuncore/datastream.h \
../stunclient/stuncore/buffer.h \
../stunclient/stuncore/socketaddress.h \
../stunclient/stuncore/stuntypes.h \
../stunclient/boost/crc.hpp \
../stunclient/boost/integer.hpp \
../stunclient/boost/integer_fwd.hpp \
../stunclient/boost/limits.hpp \
../stunclient/boost/cstdint.hpp \
../stunclient/boost/integer_traits.hpp \
../stunclient/openssl/evp/evp.h \
../stunclient/openssl/opensslconf.h \
../stunclient/openssl/ossl_typ.h \
../stunclient/openssl/e_os2.h \
../stunclient/openssl/symhacks.h \
../stunclient/openssl/bio/bio.h \
../stunclient/openssl/crypto.h \
../stunclient/openssl/opensslv.h \
../stunclient/openssl/ebcdic.h \
../stunclient/openssl/md5/md5.h \
../stunclient/openssl/hmac/hmac.h \
../stunclient/stuncore/stunauth.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o stunbuilder.o ../stunclient/stuncore/stunbuilder.cpp
stunclientlogic.o: ../stunclient/stuncore/stunclientlogic.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/stuncore.h \
../stunclient/stuncore/buffer.h \
../stunclient/stuncore/datastream.h \
../stunclient/stuncore/socketaddress.h \
../stunclient/stuncore/stuntypes.h \
../stunclient/stuncore/stunbuilder.h \
../stunclient/stuncore/stunreader.h \
../stunclient/common/fasthash.h \
../stunclient/stuncore/stunutils.h \
../stunclient/stuncore/messagehandler.h \
../stunclient/stuncore/stunauth.h \
../stunclient/stuncore/socketrole.h \
../stunclient/stuncore/stunclienttests.h \
../stunclient/stuncore/stunclientlogic.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o stunclientlogic.o ../stunclient/stuncore/stunclientlogic.cpp
stunclienttests.o: ../stunclient/stuncore/stunclienttests.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/stuncore.h \
../stunclient/stuncore/buffer.h \
../stunclient/stuncore/datastream.h \
../stunclient/stuncore/socketaddress.h \
../stunclient/stuncore/stuntypes.h \
../stunclient/stuncore/stunbuilder.h \
../stunclient/stuncore/stunreader.h \
../stunclient/common/fasthash.h \
../stunclient/stuncore/stunutils.h \
../stunclient/stuncore/messagehandler.h \
../stunclient/stuncore/stunauth.h \
../stunclient/stuncore/socketrole.h \
../stunclient/stuncore/stunclienttests.h \
../stunclient/stuncore/stunclientlogic.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o stunclienttests.o ../stunclient/stuncore/stunclienttests.cpp
stunreader.o: ../stunclient/stuncore/stunreader.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/stunreader.h \
../stunclient/stuncore/stuntypes.h \
../stunclient/stuncore/datastream.h \
../stunclient/stuncore/buffer.h \
../stunclient/stuncore/socketaddress.h \
../stunclient/common/fasthash.h \
../stunclient/stuncore/stunutils.h \
../stunclient/boost/crc.hpp \
../stunclient/boost/integer.hpp \
../stunclient/boost/integer_fwd.hpp \
../stunclient/boost/limits.hpp \
../stunclient/boost/cstdint.hpp \
../stunclient/boost/integer_traits.hpp \
../stunclient/openssl/evp/evp.h \
../stunclient/openssl/opensslconf.h \
../stunclient/openssl/ossl_typ.h \
../stunclient/openssl/e_os2.h \
../stunclient/openssl/symhacks.h \
../stunclient/openssl/bio/bio.h \
../stunclient/openssl/crypto.h \
../stunclient/openssl/opensslv.h \
../stunclient/openssl/ebcdic.h \
../stunclient/openssl/hmac/hmac.h \
../stunclient/openssl/md5/md5.h \
../stunclient/stuncore/stunauth.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o stunreader.o ../stunclient/stuncore/stunreader.cpp
stunutils.o: ../stunclient/stuncore/stunutils.cpp ../stunclient/common/commonincludes.hpp \
../stunclient/boost/shared_ptr.hpp \
../stunclient/boost/smart_ptr/shared_ptr.hpp \
../stunclient/boost/config.hpp \
../stunclient/boost/config/user.hpp \
../stunclient/boost/config/select_compiler_config.hpp \
../stunclient/boost/config/compiler/nvcc.hpp \
../stunclient/boost/config/compiler/gcc_xml.hpp \
../stunclient/boost/config/compiler/cray.hpp \
../stunclient/boost/config/compiler/common_edg.hpp \
../stunclient/boost/config/compiler/comeau.hpp \
../stunclient/boost/config/compiler/pathscale.hpp \
../stunclient/boost/config/compiler/intel.hpp \
../stunclient/boost/config/compiler/clang.hpp \
../stunclient/boost/config/compiler/digitalmars.hpp \
../stunclient/boost/config/compiler/gcc.hpp \
../stunclient/boost/config/compiler/kai.hpp \
../stunclient/boost/config/compiler/sgi_mipspro.hpp \
../stunclient/boost/config/compiler/compaq_cxx.hpp \
../stunclient/boost/config/compiler/greenhills.hpp \
../stunclient/boost/config/compiler/codegear.hpp \
../stunclient/boost/config/compiler/borland.hpp \
../stunclient/boost/config/compiler/metrowerks.hpp \
../stunclient/boost/config/compiler/sunpro_cc.hpp \
../stunclient/boost/config/compiler/hp_acc.hpp \
../stunclient/boost/config/compiler/mpw.hpp \
../stunclient/boost/config/compiler/vacpp.hpp \
../stunclient/boost/config/compiler/pgi.hpp \
../stunclient/boost/config/compiler/visualc.hpp \
../stunclient/boost/config/select_stdlib_config.hpp \
../stunclient/boost/utility \
../stunclient/boost/config/stdlib/stlport.hpp \
../stunclient/boost/algorithm \
../stunclient/boost/config/stdlib/libcomo.hpp \
../stunclient/boost/config/no_tr1/utility.hpp \
../stunclient/boost/config/stdlib/roguewave.hpp \
../stunclient/boost/config/stdlib/libcpp.hpp \
../stunclient/boost/config/stdlib/libstdcpp3.hpp \
../stunclient/boost/config/stdlib/sgi.hpp \
../stunclient/boost/config/stdlib/msl.hpp \
../stunclient/boost/config/posix_features.hpp \
../stunclient/boost/config/stdlib/vacpp.hpp \
../stunclient/boost/config/stdlib/modena.hpp \
../stunclient/boost/config/stdlib/dinkumware.hpp \
../stunclient/boost/exception \
../stunclient/boost/config/select_platform_config.hpp \
../stunclient/boost/config/platform/linux.hpp \
../stunclient/boost/config/platform/bsd.hpp \
../stunclient/boost/config/platform/solaris.hpp \
../stunclient/boost/config/platform/irix.hpp \
../stunclient/boost/config/platform/hpux.hpp \
../stunclient/boost/config/platform/cygwin.hpp \
../stunclient/boost/config/platform/win32.hpp \
../stunclient/boost/config/platform/beos.hpp \
../stunclient/boost/config/platform/macos.hpp \
../stunclient/boost/config/platform/aix.hpp \
../stunclient/boost/config/platform/amigaos.hpp \
../stunclient/boost/config/platform/qnxnto.hpp \
../stunclient/boost/config/platform/vxworks.hpp \
../stunclient/boost/config/platform/symbian.hpp \
../stunclient/boost/config/platform/cray.hpp \
../stunclient/boost/config/platform/vms.hpp \
../stunclient/boost/config/suffix.hpp \
../stunclient/boost/config/no_tr1/memory.hpp \
../stunclient/boost/assert.hpp \
../stunclient/boost/current_function.hpp \
../stunclient/boost/checked_delete.hpp \
../stunclient/boost/core/checked_delete.hpp \
../stunclient/boost/throw_exception.hpp \
../stunclient/boost/detail/workaround.hpp \
../stunclient/boost/exception/exception.hpp \
../stunclient/boost/smart_ptr/detail/shared_count.hpp \
../stunclient/boost/smart_ptr/bad_weak_ptr.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base.hpp \
../stunclient/boost/smart_ptr/detail/sp_has_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_nt.hpp \
../stunclient/boost/detail/sp_typeinfo.hpp \
../stunclient/boost/core/typeinfo.hpp \
../stunclient/boost/functional \
../stunclient/boost/core/demangle.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp \
../stunclient/boost/atomic \
../stunclient/boost/smart_ptr/detail/sp_counted_base_spin.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pool.hpp \
../stunclient/boost/smart_ptr/detail/spinlock.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_std_atomic.hpp \
../stunclient/boost/smart_ptr/detail/yield_k.hpp \
../stunclient/boost/predef.h \
../stunclient/boost/predef/language.h \
../stunclient/boost/predef/language/stdc.h \
../stunclient/boost/predef/version_number.h \
../stunclient/boost/predef/make.h \
../stunclient/boost/predef/detail/test.h \
../stunclient/boost/predef/language/stdcpp.h \
../stunclient/boost/predef/language/objc.h \
../stunclient/boost/predef/architecture.h \
../stunclient/boost/predef/architecture/alpha.h \
../stunclient/boost/predef/architecture/arm.h \
../stunclient/boost/predef/architecture/blackfin.h \
../stunclient/boost/predef/architecture/convex.h \
../stunclient/boost/predef/architecture/ia64.h \
../stunclient/boost/predef/architecture/m68k.h \
../stunclient/boost/predef/architecture/mips.h \
../stunclient/boost/predef/architecture/parisc.h \
../stunclient/boost/predef/architecture/ppc.h \
../stunclient/boost/predef/architecture/pyramid.h \
../stunclient/boost/predef/architecture/rs6k.h \
../stunclient/boost/predef/architecture/sparc.h \
../stunclient/boost/predef/architecture/superh.h \
../stunclient/boost/predef/architecture/sys370.h \
../stunclient/boost/predef/architecture/sys390.h \
../stunclient/boost/predef/architecture/x86.h \
../stunclient/boost/predef/architecture/x86/32.h \
../stunclient/boost/predef/architecture/x86/64.h \
../stunclient/boost/predef/architecture/z.h \
../stunclient/boost/predef/compiler.h \
../stunclient/boost/predef/compiler/borland.h \
../stunclient/boost/predef/detail/comp_detected.h \
../stunclient/boost/predef/compiler/clang.h \
../stunclient/boost/predef/compiler/comeau.h \
../stunclient/boost/predef/compiler/compaq.h \
../stunclient/boost/predef/compiler/diab.h \
../stunclient/boost/predef/compiler/digitalmars.h \
../stunclient/boost/predef/compiler/dignus.h \
../stunclient/boost/predef/compiler/edg.h \
../stunclient/boost/predef/compiler/ekopath.h \
../stunclient/boost/predef/compiler/gcc_xml.h \
../stunclient/boost/predef/compiler/gcc.h \
../stunclient/boost/predef/compiler/greenhills.h \
../stunclient/boost/predef/compiler/hp_acc.h \
../stunclient/boost/predef/compiler/iar.h \
../stunclient/boost/predef/compiler/ibm.h \
../stunclient/boost/predef/compiler/intel.h \
../stunclient/boost/predef/compiler/kai.h \
../stunclient/boost/predef/compiler/llvm.h \
../stunclient/boost/predef/compiler/metaware.h \
../stunclient/boost/predef/compiler/metrowerks.h \
../stunclient/boost/predef/compiler/microtec.h \
../stunclient/boost/predef/compiler/mpw.h \
../stunclient/boost/predef/compiler/palm.h \
../stunclient/boost/predef/compiler/pgi.h \
../stunclient/boost/predef/compiler/sgi_mipspro.h \
../stunclient/boost/predef/compiler/sunpro.h \
../stunclient/boost/predef/compiler/tendra.h \
../stunclient/boost/predef/compiler/visualc.h \
../stunclient/boost/predef/compiler/watcom.h \
../stunclient/boost/predef/library.h \
../stunclient/boost/predef/library/c.h \
../stunclient/boost/predef/library/c/_prefix.h \
../stunclient/boost/predef/detail/_cassert.h \
../stunclient/boost/predef/library/c/gnu.h \
../stunclient/boost/predef/library/c/uc.h \
../stunclient/boost/predef/library/c/vms.h \
../stunclient/boost/predef/library/c/zos.h \
../stunclient/boost/predef/library/std.h \
../stunclient/boost/predef/library/std/_prefix.h \
../stunclient/boost/predef/detail/_exception.h \
../stunclient/boost/predef/library/std/cxx.h \
../stunclient/boost/predef/library/std/dinkumware.h \
../stunclient/boost/predef/library/std/libcomo.h \
../stunclient/boost/predef/library/std/modena.h \
../stunclient/boost/predef/library/std/msl.h \
../stunclient/boost/predef/library/std/roguewave.h \
../stunclient/boost/predef/library/std/sgi.h \
../stunclient/boost/predef/library/std/stdcpp3.h \
../stunclient/boost/predef/library/std/stlport.h \
../stunclient/boost/predef/library/std/vacpp.h \
../stunclient/boost/predef/os.h \
../stunclient/boost/predef/os/aix.h \
../stunclient/boost/predef/detail/os_detected.h \
../stunclient/boost/predef/os/amigaos.h \
../stunclient/boost/predef/os/android.h \
../stunclient/boost/predef/os/beos.h \
../stunclient/boost/predef/os/bsd.h \
../stunclient/boost/predef/os/macos.h \
../stunclient/boost/predef/os/ios.h \
../stunclient/boost/predef/os/bsd/bsdi.h \
../stunclient/boost/predef/os/bsd/dragonfly.h \
../stunclient/boost/predef/os/bsd/free.h \
../stunclient/boost/predef/os/bsd/open.h \
../stunclient/boost/predef/os/bsd/net.h \
../stunclient/boost/predef/os/cygwin.h \
../stunclient/boost/predef/os/hpux.h \
../stunclient/boost/predef/os/irix.h \
../stunclient/boost/predef/os/linux.h \
../stunclient/boost/predef/os/os400.h \
../stunclient/boost/predef/os/qnxnto.h \
../stunclient/boost/predef/os/solaris.h \
../stunclient/boost/predef/os/unix.h \
../stunclient/boost/predef/os/vms.h \
../stunclient/boost/predef/os/windows.h \
../stunclient/boost/predef/other.h \
../stunclient/boost/predef/other/endian.h \
../stunclient/boost/predef/platform.h \
../stunclient/boost/predef/platform/mingw.h \
../stunclient/boost/predef/detail/platform_detected.h \
../stunclient/boost/predef/platform/windows_desktop.h \
../stunclient/boost/predef/platform/windows_store.h \
../stunclient/boost/predef/platform/windows_phone.h \
../stunclient/boost/predef/platform/windows_runtime.h \
../stunclient/boost/thread \
../stunclient/boost/smart_ptr/detail/spinlock_sync.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_pt.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_gcc_arm.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_interlocked.hpp \
../stunclient/boost/smart_ptr/detail/spinlock_nt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_pt.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_sync.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_w32.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_base_aix.hpp \
../stunclient/boost/smart_ptr/detail/sp_counted_impl.hpp \
../stunclient/boost/smart_ptr/detail/quick_allocator.hpp \
../stunclient/boost/smart_ptr/detail/lightweight_mutex.hpp \
../stunclient/boost/smart_ptr/detail/lwm_nop.hpp \
../stunclient/boost/smart_ptr/detail/lwm_pthreads.hpp \
../stunclient/boost/smart_ptr/detail/lwm_win32_cs.hpp \
../stunclient/boost/type_traits/type_with_alignment.hpp \
../stunclient/boost/mpl/if.hpp \
../stunclient/boost/mpl/aux_/value_wknd.hpp \
../stunclient/boost/mpl/aux_/static_cast.hpp \
../stunclient/boost/mpl/aux_/config/workaround.hpp \
../stunclient/boost/mpl/aux_/config/integral.hpp \
../stunclient/boost/mpl/aux_/config/msvc.hpp \
../stunclient/boost/mpl/aux_/config/eti.hpp \
../stunclient/boost/mpl/int.hpp \
../stunclient/boost/mpl/int_fwd.hpp \
../stunclient/boost/mpl/aux_/adl_barrier.hpp \
../stunclient/boost/mpl/aux_/config/adl.hpp \
../stunclient/boost/mpl/aux_/config/intel.hpp \
../stunclient/boost/mpl/aux_/config/gcc.hpp \
../stunclient/boost/mpl/aux_/nttp_decl.hpp \
../stunclient/boost/mpl/aux_/config/nttp.hpp \
../stunclient/boost/preprocessor/cat.hpp \
../stunclient/boost/preprocessor/config/config.hpp \
../stunclient/boost/mpl/aux_/integral_wrapper.hpp \
../stunclient/boost/mpl/integral_c_tag.hpp \
../stunclient/boost/mpl/aux_/config/static_constant.hpp \
../stunclient/boost/mpl/aux_/na_spec.hpp \
../stunclient/boost/mpl/lambda_fwd.hpp \
../stunclient/boost/mpl/void_fwd.hpp \
../stunclient/boost/mpl/aux_/na.hpp \
../stunclient/boost/mpl/bool.hpp \
../stunclient/boost/mpl/bool_fwd.hpp \
../stunclient/boost/mpl/aux_/na_fwd.hpp \
../stunclient/boost/mpl/aux_/config/ctps.hpp \
../stunclient/boost/mpl/aux_/config/lambda.hpp \
../stunclient/boost/mpl/aux_/config/ttp.hpp \
../stunclient/boost/mpl/aux_/lambda_arity_param.hpp \
../stunclient/boost/mpl/aux_/template_arity_fwd.hpp \
../stunclient/boost/mpl/aux_/arity.hpp \
../stunclient/boost/mpl/aux_/config/dtp.hpp \
../stunclient/boost/mpl/aux_/preprocessor/params.hpp \
../stunclient/boost/mpl/aux_/config/preprocessor.hpp \
../stunclient/boost/preprocessor/comma_if.hpp \
../stunclient/boost/preprocessor/punctuation/comma_if.hpp \
../stunclient/boost/preprocessor/control/if.hpp \
../stunclient/boost/preprocessor/control/iif.hpp \
../stunclient/boost/preprocessor/logical/bool.hpp \
../stunclient/boost/preprocessor/facilities/empty.hpp \
../stunclient/boost/preprocessor/punctuation/comma.hpp \
../stunclient/boost/preprocessor/repeat.hpp \
../stunclient/boost/preprocessor/repetition/repeat.hpp \
../stunclient/boost/preprocessor/debug/error.hpp \
../stunclient/boost/preprocessor/detail/auto_rec.hpp \
../stunclient/boost/preprocessor/detail/dmc/auto_rec.hpp \
../stunclient/boost/preprocessor/tuple/eat.hpp \
../stunclient/boost/preprocessor/inc.hpp \
../stunclient/boost/preprocessor/arithmetic/inc.hpp \
../stunclient/boost/mpl/aux_/preprocessor/enum.hpp \
../stunclient/boost/mpl/aux_/preprocessor/def_params_tail.hpp \
../stunclient/boost/mpl/limits/arity.hpp \
../stunclient/boost/preprocessor/logical/and.hpp \
../stunclient/boost/preprocessor/logical/bitand.hpp \
../stunclient/boost/preprocessor/identity.hpp \
../stunclient/boost/preprocessor/facilities/identity.hpp \
../stunclient/boost/preprocessor/empty.hpp \
../stunclient/boost/mpl/aux_/preprocessor/filter_params.hpp \
../stunclient/boost/mpl/aux_/preprocessor/sub.hpp \
../stunclient/boost/mpl/aux_/preprocessor/tuple.hpp \
../stunclient/boost/preprocessor/arithmetic/sub.hpp \
../stunclient/boost/preprocessor/arithmetic/dec.hpp \
../stunclient/boost/preprocessor/control/while.hpp \
../stunclient/boost/preprocessor/list/fold_left.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_left.hpp \
../stunclient/boost/preprocessor/control/expr_iif.hpp \
../stunclient/boost/preprocessor/list/adt.hpp \
../stunclient/boost/preprocessor/detail/is_binary.hpp \
../stunclient/boost/preprocessor/detail/check.hpp \
../stunclient/boost/preprocessor/logical/compl.hpp \
../stunclient/boost/preprocessor/list/detail/dmc/fold_left.hpp \
../stunclient/boost/preprocessor/tuple/elem.hpp \
../stunclient/boost/preprocessor/facilities/expand.hpp \
../stunclient/boost/preprocessor/facilities/overload.hpp \
../stunclient/boost/preprocessor/variadic/size.hpp \
../stunclient/boost/preprocessor/tuple/rem.hpp \
../stunclient/boost/preprocessor/tuple/detail/is_single_return.hpp \
../stunclient/boost/preprocessor/facilities/is_1.hpp \
../stunclient/boost/preprocessor/facilities/is_empty.hpp \
../stunclient/boost/preprocessor/facilities/is_empty_variadic.hpp \
../stunclient/boost/preprocessor/punctuation/is_begin_parens.hpp \
../stunclient/boost/preprocessor/punctuation/detail/is_begin_parens.hpp \
../stunclient/boost/preprocessor/facilities/detail/is_empty.hpp \
../stunclient/boost/preprocessor/detail/split.hpp \
../stunclient/boost/preprocessor/tuple/size.hpp \
../stunclient/boost/preprocessor/variadic/elem.hpp \
../stunclient/boost/preprocessor/list/detail/fold_left.hpp \
../stunclient/boost/preprocessor/list/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/edg/fold_right.hpp \
../stunclient/boost/preprocessor/list/detail/fold_right.hpp \
../stunclient/boost/preprocessor/list/reverse.hpp \
../stunclient/boost/preprocessor/control/detail/edg/while.hpp \
../stunclient/boost/preprocessor/control/detail/msvc/while.hpp \
../stunclient/boost/preprocessor/control/detail/dmc/while.hpp \
../stunclient/boost/preprocessor/control/detail/while.hpp \
../stunclient/boost/preprocessor/arithmetic/add.hpp \
../stunclient/boost/mpl/aux_/config/overload_resolution.hpp \
../stunclient/boost/mpl/aux_/lambda_support.hpp \
../stunclient/boost/mpl/aux_/yes_no.hpp \
../stunclient/boost/mpl/aux_/config/arrays.hpp \
../stunclient/boost/preprocessor/tuple/to_list.hpp \
../stunclient/boost/preprocessor/list/for_each_i.hpp \
../stunclient/boost/preprocessor/repetition/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/edg/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/msvc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/dmc/for.hpp \
../stunclient/boost/preprocessor/repetition/detail/for.hpp \
../stunclient/boost/preprocessor/list/transform.hpp \
../stunclient/boost/preprocessor/list/append.hpp \
../stunclient/boost/type_traits/alignment_of.hpp \
../stunclient/boost/type_traits/intrinsics.hpp \
../stunclient/boost/type_traits/config.hpp \
../stunclient/boost/type_traits/is_same.hpp \
../stunclient/boost/type_traits/detail/bool_trait_def.hpp \
../stunclient/boost/type_traits/detail/template_arity_spec.hpp \
../stunclient/boost/type_traits/integral_constant.hpp \
../stunclient/boost/mpl/integral_c.hpp \
../stunclient/boost/mpl/integral_c_fwd.hpp \
../stunclient/boost/type_traits/detail/bool_trait_undef.hpp \
../stunclient/boost/type_traits/is_function.hpp \
../stunclient/boost/type_traits/is_reference.hpp \
../stunclient/boost/type_traits/is_lvalue_reference.hpp \
../stunclient/boost/type_traits/is_rvalue_reference.hpp \
../stunclient/boost/type_traits/ice.hpp \
../stunclient/boost/type_traits/detail/yes_no_type.hpp \
../stunclient/boost/type_traits/detail/ice_or.hpp \
../stunclient/boost/type_traits/detail/ice_and.hpp \
../stunclient/boost/type_traits/detail/ice_not.hpp \
../stunclient/boost/type_traits/detail/ice_eq.hpp \
../stunclient/boost/type_traits/detail/false_result.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_helper.hpp \
../stunclient/boost/preprocessor/iterate.hpp \
../stunclient/boost/preprocessor/iteration/iterate.hpp \
../stunclient/boost/preprocessor/array/elem.hpp \
../stunclient/boost/preprocessor/array/data.hpp \
../stunclient/boost/preprocessor/array/size.hpp \
../stunclient/boost/preprocessor/slot/slot.hpp \
../stunclient/boost/preprocessor/slot/detail/def.hpp \
../stunclient/boost/preprocessor/enum_params.hpp \
../stunclient/boost/preprocessor/repetition/enum_params.hpp \
../stunclient/boost/type_traits/detail/is_function_ptr_tester.hpp \
../stunclient/boost/type_traits/is_volatile.hpp \
../stunclient/boost/type_traits/detail/cv_traits_impl.hpp \
../stunclient/boost/type_traits/remove_bounds.hpp \
../stunclient/boost/type_traits/detail/type_trait_def.hpp \
../stunclient/boost/type_traits/detail/type_trait_undef.hpp \
../stunclient/boost/type_traits/is_void.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_def.hpp \
../stunclient/boost/mpl/size_t.hpp \
../stunclient/boost/mpl/size_t_fwd.hpp \
../stunclient/boost/type_traits/detail/size_t_trait_undef.hpp \
../stunclient/boost/type_traits/is_pod.hpp \
../stunclient/boost/type_traits/is_scalar.hpp \
../stunclient/boost/type_traits/is_arithmetic.hpp \
../stunclient/boost/type_traits/is_integral.hpp \
../stunclient/boost/type_traits/is_float.hpp \
../stunclient/boost/type_traits/is_enum.hpp \
../stunclient/boost/type_traits/add_reference.hpp \
../stunclient/boost/type_traits/is_convertible.hpp \
../stunclient/boost/type_traits/is_array.hpp \
../stunclient/boost/type_traits/is_abstract.hpp \
../stunclient/boost/static_assert.hpp \
../stunclient/boost/type_traits/is_class.hpp \
../stunclient/boost/type_traits/is_union.hpp \
../stunclient/boost/type_traits/remove_cv.hpp \
../stunclient/boost/type_traits/is_polymorphic.hpp \
../stunclient/boost/type_traits/add_lvalue_reference.hpp \
../stunclient/boost/type_traits/add_rvalue_reference.hpp \
../stunclient/boost/type_traits/remove_reference.hpp \
../stunclient/boost/utility/declval.hpp \
../stunclient/boost/type_traits/is_pointer.hpp \
../stunclient/boost/type_traits/is_member_pointer.hpp \
../stunclient/boost/type_traits/is_member_function_pointer.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_impl.hpp \
../stunclient/boost/type_traits/detail/is_mem_fun_pointer_tester.hpp \
../stunclient/boost/utility/addressof.hpp \
../stunclient/boost/core/addressof.hpp \
../stunclient/boost/smart_ptr/detail/sp_convertible.hpp \
../stunclient/boost/smart_ptr/detail/sp_nullptr_t.hpp \
../stunclient/boost/smart_ptr/detail/operator_bool.hpp \
../stunclient/boost/scoped_array.hpp \
../stunclient/boost/smart_ptr/scoped_array.hpp \
../stunclient/boost/scoped_ptr.hpp \
../stunclient/boost/smart_ptr/scoped_ptr.hpp \
../stunclient/common/hresult.h \
../stunclient/common/chkmacros.h \
../stunclient/common/refcountobject.h \
../stunclient/common/objectfactory.h \
../stunclient/common/logger.h \
../stunclient/stuncore/stuntypes.h \
../stunclient/stuncore/socketaddress.h \
../stunclient/stuncore/buffer.h \
../stunclient/stuncore/datastream.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o stunutils.o ../stunclient/stuncore/stunutils.cpp
####### Install
install: FORCE
uninstall: FORCE
FORCE:
<file_sep>/gloox-lib/gloox/gloox.h
#ifndef GLOOX_H
#define GLOOX_H
class Gloox
{
public:
Gloox();
};
#endif // GLOOX_H
| d95c4ed6163339d054c50a8a3ab4facd5bdf585f | [
"JavaScript",
"Markdown",
"Makefile",
"Go",
"C++",
"Shell"
] | 21 | JavaScript | jvalvert/poc | 0976576551c1bf414bfd800c5d47347664883ad2 | a889b191deac9a7ec1e74db00154cf7f02811470 | |
refs/heads/master | <file_sep>#script prints the middle rows of a file, change on line 1
# This script prints the middle rows of a file (check out this conflicting change)
# Takes arguments:
# name_of_file number_of_head_lines number of tail_lines
head -"$2" "$1" | tail -"$3"
# new comment by Ron
#this is a comment
| ad2f23f02e8445fc524eb4319dcf6a5044587294 | [
"Shell"
] | 1 | Shell | RyanA1084/software-carpentry | 96fa3188ff5f391987908eab1c624ea70b00948b | d30fb5829aefba9154dcfa19be7a851612a63b66 | |
refs/heads/master | <file_sep>import React from 'react'
import { useGrowl, Growl } from 'growl-react-component'
import './index.css'
import 'growl-react-component/dist/index.css'
function App() {
const [active, setActive] = useGrowl()
return (
<div className="app">
<header className="">
<a className="App-link" href="#" onClick={() => {
void setActive(true)
}}>
Click here to activate the growl
</a>
</header>
<Growl onDismissed={() => setActive(false)} active={active} timer={5000} message="Hello World!"/>
</div>
)
}
export default App
<file_sep># growl-react-component
> Growl React Component
[](https://www.npmjs.com/package/growl-react-component) [](https://standardjs.com)
## Install
```bash
npm install --save growl-react-component
```
## Usage
```jsx
import React, { Component } from 'react'
import {Growl, useGrowl} from 'growl-react-component'
class Example extends Component {
const [active, setActive] = useGrowl()
render() {
return
(
<Growl
onDismissed={() => setActive(false)}
active={active}
timer={5000}
message="Hello World!"
/>
)
}
}
```
## License
MIT © [PRADHAN-P](https://github.com/PRADHAN-P)
| 156e2a885a2f05afa5a402c8fa5fb45caf2e18bd | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | PRADHAN-P/growl-react-component | a380d8d9cfde35a24eb2c1098168fa68eeaab909 | 2dc4b8aed9cbe97869792e4591ca86a6f0da3c6a | |
refs/heads/master | <file_sep><section class="section about">
<div class="container about__info">
<div class="about__text-block">
<h1 class="about__title">Something about you</h1>
<div class="about__text">
<p>In this section, you can specify any information about yourself, insert your photos, your interests
and skills. It is also desirable to use tag canvas.
</p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus
error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab
illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam
voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores
eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor
sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore
et dolore magnam aliquam quaerat voluptatem.
</div>
</div>
<div class="about__photo">
<span class="about__subtitle">
Your photo
</span>
<img class="about__img" src="img/about-photo.jpg" alt="My-photo">
</div>
</div>
</section>
<file_sep>'use strict';
//slider implementation
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("js-slide");
var dots = document.getElementsByClassName("js-slider-dot");
if (n > slides.length) {
slideIndex = 1;
}
if (n < 1) {
slideIndex = slides.length;
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
(dots[i].classList.remove('active'));
}
for (i = 0; i < dots; i++) {
dots[i].className = dots[i].className.replace("active", "a");
}
slides[slideIndex - 1].style.display = "block";
(dots[slideIndex - 1].classList.add('active'));
}
//implementation of scrolls for forms
(function ($, window, document) {
$(".js-scroll").on("click", function (e) {
e.preventDefault();
var id = $(this).attr('href'),
top = $(id).offset().top;
$('html').removeClass('menu-open');
$('.js-menu-trigger').removeClass('menu-m__close');
$('body,html').animate({scrollTop: top}, 1000);
});
//implementation of the scroll in the select
$(".js-sel").selectWidget({
change: function (changes) {
return changes;
},
effect: "slide",
keyControl: true,
speed: 200,
scrollHeight: 140
});
//implementation of bar
var scrolled = false;
$(window).scroll(function(){
if (!scrolled) {
if ($(window).scrollTop() > 200) {
scrolled = true;
jQuery('.js-skillbar').each(function () {
jQuery(this).find('.js-skillbar__bar').animate({
width: jQuery(this).attr('data-percent')
}, 4000);
});
}
}
});
//Implementation of adaptive menu
$(function () {
menu.init();
});
var menu = {
$el: $('.js-menu'),
triggerClass: '.js-menu-trigger',
init: function () {
if (!this.$el.length) return;
$(this.triggerClass).on('click', this.toggle);
this.clone();
},
toggle: function () {
$('html').toggleClass('menu-open');
$('.js-menu-trigger').toggleClass('menu-m__close');
},
clone: function () {
var arr = $(".js-menu-item").sort(function (a, b) {
return ($(a).data('menu-order') - $(b).data('menu-order'));
});
$(arr).clone(true).removeClass('mobile-hide').addClass('menu-m__item').appendTo('.menu-m .container')
}
};
}(window.jQuery, window, document));
//Copyrighting year of footer
var year = new Date().getFullYear();
document.getElementById('footer__year').innerHTML = year;
<file_sep># <a href="https://yuriihavryliuk.github.io/test-mgid-pp/docs/">Test-mgid pixel perfect</a>
# How to use
Clone this repo and then in command line type:
* `npm install` or `yarn` - install all dependencies
* `gulp watch` - run dev-server and let magic happen, or
* `gulp build` - build project from sources
| 99d24a28e5e4d30845a425f25f9a9d896183278c | [
"JavaScript",
"HTML",
"Markdown"
] | 3 | HTML | YuriiHavryliuk/test-mgid-pp | 1968bcdc5d127c9e914374cd97bd7ae23408448a | 914439270ee8f52d27f0e9f0644f441a140b8bff | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Bot.Template.Community.Api.Watson.Assistant.Model
{
public class Intent
{
public string intent { get; set; }
public double confidence { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Bot.Template.Community.Api.Watson.Assistant.Model
{
public class Response
{
public Output output { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Bot.Template.Community.Api.Watson.Assistant.Model
{
public class Generic
{
public string response_type { get; set; }
public string text { get; set; }
public string title { get; set; }
public IList<Option> options { get; set; }
}
}
<file_sep>using Bot.Template.Community.Api.Watson.Assistant.Model;
using IBM.Cloud.SDK.Core.Authentication.Iam;
using IBM.Watson.Assistant.v2;
using IBM.Watson.Assistant.v2.Model;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Bot.Template.Community.Api.Watson.Assistant.Bots
{
public class WatsonBot : ActivityHandler
{
string apikey = "----";
string url = "-----";
string versionDate = "2019-02-28";
string assistantId = "----";
static string sessionId;
string inputString = "";
public WatsonBot()
{
CreateSession();
}
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
Response response = this.MessageWithContext(turnContext.Activity.Text, turnContext.Activity.Recipient.Id);
foreach (Generic resp in response.output.generic)
{
switch (resp.response_type)
{
case "text":
await turnContext.SendActivityAsync(MessageFactory.Text(response.output.generic[0].text), cancellationToken);
break;
case "option":
var reply = MessageFactory.Text(resp.title);
reply.SuggestedActions = new SuggestedActions();
reply.SuggestedActions.Actions = new List<CardAction>();
foreach (Option opt in resp.options)
{
reply.SuggestedActions.Actions.Add(new CardAction() { Title = opt.label, Type = ActionTypes.ImBack, Value = opt.label });
}
await turnContext.SendActivityAsync(reply, cancellationToken);
break;
}
}
}
protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
foreach (var member in membersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
//await turnContext.SendActivityAsync(MessageFactory.Text($"Hello and welcome!"), cancellationToken);
}
}
}
#region Sessions
public void CreateSession()
{
IamAuthenticator authenticator = new IamAuthenticator(
apikey: apikey);
AssistantService service = new AssistantService("2019-02-28", authenticator);
service.SetServiceUrl(url);
var result = service.CreateSession(
assistantId: assistantId
);
sessionId = result.Result.SessionId;
}
public void DeleteSession()
{
IamAuthenticator authenticator = new IamAuthenticator(
apikey: apikey);
AssistantService service = new AssistantService("2019-02-28", authenticator);
service.SetServiceUrl(url);
var result = service.DeleteSession(
assistantId: assistantId,
sessionId: sessionId
);
//Console.WriteLine(result.Response);
}
#endregion
#region Message with context
public Response MessageWithContext(string utterance, string userid)
{
IamAuthenticator authenticator = new IamAuthenticator(
apikey: apikey);
AssistantService service = new AssistantService("2019-02-28", authenticator);
service.SetServiceUrl(url);
MessageContextSkills skills = new MessageContextSkills();
MessageContextSkill skill = new MessageContextSkill();
skill.UserDefined = new Dictionary<string, object>();
//skill.UserDefined.Add("unidade", FUNC.unidade);
//skill.UserDefined.Add("sexo", FUNC.sexo);
//Test
skills.Add("main skill", skill);
var result = service.Message(
assistantId: assistantId,
sessionId: sessionId,
input: new MessageInput()
{
Text = utterance
},
context: new MessageContext()
{
Global = new MessageContextGlobal()
{
System = new MessageContextGlobalSystem()
{
UserId = userid
}
},
Skills = skills
}
);
Response response = JsonConvert.DeserializeObject<Response>(result.Response);
return response;
//Console.WriteLine(result.Response);
}
#endregion
}
}
<file_sep># Bot Template for Community
This repository contains a bot template to facilitate community adoption. You can find additional [SDK V4](https://github.com/Microsoft/BotBuilder-Samples/tree/master/samples) in the BotBuilder-Samples repo.
## Contributing
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Bot.Template.Community.Api.Watson.Assistant.Model
{
public class Option
{
public string label { get; set; }
public Value value { get; set; }
}
}
<file_sep>FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
WORKDIR /src
COPY ["Bot.Template.Community.Api/Bot.Template.Community.Api.csproj", "Bot.Template.Community.Api/"]
RUN dotnet restore "Bot.Template.Community.Api/Bot.Template.Community.Api.csproj"
COPY . .
WORKDIR "/src/Bot.Template.Community.Api"
RUN dotnet build "Bot.Template.Community.Api.csproj" -c Release -o /app
FROM build AS publish
RUN dotnet publish "Bot.Template.Community.Api.csproj" -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "Bot.Template.Community.Api.dll"]<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Bot.Template.Community.Api.Watson.Assistant.Model
{
public class Input
{
public string text { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Bot.Template.Community.Api.Watson.Assistant.Model
{
public class Output
{
public IList<Generic> generic { get; set; }
public IList<Intent> intents { get; set; }
public IList<object> entities { get; set; }
}
}
| 0979851df0c46421f8941e71ce07e2168dfac73e | [
"Markdown",
"C#",
"Dockerfile"
] | 9 | C# | juscelior/bot-template-community | 34b8c09be23dd9678f7a7dde3135456ee35cb0ce | d4d8ff8f0874e8e8d49cb09f85148003fd11b73e | |
refs/heads/master | <file_sep>let btn1,btn2,btn3,btn4,btnRu,btnEng,modal; //сщздание переменных
//присвоение переменным кнопок
btn1 = document.querySelector('#btn1');
btn2 = document.querySelector('#btn2');
btn3 = document.querySelector('#btn3');
btn4 = document.querySelector('#btn4');
btnRu = document.querySelector('#btnRu');
btnEng = document.querySelector('#btnEng');
modal = document.querySelector('.modal');
//функция ктороя запускается по нажатию
btn1.onclick = show;
btn2.onclick = hide;
btn3.onclick = border;
btn4.onclick = closeBorderColor;
btnRu.onclick = ruWord;
btnEng.onclick = engWord;
hide();//функция скрывающая изначально окно
function show() {
modal.hidden = false;
}
function hide() {
modal.hidden =true;
}
function border(){
modal.style.border = '15px solid green';
modal.style.borderRadius='20px';
}
function closeBorderColor() {
modal.style.border = "";
modal.style.borderRadius="";
}
function ruWord() {
var div = document.createElement("div");
div.innerHTML = "Some text with <b>bold text</b>";
}
function engWord() {
}
| 4f7df30e1658b35c554d8f87861ddd665ac98d90 | [
"JavaScript"
] | 1 | JavaScript | harut666/practiceJs | a8101ddedcde808368b02c3bcd65c2a02684c7ee | 82e341c1daf5ded212c2fa3b8660602bd4f40e6c | |
refs/heads/master | <repo_name>TrindadeThiago/quizJava<file_sep>/src/telas/Splash.java
package telas;
import static java.lang.Thread.sleep;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author 396301368
*/
public class Splash extends javax.swing.JFrame {
/**
* Creates new form VirtualQuiz
*/
public Splash() {
initComponents();
new Thread(){
public void run(){
for (int i=0;i<=101;i++){
try{
sleep(60);
jProgressBar1.setValue(i);
if(jProgressBar1.getValue()<=30){
info.setText("Iniciando o quiz ...");
}else
if (jProgressBar1.getValue()<=60){
info.setText("Abrindo e carregando o banco de dados...");
}else
if(jProgressBar1.getValue()<=90){
info.setText("Definindo questões...");
}else{
info.setText("Abertura do quiz concluída...");
}
}catch(InterruptedException ex){
}
}
question1 ig = new question1 ();
ig.setVisible(true);
dispose();
}
}.start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jProgressBar1 = new javax.swing.JProgressBar();
info = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
bg = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMaximumSize(new java.awt.Dimension(800, 600));
setMinimumSize(new java.awt.Dimension(800, 600));
setPreferredSize(new java.awt.Dimension(800, 600));
getContentPane().setLayout(null);
jLabel1.setBackground(new java.awt.Color(153, 153, 153));
jLabel1.setFont(new java.awt.Font("Arial Black", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 51));
jLabel1.setText("Quiz da Programação");
getContentPane().add(jLabel1);
jLabel1.setBounds(270, 120, 310, 50);
jLabel2.setBackground(new java.awt.Color(255, 255, 255));
jLabel2.setFont(new java.awt.Font("MS Gothic", 1, 18)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 0));
jLabel2.setText("Status:");
getContentPane().add(jLabel2);
jLabel2.setBounds(160, 490, 70, 30);
getContentPane().add(jProgressBar1);
jProgressBar1.setBounds(200, 450, 430, 30);
info.setBackground(new java.awt.Color(255, 255, 255));
info.setFont(new java.awt.Font("MS Gothic", 1, 18)); // NOI18N
info.setForeground(new java.awt.Color(255, 255, 51));
getContentPane().add(info);
info.setBounds(240, 490, 410, 30);
jLabel3.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 51));
jLabel3.setText("Instruções");
getContentPane().add(jLabel3);
jLabel3.setBounds(430, 210, 130, 40);
jLabel4.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 0));
jLabel4.setText("1) A cada acerto +10 pontos");
getContentPane().add(jLabel4);
jLabel4.setBounds(380, 240, 240, 30);
jLabel5.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 0));
jLabel5.setText("2) A cada erro -1 vida");
getContentPane().add(jLabel5);
jLabel5.setBounds(380, 260, 240, 30);
jLabel6.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 51));
jLabel6.setText("3) Ao perder todas as vidas, o jogo fecha");
getContentPane().add(jLabel6);
jLabel6.setBounds(380, 280, 330, 30);
jLabel7.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 0));
jLabel7.setText("4) Ao responder todas questão e ficar com ");
getContentPane().add(jLabel7);
jLabel7.setBounds(380, 300, 350, 30);
jLabel8.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 0));
jLabel8.setText("pelo menos uma vida, você ganha");
getContentPane().add(jLabel8);
jLabel8.setBounds(450, 320, 280, 40);
bg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/devBG.jpg"))); // NOI18N
getContentPane().add(bg);
bg.setBounds(-200, 10, 1010, 670);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Splash.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Splash().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel bg;
private javax.swing.JLabel info;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JProgressBar jProgressBar1;
// End of variables declaration//GEN-END:variables
}
| 9ca61c6ecda4668c04d069ca724a6e62c7eab09b | [
"Java"
] | 1 | Java | TrindadeThiago/quizJava | 43736da3f7a655b22c1d93c6ba7ddc688b7b9336 | 1e55c7fbbce1048c943f18a06cb8106a638a588e | |
refs/heads/master | <repo_name>mumtazahmadui/angularjs-workflows-demo<file_sep>/js/spec/category.controller.spec.js
(function(){
'use strict';
describe('Category Controller', function() {
var categoryResource,
$controller,
$q,
$timeout;
beforeEach(angular.mock.module('todo', function($provide){
$provide.service('categoryResource', function($q) {
categoryResource = {};
categoryResource.getCategories = function getCategories() {
return $q(function(fulfill, reject) {
fulfill([1, 2, 3, 4]);
});
};
sinon.spy(categoryResource, 'getCategories');
return categoryResource;
});
}));
beforeEach(inject(function(_$controller_, _$timeout_, _$q_) {
$timeout = _$timeout_;
$q = _$q_;
$controller = _$controller_('categoryCtrl');
}));
it('should get categories from a resource', function() {
categoryResource.getCategories.called.should.equal(true);
$timeout.flush(); // causes error - 'No deferred tasks to be flushed'
$controller.categories.length.should.equal(43);
});
});
}());<file_sep>/README.md
// From Pluralsight Advanced Angular Workflows
** This is AngularJS 1.5.8 **
/** NOTE - test is broken - awaiting fix **/
'No deferred tasks to be flushed'
```
// category.controller.spec.js
...
beforeEach(inject(function(_$controller_, _$timeout_, _$q_) {
$timeout = _$timeout_;
$q = _$q_;
$controller = _$controller_('categoryCtrl');
}));
it('should get categories from a resource', function() {
categoryResource.getCategories.called.should.equal(true);
$timeout.flush(); /**** causes error - 'No deferred tasks to be flushed' ****.
$controller.categories.length.should.equal(43);
});
...
```
Goals - Gulp to Automate:
1. Babel - ES6 in AngularJS
2. Validate code with JSHint
3. Unit testing with karma & Mocha, Chai for insertion framework, Sinon for mocking
4. Specifying Environment processes
// Gulp will:
* bundle, minify, sourcemap, transpile es6 with babel, watch js files
// Setup
```
$ npm init -y
$ npm install --save-dev [email protected] [email protected] [email protected] [email protected] // fronteend dependencies
$ npm install --save-dev gulp
$ npm install --save-dev gulp-load-plugins gulp-concat gulp-ugflify gulp-ngAnnotate gulp-util
$ npm install --save-dev gulp-babel babel-preset-es2015gulp-sourcemaps
$ npm install --save-dev karma mocha sinon chai karma-mocha karma-sinon karma-chai
karma-phantomjs-launcher phantomjs-prebuilt karma-koverage
$ npm install --save-dev gulp-jshint jshint jshint-stylish
$ npm install --save gulp-jshint jshint-stylish
$ npm install --save-dev yargs
```
// Create a Gulpfile
```
$ touch gulpfile.js // creates gulpfile
```
File should output as:
```
'use strict';
var gulp = require('gulp');
gulp.task('default', function(){
console.log('We are ready to go!');
})
```
// Setup JSHint
```
$ touch .jshintrc
```
Should magically output:
```
{
"curly": true,
"eqeqeq": true,
"esversion": 6,
"maxcomplexity":5,
"maxdepth":3,
"strict":true,
"predef": ["angular", "crmContactId", "console", "process", "modules", "require"]
}
Slightly modify adding the commented parts:
```
{
"curly": true,
"eqeqeq": true,
"esversion": 6,
"maxcomplexity":5,
"maxdepth":3,
"strict":true,
"validthis": true, // add
"predef": [
"angular",
"crmContactId",
"console",
"process",
"modules", // add
"require", // add
"describe", // add
"module", // add
"inject", // add
"beforeEach", // add
"sinon", // add
"it" // add
]
}
```
```
// Setup Karma, Mocha, Chai, and Sinon
```
$ karma --version
$ npm install -g karma-cli
$ npm install --s-dev karma
```
// Gulp with all goodies
```
/***** ADD LATER ***/
```
// Config Karma testing
```
$ karma init
// tab to mocha
// no - use require.js
// tab to phantom
// [Enter] through rest of defaults
```
In karma.conf.js
// add chai and sinon to frameworks
// add npm modules
```
$ npm install --save-dev mocha sinon chai karma-mocha karma-sinon karma-chai karma-phantomjs-launcher phantomjs-prebuilt jshint-stylish
```
// Code Coverage via karma-coverage and karma-remap-istanbul
Install karma-coverage as dev dependencies.
In karma.conf.js, add 'coverage' and 'karma-remap-istanbul' to reporters array.
And configure Istanbul reporter.
```
...
reporters: ['progress', 'coverage', 'karma-remap-istanbul']
// setup instanbul
remapIstanbulReporter: {
src: 'coverage/coverage.info',
reports: {
lcovonly: 'coverage.lcov.info',
html: 'coverage/html',
'text-summary': null
},
timeoutNotCreated: 5000,
timeoutNoMoreFiles: 1000
},
// write coverage.info file
coverageReporter: {
type: 'lcovonly',
subdir: '.',
dir: 'coverage/',
file: 'coverage.info'
},
...
```
View coverage page from coverage > html > index.html
In gulpfile, add preprocessor
at top of test task, add:
```
var preprocessors = {};
preprocessors[bundle] = [ 'coverage' ];
```
add preprossors key-value pair in new Karma instance
```
...
new karma.Server({
configFile: __dirname + '/karma.conf.js',
files: files,
preprocessors: preprocessors, // add
singleRun: true
}, function() {
done();
}).start();
...
```
** This cr4eats an coverage directory with coverage stats!
Setup Prod Environments
Minify if prod
```
$ gulp --prod
```
Do not minify or build sourcemaps if not prod
```
$ gulp
```
| 7e77b09f5d247247090430927823bff5a1a06b31 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | mumtazahmadui/angularjs-workflows-demo | badba52254933cca851f7d12541f989ff19bcf12 | 86be9126d8ddfbd05b1044303cd52a83cb93ca64 | |
refs/heads/master | <repo_name>no1spirite/Portfolio<file_sep>/Portfolio.Web/Extensions/WebPageExtensions.cs
namespace BibleGravy.Extensions
{
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
using RedBadger.Web.ScriptDependencyResolver;
public static class WebPageExtentions
{
public static IHtmlString WriteScriptTags(this WebViewPage page, string scriptsDirectory)
{
string appRoot = page.Context.Server.MapPath("~/").ToLower();
string scriptsPath = page.Context.Server.MapPath(scriptsDirectory);
IEnumerable<string> allScripts = EnumerateScriptFiles(appRoot, scriptsPath);
var sb = new StringBuilder();
foreach (string file in allScripts)
{
sb.AppendLine(GetScriptTag(MapToVirtualPath(page.Context, appRoot, file)));
}
return MvcHtmlString.Create(sb.ToString());
}
private static IEnumerable<string> EnumerateScriptFiles(string appRoot, string scriptsPath)
{
var resolver = new Resolver(appRoot, scriptsPath, "*.js");
return resolver.Resolve();
}
private static string GetScriptTag(string url)
{
return string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>", url);
}
private static string MapToVirtualPath(HttpContextBase context, string appRoot, string file)
{
var url = "~/" + file.Replace(appRoot, "").Replace(@"\", "/");
return UrlHelper.GenerateContentUrl(url, context);
}
}
}<file_sep>/Portfolio.Web/Global.asax.cs
namespace Portfolio.Web
{
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Windsor;
using Castle.Windsor.Installer;
using Portfolio.Web.Factories;
public class MvcApplication : HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
routes.MapRoute(
"Default",
// Route name
"{controller}/{action}/{id}",
// URL with parameters
new { controller = "Blog", action = "Blog", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ConfigureContainer();
}
private IWindsorContainer container;
private void ConfigureContainer()
{
this.container = new WindsorContainer();
var controllerFactory = new WindsorControllerFactory(this.container.Kernel);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
this.container.Install(FromAssembly.This());
}
}
}<file_sep>/Portfolio.Domain/Services/ResourceManager.cs
namespace Portfolio.Domain.Services
{
using System.Data;
using System.Data.Objects;
using System.Data.SqlClient;
using Portfolio.Domain.Data;
public class ResourceManager : IResourceManager
{
private readonly PortfolioEntities portfolioEntities;
public ResourceManager()
{
this.portfolioEntities = new PortfolioEntities();
}
public ObjectResult<T> Get<T>(IResourceManagerOptions options) where T : IDeserializable, new()
{
ObjectResult<T> results =
this.portfolioEntities.ExecuteStoreQuery<T>(
string.Format("exec {0} {1}", options.ProcedureName, this.ConvertOptions(options.Parameters)),
options.Parameters);
return results;
}
private string ConvertOptions(object[] parameters)
{
string paramString = string.Empty;
if (parameters != null)
{
int count = 1;
foreach (SqlParameter sqlParameter in parameters)
{
paramString += sqlParameter.ParameterName + (count == parameters.Length ? string.Empty : ", ")
+ (sqlParameter.Direction == ParameterDirection.Output ? " OUT" : string.Empty);
count++;
}
}
return paramString;
}
}
}<file_sep>/Portfolio.Domain/Services/IBlogService.cs
namespace Portfolio.Domain.Services
{
using System.Collections.Generic;
using Portfolio.Domain.Resources;
public interface IBlogService
{
List<Comment> PostComment(int blogId, string name, string commentText, int lastCommentId);
IList<BlogEntry> GetBlogs();
IList<Comment> GetComments(int blogId);
}
}<file_sep>/Portfolio.Web/app.js
// ~/blog.js
/// <reference path="~/Scripts/amplify.js" />
/// <reference path="~/Scripts/knockout-2.1.0.debug.js" />
/// <reference path="~/Scripts/SyntaxHighlighter/shCore.js" />
/// <reference path="~/Scripts/SyntaxHighlighter/shBrushCSharp.js" />
var Blog = function () {
var that = this;
this.blogEntries = ko.observableArray([]);
this.showComments = ko.observable(false);
$('div.blog').find('pre').addClass('brush: csharp');
$('code').contents().unwrap();
SyntaxHighlighter.highlight();
amplify.request.define("getComments", "ajax", {
url: "/blog/comments",
dataType: "html",
type: "GET",
decoder: "appEnvelope"
});
this.toggleComments = function (d, e) {
var $anchor = $(e.target);
if ($anchor.text() === 'Show comments') {
$anchor.text('Hide comments');
if (!$anchor.closest('div.blogEntryContainer').children('div.comments').get(0)) {
var blogId = $anchor.closest('li.blogEntry').data('id');
amplify.request({
resourceId: 'getComments',
data: { blogId: blogId },
success: function (comments) {
$anchor.closest('div.blogEntryContainer').append(comments);
$anchor.closest('div.blogEntryContainer').children('div.comments').show('fast');
that.showComments(true);
}
});
} else {
$anchor.closest('div.blogEntryContainer').children('div.comments').show('fast');
that.showComments(true);
}
} else {
$anchor.text('Show comments');
$anchor.closest('div.blogEntryContainer').children('div.comments').hide('fast');
that.showComments(false);
}
e.preventDefault();
};
};
// ~/comments.js
/// <reference path="~/Scripts/Amplify.js" />
/// <reference path="~/Scripts/knockout-2.1.0.js" />
/// <reference path="~/Scripts/underscore.js" />
/// <reference path="~/Scripts/dateformat.js" />
/// <reference path="~/Scripts/Custom/Blog.js" />
var Comments = function () {
var that = this;
this.commentsObservable = ko.observableArray([]);
this.name = ko.observable();
this.commentText = ko.observable();
this.canSubmit = ko.observable(true);
var result = "BlogObject" instanceof Blog;
amplify.request.define("putComment", "ajax", {
url: "/blog/putComment",
type: "PUT",
decoder: "appEnvelope"
});
this.addNewComment = function (d, e) {
amplify.request({
resourceId: 'putComment',
data: { blogId: $(d).data('id'), name: that.name(), commentText: that.commentText(),
lastCommentId: that.commentsObservable().length > 0 ? that.commentsObservable()[that.commentsObservable().length - 1].id() : 0 },
success: function (newComments) {
_.each(newComments, function (newComment) {
var regEx = /-?\d+/;
var m = regEx.exec(newComment.Date);
var formattedDate = new Date(parseInt(m[0])).format('mmm dd, yyyy "at" hh:mm TT');
that.commentsObservable.push({ id: ko.observable(newComment.Id), author: ko.observable(newComment.Author), date: ko.observable(formattedDate), commentText: ko.observable(newComment.Text) });
});
}
});
};
};
// ~/knockoutextensions.js
/// <reference path="~/Scripts/knockout-2.1.0.debug.js" />
/// <reference path="~/Scripts/jquery-1.7.2-vsdoc.js" />
/// <reference path="~/Scripts/underscore.js" />
ko.bindingHandlers.slideVisible = {
init: function (element, valueAccessor) {
var $element = $(element);
if (ko.utils.unwrapObservable(valueAccessor())) {
$element.show();
} else {
$element.hide();
}
},
update: function (element, valueAccessor) {
var $element = $(element);
if (ko.utils.unwrapObservable(valueAccessor())) {
$('body').queue(function (next) {
$element.slideDown("fast", function () {
next();
});
});
} else {
$('body').queue(function (next) {
$element.slideUp("fast", function () {
next();
});
});
}
}
};
ko.bindingHandlers['foreachPE'] = {
'init': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
function clone(obj) {
if (obj == null || typeof (obj) != 'object')
return obj;
var temp = new obj.constructor();
for (var key in obj)
temp[key] = clone(obj[key]);
return temp;
}
var observableArray = valueAccessor();
if (ko.isWriteableObservable(observableArray)) {
_.forEach($(element).children(), function (child) {
var bindingObject = {};
_.forEach($(child).find('*'), function (ancestor) {
if ($(ancestor).attr('data-bind')) {
var jsonObject = $.parseJSON("{" + $(ancestor).attr('data-bind').replace(/'/g, '"').replace(/[\(\)]/g, '"') + "}");
_.forEach(jsonObject, function (value, key) {
try {
if (key === 'click') {
$.extend(true, bindingObject, viewModel);
//bindingObject[value] = $.extend(true, viewModel[value]);
//bindingObject[value] = viewModel[value].apply(viewModel);
//bindingObject[value] = clone(viewModel[value]);
//bindingObject[value] = viewModel[value];
}
else if(key === 'visible') {
bindingObject[value] = ko.observable(true);
}
else {
bindingObject[value] = ko.observable($(ancestor)[key]());
}
} catch (e) {
console.log("foreachPE - problem handling " + key + " binding. Error: " + e);
}
});
}
});
observableArray.push(bindingObject);
});
}
var children = $(element).children();
$(element).empty();
$(element).append(children[0]);
return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
},
'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
}
};
// ~/projects.js
/// <reference path="~/Scripts/jquery.fancybox.pack.js" />
/// <reference path="~/Scripts/jquery-1.7.2-vsdoc.js" />
var Projects = function() {
$('a.fancybox').fancybox({
openEffect: 'none',
closeEffect: 'none'
});
};
// ~/blogentry.js
var BlogEntry = function (entry) {
// this.title = entry.Title;
// this.blogText = entry.Blogtext;
// this.date = entry.Date;
// this.author = entry.Author;
};
<file_sep>/Portfolio.Domain/Services/ResourceManagerOptions.cs
namespace Portfolio.Domain.Services
{
public class ResourceManagerOptions : IResourceManagerOptions
{
public object[] Parameters { get; set; }
public string ProcedureName { get; set; }
}
}<file_sep>/Portfolio.Domain/Services/IResourceManager.cs
namespace Portfolio.Domain.Services
{
using System.Data.Objects;
public interface IResourceManager
{
ObjectResult<T> Get<T>(IResourceManagerOptions options) where T : IDeserializable, new();
}
}<file_sep>/Portfolio.Domain/Services/IResourceManagerOptions.cs
namespace Portfolio.Domain.Services
{
public interface IResourceManagerOptions
{
object[] Parameters { get; set; }
string ProcedureName { get; set; }
}
}<file_sep>/Portfolio.Web/Controllers/ToolsController.cs
namespace Portfolio.Web.Controllers
{
using System.Web.Mvc;
public class ToolsController : Controller
{
public ActionResult Tools()
{
return this.View();
}
}
}<file_sep>/Portfolio.Domain/IDeserializable.cs
namespace Portfolio.Domain
{
public interface IDeserializable
{
}
}<file_sep>/Portfolio.Web/Installers/DomainAssemblyInstaller.cs
namespace Portfolio.Web.Installers
{
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using Portfolio.Domain.Services;
public class DomainAssemblyInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Component.For<IResourceManager>().ImplementedBy<ResourceManager>().LifeStyle.Transient);
container.Register(
AllTypes.FromAssemblyContaining<ResourceManager>().Where(n => n.Name.EndsWith("Service")).WithService.
FirstInterface().LifestyleTransient());
}
}
}<file_sep>/Portfolio.Domain/Services/BlogService.cs
namespace Portfolio.Domain.Services
{
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Portfolio.Domain.Resources;
public class BlogService : IBlogService
{
private readonly IResourceManager resourceManager;
public BlogService(IResourceManager resourceManager)
{
this.resourceManager = resourceManager;
}
public List<Comment> PostComment(int blogId, string name, string commentText, int lastCommentId)
{
List<Comment> results =
this.resourceManager.Get<Comment>(
new ResourceManagerOptions
{
ProcedureName = "PutComment",
Parameters =
new object[]
{
new SqlParameter("@id", blogId),
new SqlParameter("@name", name),
new SqlParameter("@commentText", commentText),
new SqlParameter("@lastCommentId", lastCommentId)
}
}).ToList();
return results;
}
public IList<BlogEntry> GetBlogs()
{
List<BlogEntry> results =
this.resourceManager.Get<BlogEntry>(new ResourceManagerOptions { ProcedureName = "GetBlogEntries" }).
ToList();
return results;
}
public IList<Comment> GetComments(int blogId)
{
List<Comment> results =
this.resourceManager.Get<Comment>(
new ResourceManagerOptions
{ ProcedureName = "GetComments", Parameters = new object[] { new SqlParameter("@id", blogId) } })
.ToList();
return results;
}
}
}<file_sep>/Portfolio.Domain/Resources/BlogEntry.cs
namespace Portfolio.Domain.Resources
{
using System;
public class BlogEntry : IDeserializable
{
public String Author { get; set; }
public String BlogText { get; set; }
public DateTime Date { get; set; }
public int Id { get; set; }
public String Title { get; set; }
public int CommentCount { get; set; }
}
}<file_sep>/Portfolio.Web/Controllers/BlogController.cs
namespace Portfolio.Web.Controllers
{
using System.Web.Mvc;
using Portfolio.Domain.Services;
public class BlogController : Controller
{
private readonly IBlogService blogService;
public BlogController(IBlogService blogService)
{
this.blogService = blogService;
}
public ActionResult Blog()
{
var md = new MarkdownSharp.Markdown();
var blogEntries = this.blogService.GetBlogs();
foreach (var blogEntry in blogEntries)
{
blogEntry.BlogText = md.Transform(blogEntry.BlogText);
blogEntry.Title = md.Transform(blogEntry.Title);
}
this.View().ViewData["blogEntries"] = blogEntries;
return this.View();
}
[HttpGet]
public ActionResult GetBlogEntries()
{
var md = new MarkdownSharp.Markdown();
var blogEntries = this.blogService.GetBlogs();
foreach (var blogEntry in blogEntries)
{
blogEntry.BlogText = md.Transform(blogEntry.BlogText);
}
JsonResult blogs = this.Json(blogEntries
, JsonRequestBehavior.AllowGet);
return blogs;
}
[HttpPut]
public ActionResult PutComment(int blogId, string name, string commentText, int lastCommentId)
{
var newComment = this.blogService.PostComment(blogId, name, commentText, lastCommentId);
JsonResult comment = this.Json(newComment
, JsonRequestBehavior.AllowGet);
return comment;
}
public ActionResult Comments(int blogId)
{
this.PartialView().ViewData["comments"] = this.blogService.GetComments(blogId);
this.PartialView().ViewData["blogId"] = blogId;
return this.PartialView();
}
}
}<file_sep>/Portfolio.Web/Modules/CustomHeaderModule.cs
namespace Portfolio.Web.Modules
{
using System;
using System.Web;
public class CustomHeaderModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.PostReleaseRequestState += this.application_PostReleaseRequestState;
}
public void Dispose()
{
}
void application_PostReleaseRequestState(object sender, EventArgs e)
{
HttpContext.Current.Response.Headers.Remove("Server");
HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
HttpContext.Current.Response.Headers.Remove("ETag");
}
}
}<file_sep>/Portfolio.Web/Installers/ControllerInstaller.cs
namespace Portfolio.Web.Installers
{
using System.Web.Mvc;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using Portfolio.Web.Controllers;
public class ControllersInstaller : IWindsorInstaller
{
/// <summary>
/// Installs the controllers
/// </summary>
/// <param name="container"></param>
/// <param name="store"></param>
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(this.FindControllers().LifestyleTransient());
}
/// <summary>
/// Find controllers within this assembly in the same namespace as HomeController
/// </summary>
/// <returns></returns>
private BasedOnDescriptor FindControllers()
{
return AllTypes.FromThisAssembly()
.BasedOn<IController>()
.If(Component.IsInSameNamespaceAs<HomeController>())
.If(t => t.Name.EndsWith("Controller"));
}
}
}<file_sep>/Portfolio.Web/Controllers/CommentController.cs
namespace Portfolio.Web.Controllers
{
using System.Web.Mvc;
public class CommentController : Controller
{
[HttpPost]
public void PostComment()
{
}
}
} | 60b7a2c2ce6dad2480a3ff42aba396596a10b6b6 | [
"JavaScript",
"C#"
] | 17 | C# | no1spirite/Portfolio | c5fa3d6322b8f7d1568432b8b5b1501b19c0e16a | db2b4ce1c4ba86dfc4400eba687a227b8683147b | |
refs/heads/master | <file_sep>class Stroll < ApplicationRecord
belongs_to :dog, optional: true
belongs_to :dogsitter, optional: true
end
<file_sep>class Dogsitter < ApplicationRecord
has_many :strolls
has_many :dogs ,through: :strolls
belongs_to :cities, optional: true
end
<file_sep>class Dog < ApplicationRecord
has_many :strolls
has_many :dogsitters ,through: :strolls
belongs_to :cities, optional: true
end
<file_sep>class AddStrollAsTableJoin < ActiveRecord::Migration[5.2]
def change
add_reference :strolls, :dog, foreign_key: true
add_reference :strolls, :dogsitter, foreign_key: true
end
end
| f2270c63f6ead3723deac316afb78dcc0f5e317a | [
"Ruby"
] | 4 | Ruby | totaotata/AirbnDog | 5b02f7372746d55933b76557459bf789d7c8478e | cc666d08f6c0475399b33b4f8e4b7c199f6f0715 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.